context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using SIL.Data;
namespace SIL.Tests.Data
{
public class PalasoChildTestItem
{
private PalasoChildTestItem _testItem;
public PalasoChildTestItem() {}
public PalasoChildTestItem(string s, int i, DateTime d)
{
StoredInt = i;
StoredString = s;
StoredDateTime = d;
}
public PalasoChildTestItem Child
{
get { return _testItem; }
set { _testItem = value; }
}
public int Depth
{
get
{
int depth = 1;
PalasoChildTestItem item = Child;
while (item != null)
{
++depth;
item = item.Child;
}
return depth;
}
}
public int StoredInt { get; set; }
public string StoredString { get; set; }
public DateTime StoredDateTime { get; set; }
}
public class PalasoTestItem: INotifyPropertyChanged
{
private int _storedInt;
private string _storedString;
private DateTime _storedDateTime;
private PalasoChildTestItem _childTestItem;
private List<string> _storedList;
private List<PalasoChildTestItem> _childItemList;
public List<PalasoChildTestItem> ChildItemList
{
get => _childItemList;
set
{
_childItemList = value;
OnPropertyChanged(new PropertyChangedEventArgs("Children"));
}
}
public int OnActivateDepth { get; private set; }
public PalasoChildTestItem Child
{
get => _childTestItem;
set
{
_childTestItem = value;
OnPropertyChanged(new PropertyChangedEventArgs("Child"));
}
}
public int Depth
{
get
{
int depth = 1;
PalasoChildTestItem item = Child;
while (item != null)
{
++depth;
item = item.Child;
}
return depth;
}
}
public PalasoTestItem()
{
_storedDateTime = PreciseDateTime.UtcNow;
_childTestItem = new PalasoChildTestItem();
}
public PalasoTestItem(string s, int i, DateTime d)
{
_storedString = s;
_storedInt = i;
_storedDateTime = d;
}
public override string ToString()
{
return $"{StoredInt}. {StoredString} {StoredDateTime}";
}
public override bool Equals(object obj)
{
return Equals(obj as PalasoTestItem);
}
public bool Equals(PalasoTestItem item)
{
if (item == null)
{
return false;
}
return _storedInt == item._storedInt && _storedString == item._storedString &&
_storedDateTime == item._storedDateTime;
}
public override int GetHashCode()
{
// https://stackoverflow.com/a/263416/487503
unchecked // Overflow is fine, just wrap
{
var hash = 31;
hash *= 23 + _storedInt.GetHashCode();
hash *= 23 + _storedString?.GetHashCode() ?? 0;
hash *= 23 + _storedDateTime.GetHashCode();
return hash;
}
}
public int StoredInt
{
get => _storedInt;
set
{
if (_storedInt == value)
return;
_storedInt = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredInt"));
}
}
public string StoredString
{
get => _storedString;
set
{
if (_storedString == value)
return;
_storedString = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredString"));
}
}
public DateTime StoredDateTime
{
get => _storedDateTime;
set
{
if (_storedDateTime == value)
return;
_storedDateTime = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredDateTime"));
}
}
public List<string> StoredList
{
get => _storedList;
set
{
_storedList = value;
OnPropertyChanged(new PropertyChangedEventArgs("StoredList"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
PropertyChanged?.Invoke(this, e);
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Microsoft.Win32;
namespace CodeToolsUpdate
{
internal class PropertyPageInfo
{
#region Fields
private readonly CodeToolInfo tool;
private readonly Guid clsid;
private readonly Guid pageid;
private readonly string category; // CommonPropertyPages | ConfigPropertyPages
private readonly List<string> projects; // projects on which to register
#endregion
#region Constructor
private PropertyPageInfo(CodeToolInfo tool, Guid clsid, Guid pageid, string _category, List<string> _projects)
{
this.tool = tool;
this.clsid = clsid;
this.pageid = pageid;
category = _category;
projects = _projects;
// sensitize data from the registry
if (category == null || category.Length == 0) category = commonPropertyPages;
if (String.Compare(category, "Common", true) == 0 || String.Compare(category, commonPropertyPages, true) == 0)
{
category = commonPropertyPages;
}
if (String.Compare(category, "Config", true) == 0 || String.Compare(category, configPropertyPages, true) == 0)
{
category = configPropertyPages;
}
if (projects == null) projects = new List<string>();
}
public override bool Equals(object obj)
{
PropertyPageInfo p = obj as PropertyPageInfo;
if (p == null) return false;
// watch out for recursion -- just check ToolName and VsRoot
if (tool.ToolName != p.tool.ToolName) return false;
if (tool.VsRoot != p.tool.VsRoot) return false;
if (clsid != p.clsid) return false;
if (pageid != p.pageid) return false;
if (category != p.category) return false;
if (projects.Count != p.projects.Count) return false;
for (int i = 0; i < projects.Count; i++)
{
if (projects[i] != p.projects[i]) return false;
}
return true;
}
public override int GetHashCode()
{
// just a simple hash
return (tool.ToolName.GetHashCode() * clsid.GetHashCode() * pageid.GetHashCode());
}
public override string ToString()
{
return (tool.DisplayName + " property page: " + pageid.ToString("B"));
}
#endregion
#region Static methods: the registry magic guids for default property pages
private const string configPropertyPages = "ConfigPropertyPages";
private const string commonPropertyPages = "CommonPropertyPages";
private const string fxcopGuid = "{984AE51A-4B21-44E7-822C-DD5E046893EF}"; // fxcop property page guid
private const string fxcopPackage = "{72391CE3-743A-4a55-8927-4217541F6517}";
private const string fxcopPackage11 = "{B20604B0-72BC-4953-BB92-95BF26D30CFA}"; // new fxcop package guid for VS2011
private static Guid fsharpProject = new Guid("{F2A71F9B-5D33-465A-A702-920D77279786}");
private static Guid csharpProject = new Guid("{FAE04EC0-301F-11d3-BF4B-00C04F79EFBC}");
private static Guid vbProject = new Guid("{F184B08F-C81C-45F6-A57F-5ABD9991F28F}");
private const string vsLoadOnSolution = "{F1536EF8-92EC-443C-9ED7-FDADF150DA82}"; // autoload key for loading on a solution load
private static bool IsFxCopInstalled(string vsRoot)
{
return (null != Common.GetLocalRegistryRoot(vsRoot, "CLSID\\" + fxcopGuid));
}
private static List<string> GetDefaultPropertyPages(string vsRoot, Guid projectId, string category)
{
List<string> defaults = new List<string>();
// C# project
if (projectId == csharpProject)
{
if (category == configPropertyPages)
{
defaults.Add("{A54AD834-9219-4AA6-B589-607AF21C3E26}"); // CBuildPropPg2Guid
defaults.Add("{6185191F-1008-4FB2-A715-3A4E4F27E610}"); // CDebugPropPg2Guid
if (IsFxCopInstalled(vsRoot)) defaults.Add(fxcopGuid);
}
else if (category == commonPropertyPages)
{
defaults.Add("{5E9A8AC2-4F34-4521-858F-4C248BA31532}"); // Application
defaults.Add("{43E38D2E-43B8-4204-8225-9357316137A4}"); // Services
defaults.Add("{031911C8-6148-4e25-B1B1-44BCA9A0C45C}"); // Reference Paths
defaults.Add("{F8D6553F-F752-4DBF-ACB6-F291B744A792}"); // Signing
defaults.Add("{1E78F8DB-6C07-4d61-A18F-7514010ABD56}"); // Build Events
// not for type libraries -- but there is no way for us to do that... :-(
defaults.Add("{DF8F7042-0BB1-47D1-8E6D-DEB3D07698BD}"); // Security
defaults.Add("{CC4014F5-B18D-439C-9352-F99D984CCA85}"); // Publish
}
}
// VB project
else if (projectId == vbProject)
{
if (category == configPropertyPages)
{
defaults.Add("{6185191F-1008-4FB2-A715-3A4E4F27E610}"); // Debug
defaults.Add("{EDA661EA-DC61-4750-B3A5-F6E9C74060F5}"); // Compile
if (IsFxCopInstalled(vsRoot)) defaults.Add(fxcopGuid);
}
else if (category == commonPropertyPages)
{
defaults.Add("{1C25D270-6E41-4360-9221-1D22E4942FAD}"); // Application
// The next entry is CVbApplicationWithMyPropPg but is auto translated from the Application guid above.
// We could use either one but the above one is most compatible at the moment.
// defaults.Add("{8998E48E-B89A-4034-B66E-353D8C1FDC2E}");
defaults.Add("{43E38D2E-43B8-4204-8225-9357316137A4}"); // Services
defaults.Add("{4E43F4AB-9F03-4129-95BF-B8FF870AF6AB}"); // References
defaults.Add("{F8D6553F-F752-4DBF-ACB6-F291B744A792}"); // Signing
defaults.Add("{F24459FC-E883-4A8E-9DA2-AEF684F0E1F4}"); // 'my extensions' prop page ??
// not for type libraries -- but there is no way for us to do that... :-(
defaults.Add("{DF8F7042-0BB1-47D1-8E6D-DEB3D07698BD}"); // Security
defaults.Add("{CC4014F5-B18D-439C-9352-F99D984CCA85}"); // Publish
}
}
// F# project
else if (projectId == fsharpProject)
{
// Yahoo: F# is additive -- no need for default pages!
}
return defaults;
}
#endregion
#region GetAssociatedProjects
/// <summary>
/// Return the projects associated with this property page
/// </summary>
/// <returns></returns>
private List<string> GetAssociatedProjects()
{
List<string> associatedProjects = new List<string>();
RegistryKey keyProjects = Common.GetLocalRegistryRoot(tool.VsRoot, "Projects");
if (keyProjects != null)
{
// Go through the projects
foreach (string project in keyProjects.GetSubKeyNames())
{
RegistryKey projectKey = keyProjects.OpenSubKey(project);
if (projectKey != null)
{
// project can be specified by guid
if (projects.Contains(NormalizeProject(project)))
{
Common.Trace("Found associated project by guid: " + tool.DisplayName + ": " + project);
associatedProjects.Add(project);
}
// or by a language name
else if (projectKey.GetValue("DefaultProjectExtension") != null)
{
string languageName = projectKey.GetValue("Language(VsTemplate)") as string;
if (languageName != null && projects.Contains(languageName))
{
Common.Trace("Found associated project by name: " + tool.DisplayName + ": " + languageName + ": " + project);
associatedProjects.Add(project);
}
}
// debug messages
else if (Common.verbose)
{
Common.Trace(" Checked project: " + project);
}
}
}
}
return associatedProjects;
}
#endregion
#region Uninstall with VS: ie. unregister from the associated VS projects
public void UnInstall()
{
try
{
// uninstall for VS projects
foreach (string project in GetAssociatedProjects())
{
VsUninstallPropertyPage(project);
}
// deregister for CodeTools
RegistryKey installKey = tool.GetInstalledPropertyPagesKey(true);
if (installKey != null)
{
installKey.DeleteSubKeyTree(pageid.ToString("B"));
}
Common.Message("Uninstalled " + tool.DisplayName + " property pages");
}
catch (Exception exn)
{
// we don't want ever want to fail on uninstall
Common.Trace("Uninstall of property pages for " + tool.DisplayName + " failed.\n" + exn.ToString());
}
}
private void VsUninstallPropertyPage(string project)
{
RegistryKey projectKey = Common.GetLocalRegistryRoot(tool.VsRoot, "Projects\\" + project, true);
if (projectKey != null)
{
RegistryKey propPagesKey = projectKey.OpenSubKey(category, true);
if (propPagesKey != null)
{
// just try to delete it
try
{
propPagesKey.DeleteSubKeyTree(pageid.ToString("B"));
}
catch { }
// remove entire node?
string[] subKeys = propPagesKey.GetSubKeyNames();
bool removeNode = (subKeys == null || subKeys.Length == 0);
if (!removeNode)
{
List<string> defaultPages = GetDefaultPropertyPages(tool.VsRoot, new Guid(project), category);
bool allDefault = true;
foreach (string subKey in subKeys)
{
if (!defaultPages.Contains(subKey))
{
allDefault = false;
break;
}
}
if (allDefault && subKeys.Length == defaultPages.Count)
{
removeNode = true;
}
}
if (removeNode)
{
// remove key completely
propPagesKey.Close();
projectKey.DeleteSubKeyTree(category);
}
// special logic for FSharp. For vs2010 we need to remove it from the user 10.0_Config too
if (tool.VsVersion >= 10.0 && new Guid(project) == fsharpProject)
{
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32))
using (RegistryKey fsharpPropPagesKey = baseKey.OpenSubKey(tool.VsRoot + "_Config\\Projects\\" + project + "\\" + category, true))
{
if (fsharpPropPagesKey != null)
{
fsharpPropPagesKey.DeleteSubKeyTree(pageid.ToString("B"));
}
}
}
}
}
// Uninstall autoload for fxcop (or it sometimes crashes)
RegistryKey autoload = Common.GetLocalRegistryRoot(tool.VsRoot, "AutoLoadPackages\\" + vsLoadOnSolution, true);
if (autoload != null)
{
if (tool.VsVersion >= 11.0)
{
if (autoload.GetValue(fxcopPackage11) != null) autoload.DeleteValue(fxcopPackage11);
// Fix registry for people that accidently got the old package here
if (autoload.GetValue(fxcopPackage) != null) autoload.DeleteValue(fxcopPackage);
}
else
{
if (autoload.GetValue(fxcopPackage) != null) autoload.DeleteValue(fxcopPackage);
}
}
Common.Trace("Uninstalled " + tool.DisplayName + " property page for " + project + " projects");
}
#endregion
#region Install with VS: ie. register with associated VS projecgts
public void Install()
{
// if (installState != InstallMode.Installed) return;
Common.Trace("Install property pane for " + tool.DisplayName);
// Install for VS
foreach (string project in GetAssociatedProjects())
{
VsInstallPropertyPage(project);
}
// Register this property page as installed
Common.Trace("Register installed property pane for " + tool.DisplayName);
RegistryKey regPagesKey = tool.GetInstalledPropertyPagesKey(true);
if (regPagesKey != null)
{
RegistryKey propPageKey = regPagesKey.CreateSubKey(pageid.ToString("B"));
if (propPageKey != null)
{
propPageKey.SetValue("clsid", clsid.ToString("B"));
propPageKey.SetValue("category", category);
RegistryKey projectsKey = propPageKey.CreateSubKey("Projects");
if (projectsKey != null)
{
foreach (string project in projects)
{
projectsKey.SetValue(project, "", RegistryValueKind.String);
}
}
}
}
Common.Message("Installed " + tool.DisplayName + " property pages");
}
private void VsInstallPropertyPage(string project)
{
RegistryKey propPagesKey = Common.GetLocalRegistryRoot(tool.VsRoot, "Projects\\" + project + "\\" + category, true);
if (propPagesKey != null)
{
string[] subKeys = propPagesKey.GetSubKeyNames();
if (subKeys == null || subKeys.Length == 0)
{
// add default pages
List<string> defaults = GetDefaultPropertyPages(tool.VsRoot, new Guid(project), category);
foreach (string defaultPage in defaults)
{
Common.Trace("project " + project + ": install default page: " + defaultPage);
RegistryKey defaultKey = propPagesKey.CreateSubKey(defaultPage);
if (defaultPage == fxcopGuid && defaultKey != null)
{
// Force page order for fxcop
defaultKey.SetValue("PageOrder", 3, RegistryValueKind.DWord);
// Force autoload for fxcop (or it sometimes crashes)
RegistryKey autoload = Common.GetLocalRegistryRoot(tool.VsRoot, "AutoLoadPackages\\" + vsLoadOnSolution, true);
if (autoload != null)
{
if (tool.VsVersion >= 11.0)
{
autoload.SetValue(fxcopPackage11, 0, RegistryValueKind.DWord);
// Fix registry for people that accidently got the old package here
if (autoload.GetValue(fxcopPackage) != null)
{
autoload.DeleteValue(fxcopPackage);
}
}
else
{
autoload.SetValue(fxcopPackage, 0, RegistryValueKind.DWord);
}
}
}
}
}
RegistryKey propPageKey = propPagesKey.CreateSubKey(pageid.ToString("B"));
if (propPageKey != null)
{
propPageKey.SetValue("", tool.DisplayName + " Property Page");
}
// special logic for FSharp. Somehow for vs2010 we need to put it in the user 10.0_Config too
if (tool.VsVersion >= 10.0 && new Guid(project) == fsharpProject)
{
using (RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry32))
{
baseKey.CreateSubKey(tool.VsRoot + "_Config\\Projects\\" + project + "\\" + category + "\\" + pageid.ToString("B"));
}
}
Common.Trace("Installed " + tool.DisplayName + " property page for " + project + " projects");
propPageKey.Close();
propPagesKey.Close();
}
}
#endregion
#region Static: read property page info from the registry
private static string NormalizeProject(string name)
{
string norm = (name == null ? "" : name.Trim());
if (!String.IsNullOrEmpty(norm) && norm[0] == '{')
{
try
{
norm = new Guid(norm).ToString("B"); // normalize guid's
}
catch { }
}
// Common.Trace("Normalized project name " + name + " to " + norm);
return norm;
}
public static PropertyPageInfo PropertyPageInfoFromRegistry(CodeToolInfo tool, RegistryKey propPagesKey, string propPage)
{
Guid propPageId = new Guid(propPage);
if (propPageId != Guid.Empty)
{
RegistryKey propPageKey = propPagesKey.OpenSubKey(propPage, false);
if (propPageKey != null)
{
string clsid = propPageKey.GetValue("clsid") as String;
if (clsid != null)
{
Guid propPaneClsid = new Guid(clsid);
if (propPaneClsid != Guid.Empty)
{
Common.Trace("Property pane found: " + propPagesKey + "\\" + clsid);
string category = propPageKey.GetValue("Category") as String;
RegistryKey projectsKey = propPageKey.OpenSubKey("Projects", false);
List<string> projects = new List<string>();
if (projectsKey != null)
{
foreach (string key in projectsKey.GetValueNames())
{
projects.Add(NormalizeProject(key));
}
}
return new PropertyPageInfo(tool, propPaneClsid, propPageId, category, projects);
}
}
}
}
return null;
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections.ObjectModel;
using System.Management.Automation.Provider;
using Dbg = System.Management.Automation;
#pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings
#pragma warning disable 56500
namespace System.Management.Automation
{
/// <summary>
/// Holds the state of a Monad Shell session.
/// </summary>
internal sealed partial class SessionStateInternal
{
#region ItemCmdletProvider accessors
#region GetItem
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The item at the specified path.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> GetItem(string[] paths, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
GetItem(paths, context);
context.ThrowFirstErrorOrDoNothing();
// Since there was not errors return the accumulated objects
Collection<PSObject> results = context.GetAccumulatedObjects();
return results;
}
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// Nothing is returned, but all objects should be written to the WriteObject
/// method of the <paramref name="context"/> parameter.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void GetItem(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
foreach (string providerPath in providerPaths)
{
GetItemPrivate(providerInstance, providerPath, context);
}
}
}
/// <summary>
/// Gets the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void GetItemPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.GetItem(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetItemProviderException",
SessionStateStrings.GetItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the get-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object GetItemDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return GetItemDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the get-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object GetItemDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.GetItemDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"GetItemDynamicParametersProviderException",
SessionStateStrings.GetItemDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion GetItem
#region SetItem
/// <summary>
/// Gets the specified object.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="value">
/// The new value for the item at the specified path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The item that was modified at the specified path.
/// </returns>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> SetItem(string[] paths, object value, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
SetItem(paths, value, context);
context.ThrowFirstErrorOrDoNothing();
// Since there was no errors return the accumulated objects
return context.GetAccumulatedObjects();
}
/// <summary>
/// Sets the specified object to the specified value.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="value">
/// The new value of the item at the specified path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void SetItem(
string[] paths,
object value,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
SetItem(providerInstance, providerPath, value, context);
}
}
}
}
/// <summary>
/// Sets item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="value">
/// The value of the item.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void SetItem(
CmdletProvider providerInstance,
string path,
object value,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.SetItem(path, value, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetItemProviderException",
SessionStateStrings.SetItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the set-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="value">
/// The new value of the item at the specified path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object SetItemDynamicParameters(string path, object value, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return SetItemDynamicParameters(providerInstance, providerPaths[0], value, newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the set-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="value">
/// The value to be set.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object SetItemDynamicParameters(
CmdletProvider providerInstance,
string path,
object value,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.SetItemDynamicParameters(path, value, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"SetItemDynamicParametersProviderException",
SessionStateStrings.SetItemDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion SetItem
#region ClearItem
/// <summary>
/// Clears the specified object. Depending on the provider that the path
/// maps to, this could mean the properties and/or content and/or value is
/// cleared.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="force">
/// Passed on to providers to force operations.
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <returns>
/// The items that were cleared.
/// </returns>
/// <remarks>
/// If an error occurs that error will be thrown.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal Collection<PSObject> ClearItem(string[] paths, bool force, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.Force = force;
context.SuppressWildcardExpansion = literalPath;
ClearItem(paths, context);
context.ThrowFirstErrorOrDoNothing();
return context.GetAccumulatedObjects();
}
/// <summary>
/// Clears the specified item. Depending on the provider that the path
/// maps to, this could mean the properties and/or content and/or value is
/// cleared.
/// </summary>
/// <param name="paths">
/// The path(s) to the object. It can be either a relative (most common)
/// or absolute path.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void ClearItem(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
ClearItemPrivate(providerInstance, providerPath, context);
}
}
}
}
/// <summary>
/// Clears the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void ClearItemPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.ClearItem(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearItemProviderException",
SessionStateStrings.ClearItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the clear-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object ClearItemDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return ClearItemDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the clear-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object ClearItemDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.ClearItemDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"ClearItemProviderException",
SessionStateStrings.ClearItemProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion ClearItem
#region InvokeDefaultAction
/// <summary>
/// Performs the default action on the specified item. The default action is
/// determined by the provider.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute path(s).
/// </param>
/// <param name="literalPath">
/// If true, globbing is not done on paths.
/// </param>
/// <remarks>
/// If an error occurs that error will be thrown.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
internal void InvokeDefaultAction(string[] paths, bool literalPath)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext);
context.SuppressWildcardExpansion = literalPath;
InvokeDefaultAction(paths, context);
context.ThrowFirstErrorOrDoNothing();
}
/// <summary>
/// Performs the default action on the specified item. The default action
/// is determined by the provider.
/// </summary>
/// <param name="paths">
/// The path(s) to the object(s). They can be either a relative (most common)
/// or absolute paths.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="ArgumentNullException">
/// If <paramref name="path"/> is null.
/// </exception>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal void InvokeDefaultAction(
string[] paths,
CmdletProviderContext context)
{
if (paths == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
foreach (string path in paths)
{
if (path == null)
{
throw PSTraceSource.NewArgumentNullException(nameof(paths));
}
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
false,
context,
out provider,
out providerInstance);
if (providerPaths != null)
{
foreach (string providerPath in providerPaths)
{
InvokeDefaultActionPrivate(providerInstance, providerPath, context);
}
}
}
}
/// <summary>
/// Invokes the default action on the item at the specified path.
/// </summary>
/// <param name="providerInstance">
/// The provider instance to use.
/// </param>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private void InvokeDefaultActionPrivate(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
try
{
itemCmdletProvider.InvokeDefaultAction(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"InvokeDefaultActionProviderException",
SessionStateStrings.InvokeDefaultActionProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
}
/// <summary>
/// Gets the dynamic parameters for the invoke-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="ProviderNotFoundException">
/// If the <paramref name="path"/> refers to a provider that could not be found.
/// </exception>
/// <exception cref="DriveNotFoundException">
/// If the <paramref name="path"/> refers to a drive that could not be found.
/// </exception>
/// <exception cref="NotSupportedException">
/// If the provider that the <paramref name="path"/> refers to does
/// not support this operation.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
/// <exception cref="ItemNotFoundException">
/// If <paramref name="path"/> does not contain glob characters and
/// could not be found.
/// </exception>
internal object InvokeDefaultActionDynamicParameters(string path, CmdletProviderContext context)
{
if (path == null)
{
return null;
}
ProviderInfo provider = null;
CmdletProvider providerInstance = null;
CmdletProviderContext newContext =
new CmdletProviderContext(context);
newContext.SetFilters(
new Collection<string>(),
new Collection<string>(),
null);
Collection<string> providerPaths =
Globber.GetGlobbedProviderPathsFromMonadPath(
path,
true,
newContext,
out provider,
out providerInstance);
if (providerPaths.Count > 0)
{
// Get the dynamic parameters for the first resolved path
return InvokeDefaultActionDynamicParameters(providerInstance, providerPaths[0], newContext);
}
return null;
}
/// <summary>
/// Gets the dynamic parameters for the invoke-item cmdlet.
/// </summary>
/// <param name="path">
/// The path to the item if it was specified on the command line.
/// </param>
/// <param name="providerInstance">
/// The instance of the provider to use.
/// </param>
/// <param name="context">
/// The context which the core command is running.
/// </param>
/// <returns>
/// An object that has properties and fields decorated with
/// parsing attributes similar to a cmdlet class.
/// </returns>
/// <exception cref="NotSupportedException">
/// If the <paramref name="providerInstance"/> does not support this operation.
/// </exception>
/// <exception cref="PipelineStoppedException">
/// If the pipeline is being stopped while executing the command.
/// </exception>
/// <exception cref="ProviderInvocationException">
/// If the provider threw an exception.
/// </exception>
private object InvokeDefaultActionDynamicParameters(
CmdletProvider providerInstance,
string path,
CmdletProviderContext context)
{
// All parameters should have been validated by caller
Dbg.Diagnostics.Assert(
providerInstance != null,
"Caller should validate providerInstance before calling this method");
Dbg.Diagnostics.Assert(
path != null,
"Caller should validate path before calling this method");
Dbg.Diagnostics.Assert(
context != null,
"Caller should validate context before calling this method");
ItemCmdletProvider itemCmdletProvider =
GetItemProviderInstance(providerInstance);
object result = null;
try
{
result = itemCmdletProvider.InvokeDefaultActionDynamicParameters(path, context);
}
catch (LoopFlowException)
{
throw;
}
catch (PipelineStoppedException)
{
throw;
}
catch (ActionPreferenceStopException)
{
throw;
}
catch (Exception e) // Catch-all OK, 3rd party callout.
{
throw NewProviderInvocationException(
"InvokeDefaultActionDynamicParametersProviderException",
SessionStateStrings.InvokeDefaultActionDynamicParametersProviderException,
itemCmdletProvider.ProviderInfo,
path,
e);
}
return result;
}
#endregion InvokeDefaultAction
#endregion ItemCmdletProvider accessors
}
}
#pragma warning restore 56500
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Sockets.Tests
{
public class SelectTest
{
private readonly ITestOutputHelper _log;
public SelectTest(ITestOutputHelper output)
{
_log = output;
}
private const int SmallTimeoutMicroseconds = 10 * 1000;
private const int FailTimeoutMicroseconds = 30 * 1000 * 1000;
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[Theory]
[InlineData(90, 0)]
[InlineData(0, 90)]
[InlineData(45, 45)]
public void Select_ReadWrite_AllReady_ManySockets(int reads, int writes)
{
Select_ReadWrite_AllReady(reads, writes);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadWrite_AllReady(int reads, int writes)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var writePairs = Enumerable.Range(0, writes).Select(_ => CreateConnectedSockets()).ToArray();
try
{
foreach (var pair in readPairs)
{
pair.Value.Send(new byte[1] { 42 });
}
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var writeList = new List<Socket>(writePairs.Select(p => p.Key).ToArray());
Socket.Select(readList, writeList, null, -1); // using -1 to test wait code path, but should complete instantly
// Since no buffers are full, all writes should be available.
Assert.Equal(writePairs.Length, writeList.Count);
// We could wake up from Select for writes even if reads are about to become available,
// so there's very little we can assert if writes is non-zero.
if (writes == 0 && reads > 0)
{
Assert.InRange(readList.Count, 1, readPairs.Length);
}
// When we do the select again, the lists shouldn't change at all, as they've already
// been filtered to ones that were ready.
int readListCountBefore = readList.Count;
int writeListCountBefore = writeList.Count;
Socket.Select(readList, writeList, null, FailTimeoutMicroseconds);
Assert.Equal(readListCountBefore, readList.Count);
Assert.Equal(writeListCountBefore, writeList.Count);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(writePairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_ReadError_NoneReady_ManySockets()
{
Select_ReadError_NoneReady(45, 45);
}
[Theory]
[InlineData(1, 0)]
[InlineData(0, 1)]
[InlineData(2, 2)]
public void Select_ReadError_NoneReady(int reads, int errors)
{
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToArray();
var errorPairs = Enumerable.Range(0, errors).Select(_ => CreateConnectedSockets()).ToArray();
try
{
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, errorList, SmallTimeoutMicroseconds);
Assert.Empty(readList);
Assert.Empty(errorList);
}
finally
{
DisposeSockets(readPairs);
DisposeSockets(errorPairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
public void Select_Read_OneReadyAtATime_ManySockets(int reads)
{
Select_Read_OneReadyAtATime(90); // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
}
[Theory]
[InlineData(2)]
public void Select_Read_OneReadyAtATime(int reads)
{
var rand = new Random(42);
var readPairs = Enumerable.Range(0, reads).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (readPairs.Count > 0)
{
int next = rand.Next(0, readPairs.Count);
readPairs[next].Value.Send(new byte[1] { 42 });
var readList = new List<Socket>(readPairs.Select(p => p.Key).ToArray());
Socket.Select(readList, null, null, FailTimeoutMicroseconds);
Assert.Equal(1, readList.Count);
Assert.Same(readPairs[next].Key, readList[0]);
readPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(readPairs);
}
}
[PlatformSpecific(~TestPlatforms.OSX)] // typical OSX install has very low max open file descriptors value
[Fact]
public void Select_Error_OneReadyAtATime()
{
const int Errors = 90; // value larger than the internal value in SocketPal.Unix that swaps between stack and heap allocation
var rand = new Random(42);
var errorPairs = Enumerable.Range(0, Errors).Select(_ => CreateConnectedSockets()).ToList();
try
{
while (errorPairs.Count > 0)
{
int next = rand.Next(0, errorPairs.Count);
errorPairs[next].Value.Send(new byte[1] { 42 }, SocketFlags.OutOfBand);
var errorList = new List<Socket>(errorPairs.Select(p => p.Key).ToArray());
Socket.Select(null, null, errorList, FailTimeoutMicroseconds);
Assert.Equal(1, errorList.Count);
Assert.Same(errorPairs[next].Key, errorList[0]);
errorPairs.RemoveAt(next);
}
}
finally
{
DisposeSockets(errorPairs);
}
}
[Theory]
[InlineData(SelectMode.SelectRead)]
[InlineData(SelectMode.SelectError)]
public void Poll_NotReady(SelectMode mode)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Assert.False(pair.Key.Poll(SmallTimeoutMicroseconds, mode));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[Theory]
[InlineData(-1)]
[InlineData(FailTimeoutMicroseconds)]
public void Poll_ReadReady_LongTimeouts(int microsecondsTimeout)
{
KeyValuePair<Socket, Socket> pair = CreateConnectedSockets();
try
{
Task.Delay(1).ContinueWith(_ => pair.Value.Send(new byte[1] { 42 }),
CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
Assert.True(pair.Key.Poll(microsecondsTimeout, SelectMode.SelectRead));
}
finally
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
private static KeyValuePair<Socket, Socket> CreateConnectedSockets()
{
using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listener.LingerState = new LingerOption(true, 0);
listener.Bind(new IPEndPoint(IPAddress.Loopback, 0));
listener.Listen(1);
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.LingerState = new LingerOption(true, 0);
Task<Socket> acceptTask = listener.AcceptAsync();
client.Connect(listener.LocalEndPoint);
Socket server = acceptTask.GetAwaiter().GetResult();
return new KeyValuePair<Socket, Socket>(client, server);
}
}
private static void DisposeSockets(IEnumerable<KeyValuePair<Socket, Socket>> sockets)
{
foreach (var pair in sockets)
{
pair.Key.Dispose();
pair.Value.Dispose();
}
}
[OuterLoop]
[Fact]
public static async Task Select_AcceptNonBlocking_Success()
{
using (Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
int port = listenSocket.BindToAnonymousPort(IPAddress.Loopback);
listenSocket.Blocking = false;
listenSocket.Listen(5);
Task t = Task.Run(() => { DoAccept(listenSocket, 5); });
// Loop, doing connections and pausing between
for (int i = 0; i < 5; i++)
{
Thread.Sleep(50);
using (Socket connectSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
connectSocket.Connect(listenSocket.LocalEndPoint);
}
}
// Give the task 5 seconds to complete; if not, assume it's hung.
await t.TimeoutAfter(5000);
}
}
public static void DoAccept(Socket listenSocket, int connectionsToAccept)
{
int connectionCount = 0;
while (true)
{
var ls = new List<Socket> { listenSocket };
Socket.Select(ls, null, null, 1000000);
if (ls.Count > 0)
{
while (true)
{
try
{
Socket s = listenSocket.Accept();
s.Close();
connectionCount++;
}
catch (SocketException e)
{
Assert.Equal(e.SocketErrorCode, SocketError.WouldBlock);
//No more requests in queue
break;
}
if (connectionCount == connectionsToAccept)
{
return;
}
}
}
}
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: MemoryErrorLog.cs addb64b2f0fa 2012-03-07 18:50:16Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using ReaderWriterLock = System.Threading.ReaderWriterLock;
using Timeout = System.Threading.Timeout;
using NameObjectCollectionBase = System.Collections.Specialized.NameObjectCollectionBase;
using IList = System.Collections.IList;
using IDictionary = System.Collections.IDictionary;
using CultureInfo = System.Globalization.CultureInfo;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses memory as its
/// backing store.
/// </summary>
/// <remarks>
/// All <see cref="MemoryErrorLog"/> instances will share the same memory
/// store that is bound to the application (not an instance of this class).
/// </remarks>
public sealed class MemoryErrorLog : ErrorLog
{
//
// The collection that provides the actual storage for this log
// implementation and a lock to guarantee concurrency correctness.
//
private static EntryCollection _entries;
private readonly static ReaderWriterLock _lock = new ReaderWriterLock();
//
// IMPORTANT! The size must be the same for all instances
// for the entires collection to be intialized correctly.
//
private readonly int _size;
/// <summary>
/// The maximum number of errors that will ever be allowed to be stored
/// in memory.
/// </summary>
public static readonly int MaximumSize = 500;
/// <summary>
/// The maximum number of errors that will be held in memory by default
/// if no size is specified.
/// </summary>
public static readonly int DefaultSize = 15;
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a default size for maximum recordable entries.
/// </summary>
public MemoryErrorLog() : this(DefaultSize) {}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// with a specific size for maximum recordable entries.
/// </summary>
public MemoryErrorLog(int size)
{
if (size < 0 || size > MaximumSize)
throw new ArgumentOutOfRangeException("size", size, string.Format("Size must be between 0 and {0}.", MaximumSize));
_size = size;
}
/// <summary>
/// Initializes a new instance of the <see cref="MemoryErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public MemoryErrorLog(IDictionary config)
{
if (config == null)
{
_size = DefaultSize;
}
else
{
string sizeString = Mask.NullString((string) config["size"]);
if (sizeString.Length == 0)
{
_size = DefaultSize;
}
else
{
_size = Convert.ToInt32(sizeString, CultureInfo.InvariantCulture);
_size = Math.Max(0, Math.Min(MaximumSize, _size));
}
}
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "In-Memory Error Log"; }
}
/// <summary>
/// Logs an error to the application memory.
/// </summary>
/// <remarks>
/// If the log is full then the oldest error entry is removed.
/// </remarks>
public override string Log(Error error)
{
if (error == null)
throw new ArgumentNullException("error");
//
// Make a copy of the error to log since the source is mutable.
// Assign a new GUID and create an entry for the error.
//
error = (Error) ((ICloneable) error).Clone();
error.ApplicationName = string.IsNullOrEmpty(error.ApplicationName) ? this.ApplicationName : error.ApplicationName;
Guid newId = Guid.NewGuid();
ErrorLogEntry entry = new ErrorLogEntry(this, newId.ToString(), error);
_lock.AcquireWriterLock(Timeout.Infinite);
try
{
if (_entries == null)
_entries = new EntryCollection(_size);
_entries.Add(entry);
}
finally
{
_lock.ReleaseWriterLock();
}
return newId.ToString();
}
/// <summary>
/// Returns the specified error from application memory, or null
/// if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
_lock.AcquireReaderLock(Timeout.Infinite);
ErrorLogEntry entry;
try
{
if (_entries == null)
return null;
entry = _entries[id];
}
finally
{
_lock.ReleaseReaderLock();
}
if (entry == null)
return null;
//
// Return a copy that the caller can party on.
//
Error error = (Error) ((ICloneable) entry.Error).Clone();
return new ErrorLogEntry(this, entry.Id, error);
}
/// <summary>
/// Returns a page of errors from the application memory in
/// descending order of logged time.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, IList errorEntryList)
{
if (pageIndex < 0)
throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0)
throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
//
// To minimize the time for which we hold the lock, we'll first
// grab just references to the entries we need to return. Later,
// we'll make copies and return those to the caller. Since Error
// is mutable, we don't want to return direct references to our
// internal versions since someone could change their state.
//
ErrorLogEntry[] selectedEntries = null;
int totalCount;
_lock.AcquireReaderLock(Timeout.Infinite);
try
{
if (_entries == null)
return 0;
totalCount = _entries.Count;
int startIndex = pageIndex * pageSize;
int endIndex = Math.Min(startIndex + pageSize, totalCount);
int count = Math.Max(0, endIndex - startIndex);
if (count > 0)
{
selectedEntries = new ErrorLogEntry[count];
int sourceIndex = endIndex;
int targetIndex = 0;
while (sourceIndex > startIndex)
selectedEntries[targetIndex++] = _entries[--sourceIndex];
}
}
finally
{
_lock.ReleaseReaderLock();
}
if (errorEntryList != null && selectedEntries != null)
{
//
// Return copies of fetched entries. If the Error class would
// be immutable then this step wouldn't be necessary.
//
foreach (ErrorLogEntry entry in selectedEntries)
{
Error error = (Error)((ICloneable)entry.Error).Clone();
errorEntryList.Add(new ErrorLogEntry(this, entry.Id, error));
}
}
return totalCount;
}
private class EntryCollection : NameObjectCollectionBase
{
private readonly int _size;
public EntryCollection(int size) : base(size)
{
_size = size;
}
public ErrorLogEntry this[int index]
{
get { return (ErrorLogEntry) BaseGet(index); }
}
public ErrorLogEntry this[Guid id]
{
get { return (ErrorLogEntry) BaseGet(id.ToString()); }
}
public ErrorLogEntry this[string id]
{
get { return this[new Guid(id)]; }
}
public void Add(ErrorLogEntry entry)
{
Debug.Assert(entry != null);
Debug.AssertStringNotEmpty(entry.Id);
Debug.Assert(this.Count <= _size);
if (this.Count == _size)
BaseRemoveAt(0);
BaseAdd(entry.Id, entry);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using Luis.MasteringExtJs.Areas.HelpPage.ModelDescriptions;
using Luis.MasteringExtJs.Areas.HelpPage.Models;
namespace Luis.MasteringExtJs.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace AttendanceServices.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/* ====================================================================
*/
using System;
using System.Xml;
using System.Text;
namespace Oranikle.Report.Engine
{
///<summary>
/// The type (dotted, solid, ...) of border. Expressions for all sides as well as default expression.
///</summary>
[Serializable]
public class StyleBorderStyle : ReportLink
{
Expression _Default; // (Enum BorderStyle) Style of the border (unless overridden for a specific side)
// Default: none
Expression _Left; // (Enum BorderStyle) Style of the left border
Expression _Right; // (Enum BorderStyle) Style of the right border
Expression _Top; // (Enum BorderStyle) Style of the top border
Expression _Bottom; // (Enum BorderStyle) Style of the bottom border
public StyleBorderStyle(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p)
{
_Default=null;
_Left=null;
_Right=null;
_Top=null;
_Bottom=null;
// Loop thru all the child nodes
foreach(XmlNode xNodeLoop in xNode.ChildNodes)
{
if (xNodeLoop.NodeType != XmlNodeType.Element)
continue;
switch (xNodeLoop.Name)
{
case "Default":
_Default = new Expression(r, this, xNodeLoop, ExpressionType.Enum);
break;
case "Left":
_Left = new Expression(r, this, xNodeLoop, ExpressionType.Enum);
break;
case "Right":
_Right = new Expression(r, this, xNodeLoop, ExpressionType.Enum);
break;
case "Top":
_Top = new Expression(r, this, xNodeLoop, ExpressionType.Enum);
break;
case "Bottom":
_Bottom = new Expression(r, this, xNodeLoop, ExpressionType.Enum);
break;
default:
// don't know this element - log it
OwnerReport.rl.LogError(4, "Unknown BorderStyle element '" + xNodeLoop.Name + "' ignored.");
break;
}
}
}
// Handle parsing of function in final pass
override public void FinalPass()
{
if (_Default != null)
_Default.FinalPass();
if (_Left != null)
_Left.FinalPass();
if (_Right != null)
_Right.FinalPass();
if (_Top != null)
_Top.FinalPass();
if (_Bottom != null)
_Bottom.FinalPass();
return;
}
// Generate a CSS string from the specified styles
public string GetCSS(Report rpt, Row row, bool bDefaults)
{
StringBuilder sb = new StringBuilder();
if (_Default != null)
sb.AppendFormat("border-style:{0};",_Default.EvaluateString(rpt, row));
else if (bDefaults)
sb.Append("border-style:none;");
if (_Left != null)
sb.AppendFormat("border-left-style:{0};",_Left.EvaluateString(rpt, row));
if (_Right != null)
sb.AppendFormat("border-right-style:{0};",_Right.EvaluateString(rpt, row));
if (_Top != null)
sb.AppendFormat("border-top-style:{0};",_Top.EvaluateString(rpt, row));
if (_Bottom != null)
sb.AppendFormat("border-bottom-style:{0};",_Bottom.EvaluateString(rpt, row));
return sb.ToString();
}
public bool IsConstant()
{
bool rc = true;
if (_Default != null)
rc = _Default.IsConstant();
if (!rc)
return false;
if (_Left != null)
rc = _Left.IsConstant();
if (!rc)
return false;
if (_Right != null)
rc = _Right.IsConstant();
if (!rc)
return false;
if (_Top != null)
rc = _Top.IsConstant();
if (!rc)
return false;
if (_Bottom != null)
rc = _Bottom.IsConstant();
return rc;
}
static public string GetCSSDefaults()
{
return "border-style:none;";
}
public Expression Default
{
get { return _Default; }
set { _Default = value; }
}
public BorderStyleEnum EvalDefault(Report rpt, Row r)
{
if (_Default == null)
return BorderStyleEnum.None;
string bs = _Default.EvaluateString(rpt, r);
return GetBorderStyle(bs, BorderStyleEnum.Solid);
}
public Expression Left
{
get { return _Left; }
set { _Left = value; }
}
public BorderStyleEnum EvalLeft(Report rpt, Row r)
{
if (_Left == null)
return EvalDefault(rpt, r);
string bs = _Left.EvaluateString(rpt, r);
return GetBorderStyle(bs, BorderStyleEnum.Solid);
}
public Expression Right
{
get { return _Right; }
set { _Right = value; }
}
public BorderStyleEnum EvalRight(Report rpt, Row r)
{
if (_Right == null)
return EvalDefault(rpt, r);
string bs = _Right.EvaluateString(rpt, r);
return GetBorderStyle(bs, BorderStyleEnum.Solid);
}
public Expression Top
{
get { return _Top; }
set { _Top = value; }
}
public BorderStyleEnum EvalTop(Report rpt, Row r)
{
if (_Top == null)
return EvalDefault(rpt, r);
string bs = _Top.EvaluateString(rpt, r);
return GetBorderStyle(bs, BorderStyleEnum.Solid);
}
public Expression Bottom
{
get { return _Bottom; }
set { _Bottom = value; }
}
public BorderStyleEnum EvalBottom(Report rpt, Row r)
{
if (_Bottom == null)
return EvalDefault(rpt, r);
string bs = _Bottom.EvaluateString(rpt, r);
return GetBorderStyle(bs, BorderStyleEnum.Solid);
}
// return the BorderStyleEnum given a particular string value
static public BorderStyleEnum GetBorderStyle(string v, BorderStyleEnum def)
{
BorderStyleEnum bs;
switch (v)
{
case "None":
bs = BorderStyleEnum.None;
break;
case "Dotted":
bs = BorderStyleEnum.Dotted;
break;
case "Dashed":
bs = BorderStyleEnum.Dashed;
break;
case "Solid":
bs = BorderStyleEnum.Solid;
break;
case "Double":
bs = BorderStyleEnum.Double;
break;
case "Groove":
bs = BorderStyleEnum.Groove;
break;
case "Ridge":
bs = BorderStyleEnum.Ridge;
break;
case "Inset":
bs = BorderStyleEnum.Inset;
break;
case "WindowInset":
bs = BorderStyleEnum.WindowInset;
break;
case "Outset":
bs = BorderStyleEnum.Outset;
break;
default:
bs = def;
break;
}
return bs;
}
}
/// <summary>
/// Allowed values for border styles. Note: these may not be actually supported depending
/// on the renderer used.
/// </summary>
public enum BorderStyleEnum
{
/// <summary>
/// No border
/// </summary>
None,
/// <summary>
/// Dotted line border
/// </summary>
Dotted,
/// <summary>
/// Dashed lin border
/// </summary>
Dashed,
/// <summary>
/// Solid line border
/// </summary>
Solid,
/// <summary>
/// Double line border
/// </summary>
Double,
/// <summary>
/// Grooved border
/// </summary>
Groove,
/// <summary>
/// Ridge border
/// </summary>
Ridge,
/// <summary>
/// Inset border
/// </summary>
Inset,
/// <summary>
/// Windows Inset border
/// </summary>
WindowInset,
/// <summary>
/// Outset border
/// </summary>
Outset
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
namespace UnityEditor.XCodeEditor
{
public partial class XCProject : System.IDisposable
{
private PBXDictionary _datastore;
public PBXDictionary _objects;
//private PBXDictionary _configurations;
private PBXGroup _rootGroup;
//private string _defaultConfigurationName;
private string _rootObjectKey;
public string projectRootPath { get; private set; }
private FileInfo projectFileInfo;
public string filePath { get; private set; }
//private string sourcePathRoot;
private bool modified = false;
#region Data
// Objects
private PBXSortedDictionary<PBXBuildFile> _buildFiles;
private PBXSortedDictionary<PBXGroup> _groups;
private PBXSortedDictionary<PBXFileReference> _fileReferences;
private PBXDictionary<PBXNativeTarget> _nativeTargets;
private PBXDictionary<PBXFrameworksBuildPhase> _frameworkBuildPhases;
private PBXDictionary<PBXResourcesBuildPhase> _resourcesBuildPhases;
private PBXDictionary<PBXShellScriptBuildPhase> _shellScriptBuildPhases;
private PBXDictionary<PBXSourcesBuildPhase> _sourcesBuildPhases;
private PBXDictionary<PBXCopyFilesBuildPhase> _copyBuildPhases;
private PBXDictionary<PBXVariantGroup> _variantGroups;
private PBXDictionary<XCBuildConfiguration> _buildConfigurations;
private PBXSortedDictionary<XCConfigurationList> _configurationLists;
private PBXProject _project;
#endregion
#region Constructor
public XCProject()
{
}
public XCProject( string filePath ) : this()
{
if( !System.IO.Directory.Exists( filePath ) ) {
Debug.LogWarning( "XCode project path does not exist: " + filePath );
return;
}
if( filePath.EndsWith( ".xcodeproj" ) ) {
Debug.Log( "Opening project " + filePath );
this.projectRootPath = Path.GetDirectoryName( filePath );
this.filePath = filePath;
} else {
Debug.Log( "Looking for xcodeproj files in " + filePath );
string[] projects = System.IO.Directory.GetDirectories( filePath, "*.xcodeproj" );
if( projects.Length == 0 ) {
Debug.LogWarning( "Error: missing xcodeproj file" );
return;
}
this.projectRootPath = filePath;
//if the path is relative to the project, we need to make it absolute
if (!System.IO.Path.IsPathRooted(projectRootPath))
projectRootPath = Application.dataPath.Replace("Assets", "") + projectRootPath;
//Debug.Log ("projectRootPath adjusted to " + projectRootPath);
this.filePath = projects[ 0 ];
}
projectFileInfo = new FileInfo( Path.Combine( this.filePath, "project.pbxproj" ) );
string contents = projectFileInfo.OpenText().ReadToEnd();
PBXParser parser = new PBXParser();
_datastore = parser.Decode( contents );
if( _datastore == null ) {
throw new System.Exception( "Project file not found at file path " + filePath );
}
if( !_datastore.ContainsKey( "objects" ) ) {
Debug.Log( "Errore " + _datastore.Count );
return;
}
_objects = (PBXDictionary)_datastore["objects"];
modified = false;
_rootObjectKey = (string)_datastore["rootObject"];
if( !string.IsNullOrEmpty( _rootObjectKey ) ) {
_project = new PBXProject( _rootObjectKey, (PBXDictionary)_objects[ _rootObjectKey ] );
_rootGroup = new PBXGroup( _rootObjectKey, (PBXDictionary)_objects[ _project.mainGroupID ] );
}
else {
Debug.LogWarning( "error: project has no root object" );
_project = null;
_rootGroup = null;
}
}
#endregion
#region Properties
public PBXProject project {
get {
return _project;
}
}
public PBXGroup rootGroup {
get {
return _rootGroup;
}
}
public PBXSortedDictionary<PBXBuildFile> buildFiles {
get {
if( _buildFiles == null ) {
_buildFiles = new PBXSortedDictionary<PBXBuildFile>( _objects );
}
return _buildFiles;
}
}
public PBXSortedDictionary<PBXGroup> groups {
get {
if( _groups == null ) {
_groups = new PBXSortedDictionary<PBXGroup>( _objects );
}
return _groups;
}
}
public PBXSortedDictionary<PBXFileReference> fileReferences {
get {
if( _fileReferences == null ) {
_fileReferences = new PBXSortedDictionary<PBXFileReference>( _objects );
}
return _fileReferences;
}
}
public PBXDictionary<PBXVariantGroup> variantGroups {
get {
if( _variantGroups == null ) {
_variantGroups = new PBXDictionary<PBXVariantGroup>( _objects );
}
return _variantGroups;
}
}
public PBXDictionary<PBXNativeTarget> nativeTargets {
get {
if( _nativeTargets == null ) {
_nativeTargets = new PBXDictionary<PBXNativeTarget>( _objects );
}
return _nativeTargets;
}
}
public PBXDictionary<XCBuildConfiguration> buildConfigurations {
get {
if( _buildConfigurations == null ) {
_buildConfigurations = new PBXDictionary<XCBuildConfiguration>( _objects );
}
return _buildConfigurations;
}
}
public PBXSortedDictionary<XCConfigurationList> configurationLists {
get {
if( _configurationLists == null ) {
_configurationLists = new PBXSortedDictionary<XCConfigurationList>( _objects );
}
return _configurationLists;
}
}
public PBXDictionary<PBXFrameworksBuildPhase> frameworkBuildPhases {
get {
if( _frameworkBuildPhases == null ) {
_frameworkBuildPhases = new PBXDictionary<PBXFrameworksBuildPhase>( _objects );
}
return _frameworkBuildPhases;
}
}
public PBXDictionary<PBXResourcesBuildPhase> resourcesBuildPhases {
get {
if( _resourcesBuildPhases == null ) {
_resourcesBuildPhases = new PBXDictionary<PBXResourcesBuildPhase>( _objects );
}
return _resourcesBuildPhases;
}
}
public PBXDictionary<PBXShellScriptBuildPhase> shellScriptBuildPhases {
get {
if( _shellScriptBuildPhases == null ) {
_shellScriptBuildPhases = new PBXDictionary<PBXShellScriptBuildPhase>( _objects );
}
return _shellScriptBuildPhases;
}
}
public PBXDictionary<PBXSourcesBuildPhase> sourcesBuildPhases {
get {
if( _sourcesBuildPhases == null ) {
_sourcesBuildPhases = new PBXDictionary<PBXSourcesBuildPhase>( _objects );
}
return _sourcesBuildPhases;
}
}
public PBXDictionary<PBXCopyFilesBuildPhase> copyBuildPhases {
get {
if( _copyBuildPhases == null ) {
_copyBuildPhases = new PBXDictionary<PBXCopyFilesBuildPhase>( _objects );
}
return _copyBuildPhases;
}
}
#endregion
#region PBXMOD
public bool AddOtherCFlags( string flag )
{
return AddOtherCFlags( new PBXList( flag ) );
}
public bool AddOtherCFlags( PBXList flags )
{
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
buildConfig.Value.AddOtherCFlags( flags );
}
modified = true;
return modified;
}
public bool AddOtherLinkerFlags( string flag )
{
return AddOtherLinkerFlags( new PBXList( flag ) );
}
public bool AddOtherLinkerFlags( PBXList flags )
{
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
buildConfig.Value.AddOtherLinkerFlags( flags );
}
modified = true;
return modified;
}
public bool overwriteBuildSetting( string settingName, string newValue, string buildConfigName = "all") {
Debug.Log("overwriteBuildSetting " + settingName + " " + newValue + " " + buildConfigName);
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
//Debug.Log ("build config " + buildConfig);
XCBuildConfiguration b = buildConfig.Value;
if ( (string)b.data["name"] == buildConfigName || (string)b.data["name"] == "all") {
//Debug.Log ("found " + buildConfigName + " config");
buildConfig.Value.overwriteBuildSetting(settingName, newValue);
modified = true;
} else {
//Debug.LogWarning ("skipping " + buildConfigName + " config " + (string)b.data["name"]);
}
}
return modified;
}
public bool AddHeaderSearchPaths( string path )
{
return AddHeaderSearchPaths( new PBXList( path ) );
}
public bool AddHeaderSearchPaths( PBXList paths )
{
Debug.Log ("AddHeaderSearchPaths " + paths);
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
buildConfig.Value.AddHeaderSearchPaths( paths );
}
modified = true;
return modified;
}
public bool AddLibrarySearchPaths( string path )
{
return AddLibrarySearchPaths( new PBXList( path ) );
}
public bool AddLibrarySearchPaths( PBXList paths )
{
Debug.Log ("AddLibrarySearchPaths " + paths);
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
buildConfig.Value.AddLibrarySearchPaths( paths );
}
modified = true;
return modified;
}
public bool AddFrameworkSearchPaths( string path )
{
return AddFrameworkSearchPaths( new PBXList( path ) );
}
public bool AddFrameworkSearchPaths( PBXList paths )
{
foreach( KeyValuePair<string, XCBuildConfiguration> buildConfig in buildConfigurations ) {
buildConfig.Value.AddFrameworkSearchPaths( paths );
}
modified = true;
return modified;
}
public object GetObject( string guid )
{
return _objects[guid];
}
public PBXDictionary AddFile( string filePath, PBXGroup parent = null, string tree = "SOURCE_ROOT", bool createBuildFiles = true, bool weak = false )
{
//Debug.Log("AddFile " + filePath + ", " + parent + ", " + tree + ", " + (createBuildFiles? "TRUE":"FALSE") + ", " + (weak? "TRUE":"FALSE") );
PBXDictionary results = new PBXDictionary();
if (filePath == null) {
Debug.LogError ("AddFile called with null filePath");
return results;
}
string absPath = string.Empty;
if( Path.IsPathRooted( filePath ) ) {
Debug.Log( "Path is Rooted" );
absPath = filePath;
}
else if( tree.CompareTo( "SDKROOT" ) != 0) {
absPath = Path.Combine( Application.dataPath, filePath );
}
if( !( File.Exists( absPath ) || Directory.Exists( absPath ) ) && tree.CompareTo( "SDKROOT" ) != 0 ) {
Debug.Log( "Missing file: " + filePath );
return results;
}
else if( tree.CompareTo( "SOURCE_ROOT" ) == 0 ) {
Debug.Log( "Source Root File" );
System.Uri fileURI = new System.Uri( absPath );
System.Uri rootURI = new System.Uri( ( projectRootPath + "/." ) );
filePath = rootURI.MakeRelativeUri( fileURI ).ToString();
}
else if( tree.CompareTo("GROUP") == 0) {
Debug.Log( "Group File" );
filePath = System.IO.Path.GetFileName( filePath );
}
if( parent == null ) {
parent = _rootGroup;
}
//Check if there is already a file
PBXFileReference fileReference = GetFile( System.IO.Path.GetFileName( filePath ) );
if( fileReference != null ) {
Debug.Log("File already exists: " + filePath); //not a warning, because this is normal for most builds!
return null;
}
fileReference = new PBXFileReference( filePath, (TreeEnum)System.Enum.Parse( typeof(TreeEnum), tree ) );
parent.AddChild( fileReference );
fileReferences.Add( fileReference );
results.Add( fileReference.guid, fileReference );
//Create a build file for reference
if( !string.IsNullOrEmpty( fileReference.buildPhase ) && createBuildFiles ) {
switch( fileReference.buildPhase ) {
case "PBXFrameworksBuildPhase":
foreach( KeyValuePair<string, PBXFrameworksBuildPhase> currentObject in frameworkBuildPhases ) {
BuildAddFile(fileReference,currentObject,weak);
}
if ( !string.IsNullOrEmpty( absPath ) && ( tree.CompareTo( "SOURCE_ROOT" ) == 0 )) {
string libraryPath = Path.Combine( "$(SRCROOT)", Path.GetDirectoryName( filePath ) );
if (File.Exists(absPath)) {
this.AddLibrarySearchPaths( new PBXList( libraryPath ) );
} else {
this.AddFrameworkSearchPaths( new PBXList( libraryPath ) );
}
}
break;
case "PBXResourcesBuildPhase":
foreach( KeyValuePair<string, PBXResourcesBuildPhase> currentObject in resourcesBuildPhases ) {
Debug.Log( "Adding Resources Build File" );
BuildAddFile(fileReference,currentObject,weak);
}
break;
case "PBXShellScriptBuildPhase":
foreach( KeyValuePair<string, PBXShellScriptBuildPhase> currentObject in shellScriptBuildPhases ) {
Debug.Log( "Adding Script Build File" );
BuildAddFile(fileReference,currentObject,weak);
}
break;
case "PBXSourcesBuildPhase":
foreach( KeyValuePair<string, PBXSourcesBuildPhase> currentObject in sourcesBuildPhases ) {
Debug.Log( "Adding Source Build File" );
BuildAddFile(fileReference,currentObject,weak);
}
break;
case "PBXCopyFilesBuildPhase":
foreach( KeyValuePair<string, PBXCopyFilesBuildPhase> currentObject in copyBuildPhases ) {
Debug.Log( "Adding Copy Files Build Phase" );
BuildAddFile(fileReference,currentObject,weak);
}
break;
case null:
Debug.LogWarning( "File Not Supported: " + filePath );
break;
default:
Debug.LogWarning( "File Not Supported." );
return null;
}
}
return results;
}
public PBXNativeTarget GetNativeTarget( string name )
{
PBXNativeTarget naviTarget = null;
foreach( KeyValuePair<string, PBXNativeTarget> currentObject in nativeTargets ) {
string targetName = (string)currentObject.Value.data["name"];
if (targetName == name) {
naviTarget = currentObject.Value;
break;
}
}
return naviTarget;
}
public int GetBuildActionMask()
{
int buildActionMask = 0;
foreach( var currentObject in copyBuildPhases )
{
buildActionMask = (int)currentObject.Value.data["buildActionMask"];
break;
}
return buildActionMask;
}
public PBXCopyFilesBuildPhase AddEmbedFrameworkBuildPhase()
{
PBXCopyFilesBuildPhase phase = null;
PBXNativeTarget naviTarget = GetNativeTarget("Unity-iPhone");
if (naviTarget == null)
{
Debug.Log("Not found Correct NativeTarget.");
return phase;
}
//check if embed framework buildPhase exist
foreach( var currentObject in copyBuildPhases )
{
object nameObj = null;
if (currentObject.Value.data.TryGetValue("name", out nameObj))
{
string name = (string)nameObj;
if (name == "Embed Frameworks")
return currentObject.Value;
}
}
int buildActionMask = this.GetBuildActionMask();
phase = new PBXCopyFilesBuildPhase(buildActionMask);
var buildPhases = (ArrayList)naviTarget.data["buildPhases"];
buildPhases.Add(phase.guid);//add build phase
copyBuildPhases.Add(phase);
return phase;
}
public void AddEmbedFramework( string fileName)
{
Debug.Log( "Add Embed Framework: " + fileName );
//Check if there is already a file
PBXFileReference fileReference = GetFile( System.IO.Path.GetFileName( fileName ) );
if( fileReference == null ) {
Debug.Log("Embed Framework must added already: " + fileName);
return;
}
var embedPhase = this.AddEmbedFrameworkBuildPhase();
if (embedPhase == null)
{
Debug.Log("AddEmbedFrameworkBuildPhase Failed.");
return;
}
//create a build file
PBXBuildFile buildFile = new PBXBuildFile( fileReference );
buildFile.AddCodeSignOnCopy();
buildFiles.Add( buildFile );
embedPhase.AddBuildFile(buildFile);
}
private void BuildAddFile (PBXFileReference fileReference, KeyValuePair<string, PBXFrameworksBuildPhase> currentObject,bool weak)
{
PBXBuildFile buildFile = new PBXBuildFile( fileReference, weak );
buildFiles.Add( buildFile );
currentObject.Value.AddBuildFile( buildFile );
}
private void BuildAddFile (PBXFileReference fileReference, KeyValuePair<string, PBXResourcesBuildPhase> currentObject,bool weak)
{
PBXBuildFile buildFile = new PBXBuildFile( fileReference, weak );
buildFiles.Add( buildFile );
currentObject.Value.AddBuildFile( buildFile );
}
private void BuildAddFile (PBXFileReference fileReference, KeyValuePair<string, PBXShellScriptBuildPhase> currentObject,bool weak)
{
PBXBuildFile buildFile = new PBXBuildFile( fileReference, weak );
buildFiles.Add( buildFile );
currentObject.Value.AddBuildFile( buildFile );
}
private void BuildAddFile (PBXFileReference fileReference, KeyValuePair<string, PBXSourcesBuildPhase> currentObject,bool weak)
{
PBXBuildFile buildFile = new PBXBuildFile( fileReference, weak );
buildFiles.Add( buildFile );
currentObject.Value.AddBuildFile( buildFile );
}
private void BuildAddFile (PBXFileReference fileReference, KeyValuePair<string, PBXCopyFilesBuildPhase> currentObject,bool weak)
{
PBXBuildFile buildFile = new PBXBuildFile( fileReference, weak );
buildFiles.Add( buildFile );
currentObject.Value.AddBuildFile( buildFile );
}
public bool AddFolder( string folderPath, PBXGroup parent = null, string[] exclude = null, bool recursive = true, bool createBuildFile = true )
{
Debug.Log("Folder PATH: "+folderPath);
if( !Directory.Exists( folderPath ) ){
Debug.Log("Directory doesn't exist?");
return false;
}
if (folderPath.EndsWith(".lproj")){
Debug.Log("Ended with .lproj");
return AddLocFolder(folderPath, parent, exclude, createBuildFile);
}
DirectoryInfo sourceDirectoryInfo = new DirectoryInfo( folderPath );
if( exclude == null ){
Debug.Log("Exclude was null");
exclude = new string[] {};
}
if( parent == null ){
Debug.Log("Parent was null");
parent = rootGroup;
}
// Create group
PBXGroup newGroup = GetGroup( sourceDirectoryInfo.Name, null /*relative path*/, parent );
Debug.Log("New Group created");
foreach( string directory in Directory.GetDirectories( folderPath ) ) {
Debug.Log( "DIR: " + directory );
if( directory.EndsWith( ".bundle" ) ) {
// Treat it like a file and copy even if not recursive
// TODO also for .xcdatamodeld?
Debug.LogWarning( "This is a special folder: " + directory );
AddFile( directory, newGroup, "SOURCE_ROOT", createBuildFile );
continue;
}
if( recursive ) {
Debug.Log( "recursive" );
AddFolder( directory, newGroup, exclude, recursive, createBuildFile );
}
}
// Adding files.
string regexExclude = string.Format( @"{0}", string.Join( "|", exclude ) );
foreach( string file in Directory.GetFiles( folderPath ) ) {
if( Regex.IsMatch( file, regexExclude ) ) {
continue;
}
Debug.Log("Adding Files for Folder");
AddFile( file, newGroup, "SOURCE_ROOT", createBuildFile );
}
modified = true;
return modified;
}
// We support neither recursing into nor bundles contained inside loc folders
public bool AddLocFolder( string folderPath, PBXGroup parent = null, string[] exclude = null, bool createBuildFile = true)
{
DirectoryInfo sourceDirectoryInfo = new DirectoryInfo( folderPath );
if( exclude == null )
exclude = new string[] {};
if( parent == null )
parent = rootGroup;
// Create group as needed
System.Uri projectFolderURI = new System.Uri( projectFileInfo.DirectoryName );
System.Uri locFolderURI = new System.Uri( folderPath );
var relativePath = projectFolderURI.MakeRelativeUri( locFolderURI ).ToString();
PBXGroup newGroup = GetGroup( sourceDirectoryInfo.Name, relativePath, parent );
// Add loc region to project
string nom = sourceDirectoryInfo.Name;
string region = nom.Substring(0, nom.Length - ".lproj".Length);
project.AddRegion(region);
// Adding files.
string regexExclude = string.Format( @"{0}", string.Join( "|", exclude ) );
foreach( string file in Directory.GetFiles( folderPath ) ) {
if( Regex.IsMatch( file, regexExclude ) ) {
continue;
}
// Add a variant group for the language as well
var variant = new PBXVariantGroup(System.IO.Path.GetFileName( file ), null, "GROUP");
variantGroups.Add(variant);
// The group gets a reference to the variant, not to the file itself
newGroup.AddChild(variant);
AddFile( file, variant, "GROUP", createBuildFile );
}
modified = true;
return modified;
}
#endregion
#region Getters
public PBXFileReference GetFile( string name )
{
if( string.IsNullOrEmpty( name ) ) {
return null;
}
foreach( KeyValuePair<string, PBXFileReference> current in fileReferences ) {
if( !string.IsNullOrEmpty( current.Value.name ) && current.Value.name.CompareTo( name ) == 0 ) {
return current.Value;
}
}
return null;
}
public PBXGroup GetGroup( string name, string path = null, PBXGroup parent = null )
{
if( string.IsNullOrEmpty( name ) )
return null;
if( parent == null ) parent = rootGroup;
foreach( KeyValuePair<string, PBXGroup> current in groups ) {
if( string.IsNullOrEmpty( current.Value.name ) ) {
if( current.Value.path.CompareTo( name ) == 0 && parent.HasChild( current.Key ) ) {
return current.Value;
}
} else if( current.Value.name.CompareTo( name ) == 0 && parent.HasChild( current.Key ) ) {
return current.Value;
}
}
PBXGroup result = new PBXGroup( name, path );
groups.Add( result );
parent.AddChild( result );
modified = true;
return result;
}
#endregion
#region Mods
public void ApplyMod( string pbxmod )
{
XCMod mod = new XCMod( pbxmod );
foreach(var lib in mod.libs){
Debug.Log("Library: "+lib);
}
ApplyMod( mod );
}
public void ApplyMod( XCMod mod )
{
PBXGroup modGroup = this.GetGroup( mod.group );
Debug.Log( "Adding libraries..." );
foreach( XCModFile libRef in mod.libs ) {
string completeLibPath = System.IO.Path.Combine( "usr/lib", libRef.filePath );
Debug.Log ("Adding library " + completeLibPath);
this.AddFile( completeLibPath, modGroup, "SDKROOT", true, libRef.isWeak );
}
Debug.Log( "Adding frameworks..." );
PBXGroup frameworkGroup = this.GetGroup( "Frameworks" );
foreach( string framework in mod.frameworks ) {
string[] filename = framework.Split( ':' );
bool isWeak = ( filename.Length > 1 ) ? true : false;
string completePath = System.IO.Path.Combine( "System/Library/Frameworks", filename[0] );
this.AddFile( completePath, frameworkGroup, "SDKROOT", true, isWeak );
}
Debug.Log( "Adding files..." );
foreach( string filePath in mod.files ) {
string absoluteFilePath = System.IO.Path.Combine( mod.path, filePath );
this.AddFile( absoluteFilePath, modGroup );
}
Debug.Log( "Adding embed binaries..." );
if (mod.embed_binaries != null)
{
//1. Add LD_RUNPATH_SEARCH_PATHS for embed framework
this.overwriteBuildSetting("LD_RUNPATH_SEARCH_PATHS", "$(inherited) @executable_path/Frameworks", "Release");
this.overwriteBuildSetting("LD_RUNPATH_SEARCH_PATHS", "$(inherited) @executable_path/Frameworks", "Debug");
foreach( string binary in mod.embed_binaries ) {
string absoluteFilePath = System.IO.Path.Combine( mod.path, binary );
this.AddEmbedFramework(absoluteFilePath);
}
}
Debug.Log( "Adding folders..." );
foreach( string folderPath in mod.folders ) {
string absoluteFolderPath = System.IO.Path.Combine( Application.dataPath, folderPath );
Debug.Log ("Adding folder " + absoluteFolderPath);
this.AddFolder( absoluteFolderPath, modGroup, (string[])mod.excludes.ToArray( typeof(string) ) );
}
Debug.Log( "Adding headerpaths..." );
foreach( string headerpath in mod.headerpaths ) {
if (headerpath.Contains("$(inherited)")) {
Debug.Log ("not prepending a path to " + headerpath);
this.AddHeaderSearchPaths( headerpath );
} else {
string absoluteHeaderPath = System.IO.Path.Combine( mod.path, headerpath );
this.AddHeaderSearchPaths( absoluteHeaderPath );
}
}
Debug.Log( "Adding compiler flags..." );
foreach( string flag in mod.compiler_flags ) {
this.AddOtherCFlags( flag );
}
Debug.Log( "Adding linker flags..." );
foreach( string flag in mod.linker_flags ) {
this.AddOtherLinkerFlags( flag );
}
Debug.Log ("Adding plist items...");
string plistPath = this.projectRootPath + "/Info.plist";
XCPlist plist = new XCPlist (plistPath);
plist.Process(mod.plist);
this.Consolidate();
}
#endregion
#region Savings
public void Consolidate()
{
PBXDictionary consolidated = new PBXDictionary();
consolidated.Append<PBXBuildFile>( this.buildFiles );//sort!
consolidated.Append<PBXCopyFilesBuildPhase>( this.copyBuildPhases );
consolidated.Append<PBXFileReference>( this.fileReferences );//sort!
consolidated.Append<PBXFrameworksBuildPhase>( this.frameworkBuildPhases );
consolidated.Append<PBXGroup>( this.groups );//sort!
consolidated.Append<PBXNativeTarget>( this.nativeTargets );
consolidated.Add( project.guid, project.data );//TODO this should be named PBXProject?
consolidated.Append<PBXResourcesBuildPhase>( this.resourcesBuildPhases );
consolidated.Append<PBXShellScriptBuildPhase>( this.shellScriptBuildPhases );
consolidated.Append<PBXSourcesBuildPhase>( this.sourcesBuildPhases );
consolidated.Append<PBXVariantGroup>( this.variantGroups );
consolidated.Append<XCBuildConfiguration>( this.buildConfigurations );
consolidated.Append<XCConfigurationList>( this.configurationLists );
_objects = consolidated;
consolidated = null;
}
public void Backup()
{
string backupPath = Path.Combine( this.filePath, "project.backup.pbxproj" );
// Delete previous backup file
if( File.Exists( backupPath ) )
File.Delete( backupPath );
// Backup original pbxproj file first
File.Copy( System.IO.Path.Combine( this.filePath, "project.pbxproj" ), backupPath );
}
private void DeleteExisting(string path)
{
// Delete old project file
if( File.Exists( path ))
File.Delete( path );
}
private void CreateNewProject(PBXDictionary result, string path)
{
PBXParser parser = new PBXParser();
StreamWriter saveFile = File.CreateText( path );
saveFile.Write( parser.Encode( result, true ) );
saveFile.Close();
}
/// <summary>
/// Saves a project after editing.
/// </summary>
public void Save()
{
PBXDictionary result = new PBXDictionary();
result.Add( "archiveVersion", 1 );
result.Add( "classes", new PBXDictionary() );
result.Add( "objectVersion", 46 );
Consolidate();
result.Add( "objects", _objects );
result.Add( "rootObject", _rootObjectKey );
string projectPath = Path.Combine( this.filePath, "project.pbxproj" );
// Delete old project file, in case of an IOException 'Sharing violation on path Error'
DeleteExisting(projectPath);
// Parse result object directly into file
CreateNewProject(result,projectPath);
}
/**
* Raw project data.
*/
public Dictionary<string, object> objects {
get {
return null;
}
}
#endregion
public void 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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void SubtractDouble()
{
var test = new SimpleBinaryOpTest__SubtractDouble();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__SubtractDouble
{
private const int VectorSize = 32;
private const int ElementCount = VectorSize / sizeof(Double);
private static Double[] _data1 = new Double[ElementCount];
private static Double[] _data2 = new Double[ElementCount];
private static Vector256<Double> _clsVar1;
private static Vector256<Double> _clsVar2;
private Vector256<Double> _fld1;
private Vector256<Double> _fld2;
private SimpleBinaryOpTest__DataTable<Double> _dataTable;
static SimpleBinaryOpTest__SubtractDouble()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__SubtractDouble()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); _data2[i] = (double)(random.NextDouble()); }
_dataTable = new SimpleBinaryOpTest__DataTable<Double>(_data1, _data2, new Double[ElementCount], VectorSize);
}
public bool IsSupported => Avx.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx.Subtract(
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx.Subtract(
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx.Subtract(
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx).GetMethod(nameof(Avx.Subtract), new Type[] { typeof(Vector256<Double>), typeof(Vector256<Double>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Double>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx.Subtract(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector256<Double>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector256<Double>>(_dataTable.inArray2Ptr);
var result = Avx.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Avx.LoadVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray1Ptr));
var right = Avx.LoadAlignedVector256((Double*)(_dataTable.inArray2Ptr));
var result = Avx.Subtract(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__SubtractDouble();
var result = Avx.Subtract(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx.Subtract(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<Double> left, Vector256<Double> right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
Double[] inArray1 = new Double[ElementCount];
Double[] inArray2 = new Double[ElementCount];
Double[] outArray = new Double[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "")
{
if (BitConverter.DoubleToInt64Bits(left[0] - right[0]) != BitConverter.DoubleToInt64Bits(result[0]))
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (BitConverter.DoubleToInt64Bits(left[i] - right[i]) != BitConverter.DoubleToInt64Bits(result[i]))
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx)}.{nameof(Avx.Subtract)}<Double>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* 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 log4net;
using NUnit.Framework;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Tests.Common;
using OpenSim.Tests.Common.Mock;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.Framework.Scenes.Tests
{
[TestFixture]
public class SceneObjectLinkingTests : OpenSimTestCase
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Links to self should be ignored.
/// </summary>
[Test]
public void TestLinkToSelf()
{
TestHelpers.InMethod();
UUID ownerId = TestHelpers.ParseTail(0x1);
int nParts = 3;
TestScene scene = new SceneHelpers().SetupScene();
SceneObjectGroup sog1 = SceneHelpers.CreateSceneObject(nParts, ownerId, "TestLinkToSelf_", 0x10);
scene.AddSceneObject(sog1);
scene.LinkObjects(ownerId, sog1.LocalId, new List<uint>() { sog1.Parts[1].LocalId });
// sog1.LinkToGroup(sog1);
Assert.That(sog1.Parts.Length, Is.EqualTo(nParts));
}
[Test]
public void TestLinkDelink2SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
Assert.IsFalse(grp1.GroupContainsForeignPrims);
grp1.LinkToGroup(grp2);
Assert.IsTrue(grp1.GroupContainsForeignPrims);
scene.Backup(true);
Assert.IsFalse(grp1.GroupContainsForeignPrims);
// FIXME: Can't do this test yet since group 2 still has its root part! We can't yet null this since
// it might cause SOG.ProcessBackup() to fail due to the race condition. This really needs to be fixed.
Assert.That(grp2.IsDeleted, "SOG 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained children after delink.");
Assert.That(grp1.Parts.Length == 2);
if (debugtest)
{
m_log.Debug("parts: " + grp1.Parts.Length);
m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset);
}
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position.");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not exactly sure what this is asserting...");
// Delink part 2
SceneObjectGroup grp3 = grp1.DelinkFromGroup(part2.LocalId);
if (debugtest)
m_log.Debug("Group2: Prim2: OffsetPosition:" + part2.AbsolutePosition + ", OffsetRotation:" + part2.RotationOffset);
Assert.That(grp1.Parts.Length, Is.EqualTo(1), "Group 1 still contained part2 after delink.");
Assert.That(part2.AbsolutePosition == Vector3.Zero, "The absolute position should be zero");
Assert.NotNull(grp3);
}
[Test]
public void TestLinkDelink2groups4SceneObjects()
{
TestHelpers.InMethod();
bool debugtest = false;
Scene scene = new SceneHelpers().SetupScene();
SceneObjectGroup grp1 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part1 = grp1.RootPart;
SceneObjectGroup grp2 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part2 = grp2.RootPart;
SceneObjectGroup grp3 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part3 = grp3.RootPart;
SceneObjectGroup grp4 = SceneHelpers.AddSceneObject(scene);
SceneObjectPart part4 = grp4.RootPart;
grp1.AbsolutePosition = new Vector3(10, 10, 10);
grp2.AbsolutePosition = Vector3.Zero;
grp3.AbsolutePosition = new Vector3(20, 20, 20);
grp4.AbsolutePosition = new Vector3(40, 40, 40);
// <90,0,0>
// grp1.UpdateGroupRotationR(Quaternion.CreateFromEulers(90 * Utils.DEG_TO_RAD, 0, 0));
// <180,0,0>
grp2.UpdateGroupRotationR(Quaternion.CreateFromEulers(180 * Utils.DEG_TO_RAD, 0, 0));
// <270,0,0>
// grp3.UpdateGroupRotationR(Quaternion.CreateFromEulers(270 * Utils.DEG_TO_RAD, 0, 0));
// <0,90,0>
grp4.UpdateGroupRotationR(Quaternion.CreateFromEulers(0, 90 * Utils.DEG_TO_RAD, 0));
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp2.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
grp4.RootPart.ClearUpdateSchedule();
// Link grp2 to grp1. part2 becomes child prim to grp1. grp2 is eliminated.
grp1.LinkToGroup(grp2);
// Link grp4 to grp3.
grp3.LinkToGroup(grp4);
// At this point we should have 4 parts total in two groups.
Assert.That(grp1.Parts.Length == 2, "Group1 children count should be 2");
Assert.That(grp2.IsDeleted, "Group 2 was not registered as deleted after link.");
Assert.That(grp2.Parts.Length, Is.EqualTo(0), "Group 2 still contained parts after delink.");
Assert.That(grp3.Parts.Length == 2, "Group3 children count should be 2");
Assert.That(grp4.IsDeleted, "Group 4 was not registered as deleted after link.");
Assert.That(grp4.Parts.Length, Is.EqualTo(0), "Group 4 still contained parts after delink.");
if (debugtest)
{
m_log.Debug("--------After Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset);
}
// Required for linking
grp1.RootPart.ClearUpdateSchedule();
grp3.RootPart.ClearUpdateSchedule();
// root part should have no offset position or rotation
Assert.That(part1.OffsetPosition == Vector3.Zero && part1.RotationOffset == Quaternion.Identity,
"root part should have no offset position or rotation (again)");
// offset position should be root part position - part2.absolute position.
Assert.That(part2.OffsetPosition == new Vector3(-10, -10, -10),
"offset position should be root part position - part2.absolute position (again)");
float roll = 0;
float pitch = 0;
float yaw = 0;
// There's a euler anomoly at 180, 0, 0 so expect 180 to turn into -180.
part1.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler1 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler1);
part2.RotationOffset.GetEulerAngles(out roll, out pitch, out yaw);
Vector3 rotEuler2 = new Vector3(roll * Utils.RAD_TO_DEG, pitch * Utils.RAD_TO_DEG, yaw * Utils.RAD_TO_DEG);
if (debugtest)
m_log.Debug(rotEuler2);
Assert.That(rotEuler2.ApproxEquals(new Vector3(-180, 0, 0), 0.001f) || rotEuler2.ApproxEquals(new Vector3(180, 0, 0), 0.001f),
"Not sure what this assertion is all about...");
// Now we're linking the first group to the third group. This will make the first group child parts of the third one.
grp3.LinkToGroup(grp1);
// Delink parts 2 and 3
grp3.DelinkFromGroup(part2.LocalId);
grp3.DelinkFromGroup(part3.LocalId);
if (debugtest)
{
m_log.Debug("--------After De-Link-------");
m_log.Debug("Group1: parts:" + grp1.Parts.Length);
m_log.Debug("Group1: Pos:" + grp1.AbsolutePosition + ", Rot:" + grp1.GroupRotation);
m_log.Debug("Group1: Prim1: OffsetPosition:" + part1.OffsetPosition + ", OffsetRotation:" + part1.RotationOffset);
m_log.Debug("Group1: Prim2: OffsetPosition:" + part2.OffsetPosition + ", OffsetRotation:" + part2.RotationOffset);
m_log.Debug("Group3: parts:" + grp3.Parts.Length);
m_log.Debug("Group3: Pos:" + grp3.AbsolutePosition + ", Rot:" + grp3.GroupRotation);
m_log.Debug("Group3: Prim1: OffsetPosition:" + part3.OffsetPosition + ", OffsetRotation:" + part3.RotationOffset);
m_log.Debug("Group3: Prim2: OffsetPosition:" + part4.OffsetPosition + ", OffsetRotation:" + part4.RotationOffset);
}
Assert.That(part2.AbsolutePosition == Vector3.Zero, "Badness 1");
Assert.That(part4.OffsetPosition == new Vector3(20, 20, 20), "Badness 2");
Quaternion compareQuaternion = new Quaternion(0, 0.7071068f, 0, 0.7071068f);
Assert.That((part4.RotationOffset.X - compareQuaternion.X < 0.00003)
&& (part4.RotationOffset.Y - compareQuaternion.Y < 0.00003)
&& (part4.RotationOffset.Z - compareQuaternion.Z < 0.00003)
&& (part4.RotationOffset.W - compareQuaternion.W < 0.00003),
"Badness 3");
}
/// <summary>
/// Test that a new scene object which is already linked is correctly persisted to the persistence layer.
/// </summary>
[Test]
public void TestNewSceneObjectLinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
sog.AddPart(linkPart);
scene.AddNewSceneObject(sog, true);
// In a test, we have to crank the backup handle manually. Normally this would be done by the timer invoked
// scene backup thread.
scene.Backup(true);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.That(storedObjects.Count, Is.EqualTo(1));
Assert.That(storedObjects[0].Parts.Length, Is.EqualTo(2));
Assert.That(storedObjects[0].ContainsPart(rootPartUuid));
Assert.That(storedObjects[0].ContainsPart(linkPartUuid));
}
/// <summary>
/// Test that a delink of a previously linked object is correctly persisted to the database
/// </summary>
[Test]
public void TestDelinkPersistence()
{
TestHelpers.InMethod();
//log4net.Config.XmlConfigurator.Configure();
TestScene scene = new SceneHelpers().SetupScene();
string rootPartName = "rootpart";
UUID rootPartUuid = new UUID("00000000-0000-0000-0000-000000000001");
string linkPartName = "linkpart";
UUID linkPartUuid = new UUID("00000000-0000-0000-0001-000000000000");
SceneObjectPart rootPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = rootPartName, UUID = rootPartUuid };
SceneObjectPart linkPart
= new SceneObjectPart(UUID.Zero, PrimitiveBaseShape.Default, Vector3.Zero, Quaternion.Identity, Vector3.Zero) { Name = linkPartName, UUID = linkPartUuid };
SceneObjectGroup linkGroup = new SceneObjectGroup(linkPart);
scene.AddNewSceneObject(linkGroup, true);
SceneObjectGroup sog = new SceneObjectGroup(rootPart);
scene.AddNewSceneObject(sog, true);
Assert.IsFalse(sog.GroupContainsForeignPrims);
sog.LinkToGroup(linkGroup);
Assert.IsTrue(sog.GroupContainsForeignPrims);
scene.Backup(true);
Assert.AreEqual(1, scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID).Count);
// These changes should occur immediately without waiting for a backup pass
SceneObjectGroup groupToDelete = sog.DelinkFromGroup(linkPart, false);
Assert.IsFalse(groupToDelete.GroupContainsForeignPrims);
scene.DeleteSceneObject(groupToDelete, false);
List<SceneObjectGroup> storedObjects = scene.SimulationDataService.LoadObjects(scene.RegionInfo.RegionID);
Assert.AreEqual(1, storedObjects.Count);
Assert.AreEqual(1, storedObjects[0].Parts.Length);
Assert.IsTrue(storedObjects[0].ContainsPart(rootPartUuid));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.Compute.Models;
namespace Microsoft.WindowsAzure.Management.Compute.Models
{
/// <summary>
/// The List OS Images operation response.
/// </summary>
public partial class VirtualMachineOSImageListResponse : OperationResponse, IEnumerable<VirtualMachineOSImageListResponse.VirtualMachineOSImage>
{
private IList<VirtualMachineOSImageListResponse.VirtualMachineOSImage> _images;
/// <summary>
/// Optional. The virtual machine images associated with your
/// subscription.
/// </summary>
public IList<VirtualMachineOSImageListResponse.VirtualMachineOSImage> Images
{
get { return this._images; }
set { this._images = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineOSImageListResponse
/// class.
/// </summary>
public VirtualMachineOSImageListResponse()
{
this.Images = new LazyList<VirtualMachineOSImageListResponse.VirtualMachineOSImage>();
}
/// <summary>
/// Gets the sequence of Images.
/// </summary>
public IEnumerator<VirtualMachineOSImageListResponse.VirtualMachineOSImage> GetEnumerator()
{
return this.Images.GetEnumerator();
}
/// <summary>
/// Gets the sequence of Images.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// A virtual machine image associated with your subscription.
/// </summary>
public partial class VirtualMachineOSImage
{
private string _affinityGroup;
/// <summary>
/// Optional. The affinity in which the media is located. The
/// AffinityGroup value is derived from storage account that
/// contains the blob in which the media is located. If the
/// storage account does not belong to an affinity group the value
/// is NULL and the element is not displayed in the response.
/// This value is NULL for platform images.
/// </summary>
public string AffinityGroup
{
get { return this._affinityGroup; }
set { this._affinityGroup = value; }
}
private string _category;
/// <summary>
/// Optional. The repository classification of the image. All user
/// images have the category User.
/// </summary>
public string Category
{
get { return this._category; }
set { this._category = value; }
}
private string _description;
/// <summary>
/// Optional. Specifies the description of the image.
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
private string _eula;
/// <summary>
/// Optional. Specifies the End User License Agreement that is
/// associated with the image. The value for this element is a
/// string, but it is recommended that the value be a URL that
/// points to a EULA.
/// </summary>
public string Eula
{
get { return this._eula; }
set { this._eula = value; }
}
private string _imageFamily;
/// <summary>
/// Optional. Specifies a value that can be used to group images.
/// </summary>
public string ImageFamily
{
get { return this._imageFamily; }
set { this._imageFamily = value; }
}
private string _iOType;
/// <summary>
/// Optional. Gets or sets the IO type.
/// </summary>
public string IOType
{
get { return this._iOType; }
set { this._iOType = value; }
}
private bool? _isPremium;
/// <summary>
/// Optional. Indicates whether the image contains software or
/// associated services that will incur charges above the core
/// price for the virtual machine. For additional details, see the
/// PricingDetailLink element.
/// </summary>
public bool? IsPremium
{
get { return this._isPremium; }
set { this._isPremium = value; }
}
private string _label;
/// <summary>
/// Optional. An identifier for the image.
/// </summary>
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _language;
/// <summary>
/// Optional. Specifies the language of the image. The Language
/// element is only available using version 2013-03-01 or higher.
/// </summary>
public string Language
{
get { return this._language; }
set { this._language = value; }
}
private string _location;
/// <summary>
/// Optional. The geo-location in which this media is located. The
/// Location value is derived from storage account that contains
/// the blob in which the media is located. If the storage account
/// belongs to an affinity group the value is NULL. If the
/// version is set to 2012-08-01 or later, the locations are
/// returned for platform images; otherwise, this value is NULL
/// for platform images.
/// </summary>
public string Location
{
get { return this._location; }
set { this._location = value; }
}
private double _logicalSizeInGB;
/// <summary>
/// Optional. The size, in GB, of the image.
/// </summary>
public double LogicalSizeInGB
{
get { return this._logicalSizeInGB; }
set { this._logicalSizeInGB = value; }
}
private Uri _mediaLinkUri;
/// <summary>
/// Optional. The location of the blob in Azure storage. The blob
/// location belongs to a storage account in the subscription
/// specified by the SubscriptionId value in the operation call.
/// Example:
/// http://example.blob.core.windows.net/disks/myimage.vhd
/// </summary>
public Uri MediaLinkUri
{
get { return this._mediaLinkUri; }
set { this._mediaLinkUri = value; }
}
private string _name;
/// <summary>
/// Optional. The name of the operating system image. This is the
/// name that is used when creating one or more virtual machines
/// using the image.
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
private string _operatingSystemType;
/// <summary>
/// Optional. The operating system type of the OS image. Possible
/// values are: Linux, Windows.
/// </summary>
public string OperatingSystemType
{
get { return this._operatingSystemType; }
set { this._operatingSystemType = value; }
}
private Uri _pricingDetailUri;
/// <summary>
/// Optional. Specifies a URL for an image with IsPremium set to
/// true, which contains the pricing details for a virtual machine
/// that is created from the image. The PricingDetailLink element
/// is only available using version 2012-12-01 or higher.
/// </summary>
public Uri PricingDetailUri
{
get { return this._pricingDetailUri; }
set { this._pricingDetailUri = value; }
}
private Uri _privacyUri;
/// <summary>
/// Optional. Specifies the URI that points to a document that
/// contains the privacy policy related to the image.
/// </summary>
public Uri PrivacyUri
{
get { return this._privacyUri; }
set { this._privacyUri = value; }
}
private DateTime _publishedDate;
/// <summary>
/// Optional. Specifies the date when the image was added to the
/// image repository.
/// </summary>
public DateTime PublishedDate
{
get { return this._publishedDate; }
set { this._publishedDate = value; }
}
private string _publisherName;
/// <summary>
/// Optional. The name of the publisher of this OS Image in Azure.
/// </summary>
public string PublisherName
{
get { return this._publisherName; }
set { this._publisherName = value; }
}
private string _recommendedVMSize;
/// <summary>
/// Optional. Specifies the size to use for the virtual machine
/// that is created from the OS image.
/// </summary>
public string RecommendedVMSize
{
get { return this._recommendedVMSize; }
set { this._recommendedVMSize = value; }
}
private bool? _showInGui;
/// <summary>
/// Optional. Indicates whether the image should be shown in the
/// Azure portal.
/// </summary>
public bool? ShowInGui
{
get { return this._showInGui; }
set { this._showInGui = value; }
}
private Uri _smallIconUri;
/// <summary>
/// Optional. Specifies the URI to the small icon that is displayed
/// when the image is presented in the Azure Management Portal.
/// The SmallIconUri element is only available using version
/// 2013-03-01 or higher.
/// </summary>
public Uri SmallIconUri
{
get { return this._smallIconUri; }
set { this._smallIconUri = value; }
}
/// <summary>
/// Initializes a new instance of the VirtualMachineOSImage class.
/// </summary>
public VirtualMachineOSImage()
{
}
}
}
}
| |
// 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.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Extension methods for NetworkSecurityGroupsOperations.
/// </summary>
public static partial class NetworkSecurityGroupsOperationsExtensions
{
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void Delete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.DeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
public static NetworkSecurityGroup Get(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string))
{
return operations.GetAsync(resourceGroupName, networkSecurityGroupName, expand).GetAwaiter().GetResult();
}
/// <summary>
/// Gets the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='expand'>
/// Expands referenced resources.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> GetAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, string expand = default(string), CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, expand, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup CreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> CreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NetworkSecurityGroup> ListAll(this INetworkSecurityGroupsOperations operations)
{
return operations.ListAllAsync().GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllAsync(this INetworkSecurityGroupsOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
public static IPage<NetworkSecurityGroup> List(this INetworkSecurityGroupsOperations operations, string resourceGroupName)
{
return operations.ListAsync(resourceGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
public static void BeginDelete(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName)
{
operations.BeginDeleteAsync(resourceGroupName, networkSecurityGroupName).GetAwaiter().GetResult();
}
/// <summary>
/// Deletes the specified network security group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
(await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, null, cancellationToken).ConfigureAwait(false)).Dispose();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
public static NetworkSecurityGroup BeginCreateOrUpdate(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters)
{
return operations.BeginCreateOrUpdateAsync(resourceGroupName, networkSecurityGroupName, parameters).GetAwaiter().GetResult();
}
/// <summary>
/// Creates or updates a network security group in the specified resource
/// group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkSecurityGroupName'>
/// The name of the network security group.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create or update network security group
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NetworkSecurityGroup> BeginCreateOrUpdateAsync(this INetworkSecurityGroupsOperations operations, string resourceGroupName, string networkSecurityGroupName, NetworkSecurityGroup parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, networkSecurityGroupName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListAllNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListAllNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a subscription.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListAllNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAllNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
public static IPage<NetworkSecurityGroup> ListNext(this INetworkSecurityGroupsOperations operations, string nextPageLink)
{
return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
}
/// <summary>
/// Gets all network security groups in a resource group.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NetworkSecurityGroup>> ListNextAsync(this INetworkSecurityGroupsOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
using System;
using System.Diagnostics.Contracts;
namespace System {
// Summary:
// Defines methods that convert the value of the implementing reference or value
// type to a common language runtime type that has an equivalent value.
[ContractClass(typeof(IConvertibleContract))]
public interface IConvertible {
// Summary:
// Returns the System.TypeCode for this instance.
//
// Returns:
// The enumerated constant that is the System.TypeCode of the class or value
// type that implements this interface.
[Pure]
TypeCode GetTypeCode();
//
// Summary:
// Converts the value of this instance to an equivalent Boolean value using
// the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A Boolean value equivalent to the value of this instance.
[Pure]
bool ToBoolean(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 8-bit unsigned integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 8-bit unsigned integer equivalent to the value of this instance.
[Pure]
byte ToByte(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent Unicode character using
// the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A Unicode character equivalent to the value of this instance.
[Pure]
char ToChar(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent System.DateTime using
// the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A System.DateTime instance equivalent to the value of this instance.
[Pure]
DateTime ToDateTime(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent System.Decimal number
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A System.Decimal number equivalent to the value of this instance.
[Pure]
decimal ToDecimal(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent double-precision floating-point
// number using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A double-precision floating-point number equivalent to the value of this
// instance.
[Pure]
double ToDouble(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 16-bit signed integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 16-bit signed integer equivalent to the value of this instance.
[Pure]
short ToInt16(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 32-bit signed integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 32-bit signed integer equivalent to the value of this instance.
[Pure]
int ToInt32(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 64-bit signed integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 64-bit signed integer equivalent to the value of this instance.
[Pure]
long ToInt64(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 8-bit signed integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 8-bit signed integer equivalent to the value of this instance.
[Pure]
sbyte ToSByte(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent single-precision floating-point
// number using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A single-precision floating-point number equivalent to the value of this
// instance.
[Pure]
float ToSingle(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent System.String using
// the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// A System.String instance equivalent to the value of this instance.
[Pure]
string ToString(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an System.Object of the specified
// System.Type that has an equivalent value, using the specified culture-specific
// formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// conversionType:
// The System.Type to which the value of this instance is converted.
//
// Returns:
// An System.Object instance of type conversionType whose value is equivalent
// to the value of this instance.
[Pure]
object ToType(Type conversionType, IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 16-bit unsigned integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 16-bit unsigned integer equivalent to the value of this instance.
[Pure]
ushort ToUInt16(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 32-bit unsigned integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 32-bit unsigned integer equivalent to the value of this instance.
[Pure]
uint ToUInt32(IFormatProvider provider);
//
// Summary:
// Converts the value of this instance to an equivalent 64-bit unsigned integer
// using the specified culture-specific formatting information.
//
// Parameters:
// provider:
// An System.IFormatProvider interface implementation that supplies culture-specific
// formatting information.
//
// Returns:
// An 64-bit unsigned integer equivalent to the value of this instance.
[Pure]
ulong ToUInt64(IFormatProvider provider);
}
[ContractClassFor(typeof(IConvertible))]
abstract class IConvertibleContract : IConvertible
{
#region IConvertible Members
TypeCode IConvertible.GetTypeCode()
{
throw new NotImplementedException();
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
throw new NotImplementedException();
}
byte IConvertible.ToByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
char IConvertible.ToChar(IFormatProvider provider)
{
throw new NotImplementedException();
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new NotImplementedException();
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
throw new NotImplementedException();
}
double IConvertible.ToDouble(IFormatProvider provider)
{
throw new NotImplementedException();
}
short IConvertible.ToInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
int IConvertible.ToInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
long IConvertible.ToInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
throw new NotImplementedException();
}
float IConvertible.ToSingle(IFormatProvider provider)
{
throw new NotImplementedException();
}
[Pure]
string IConvertible.ToString(IFormatProvider provider)
{
Contract.Ensures(Contract.Result<string>() != null);
return default(string);
}
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
throw new NotImplementedException();
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
throw new NotImplementedException();
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
throw new NotImplementedException();
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
throw new NotImplementedException();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. 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.IO;
using Microsoft.AspNet.Razor.Text;
namespace Microsoft.AspNet.Razor.Generator.Compiler
{
public class CodeWriter : IDisposable
{
private static readonly char[] NewLineCharacters = new char[] { '\r', '\n' };
private StringWriter _writer = new StringWriter();
private bool _newLine;
private string _cache = string.Empty;
private bool _dirty = false;
private int _absoluteIndex;
private int _currentLineIndex;
private int _currentLineCharacterIndex;
public string LastWrite { get; private set; }
public int CurrentIndent { get; private set; }
public CodeWriter ResetIndent()
{
return SetIndent(0);
}
public CodeWriter IncreaseIndent(int size)
{
CurrentIndent += size;
return this;
}
public CodeWriter DecreaseIndent(int size)
{
CurrentIndent -= size;
return this;
}
public CodeWriter SetIndent(int size)
{
CurrentIndent = size;
return this;
}
public CodeWriter Indent(int size)
{
if (_newLine)
{
_writer.Write(new string(' ', size));
Flush();
_currentLineCharacterIndex += size;
_absoluteIndex += size;
_dirty = true;
_newLine = false;
}
return this;
}
public CodeWriter Write(string data)
{
Indent(CurrentIndent);
_writer.Write(data);
Flush();
LastWrite = data;
_dirty = true;
_newLine = false;
if (data == null || data.Length == 0)
{
return this;
}
_absoluteIndex += data.Length;
// The data string might contain a partial newline where the previously
// written string has part of the newline.
var i = 0;
int? trailingPartStart = null;
var builder = _writer.GetStringBuilder();
if (
// Check the last character of the previous write operation.
builder.Length - data.Length - 1 >= 0 &&
builder[builder.Length - data.Length - 1] == '\r' &&
// Check the first character of the current write operation.
builder[builder.Length - data.Length] == '\n')
{
// This is newline that's spread across two writes. Skip the first character of the
// current write operation.
//
// We don't need to increment our newline counter because we already did that when we
// saw the \r.
i += 1;
trailingPartStart = 1;
}
// Iterate the string, stopping at each occurrence of a newline character. This lets us count the
// newline occurrences and keep the index of the last one.
while ((i = data.IndexOfAny(NewLineCharacters, i)) >= 0)
{
// Newline found.
_currentLineIndex++;
_currentLineCharacterIndex = 0;
i++;
// We might have stopped at a \r, so check if it's followed by \n and then advance the index to
// start the next search after it.
if (data.Length > i &&
data[i - 1] == '\r' &&
data[i] == '\n')
{
i++;
}
// The 'suffix' of the current line starts after this newline token.
trailingPartStart = i;
}
if (trailingPartStart == null)
{
// No newlines, just add the length of the data buffer
_currentLineCharacterIndex += data.Length;
}
else
{
// Newlines found, add the trailing part of 'data'
_currentLineCharacterIndex += (data.Length - trailingPartStart.Value);
}
return this;
}
public CodeWriter WriteLine()
{
LastWrite = _writer.NewLine;
_writer.WriteLine();
Flush();
_currentLineIndex++;
_currentLineCharacterIndex = 0;
_absoluteIndex += _writer.NewLine.Length;
_dirty = true;
_newLine = true;
return this;
}
public CodeWriter WriteLine(string data)
{
return Write(data).WriteLine();
}
public CodeWriter Flush()
{
_writer.Flush();
return this;
}
public string GenerateCode()
{
if (_dirty)
{
_cache = _writer.ToString();
_dirty = false;
}
return _cache;
}
public SourceLocation GetCurrentSourceLocation()
{
return new SourceLocation(_absoluteIndex, _currentLineIndex, _currentLineCharacterIndex);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_writer.Dispose();
}
}
public void Dispose()
{
Dispose(disposing: true);
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="EdmModelBase.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Linq;
using Microsoft.OData.Edm.Annotations;
using Microsoft.OData.Edm.Vocabularies.V1;
namespace Microsoft.OData.Edm.Library
{
/// <summary>
/// Represents an EDM model.
/// </summary>
public abstract class EdmModelBase : EdmElement, IEdmModel
{
private readonly List<IEdmModel> referencedEdmModels;
private readonly IEdmDirectValueAnnotationsManager annotationsManager;
private readonly Dictionary<string, IEdmEntityContainer> containersDictionary = new Dictionary<string, IEdmEntityContainer>();
private readonly Dictionary<string, IEdmSchemaType> schemaTypeDictionary = new Dictionary<string, IEdmSchemaType>();
private readonly Dictionary<string, IEdmValueTerm> valueTermDictionary = new Dictionary<string, IEdmValueTerm>();
private readonly Dictionary<string, IList<IEdmOperation>> functionDictionary = new Dictionary<string, IList<IEdmOperation>>();
/// <summary>
/// Initializes a new instance of the <see cref="EdmModelBase"/> class.
/// </summary>
/// <param name="referencedModels">Models to which this model refers.</param>
/// <param name="annotationsManager">Annotations manager for the model to use.</param>
/// <remarks>Only either mainModel and referencedModels should have value.</remarks>
protected EdmModelBase(IEnumerable<IEdmModel> referencedModels, IEdmDirectValueAnnotationsManager annotationsManager)
{
EdmUtil.CheckArgumentNull(referencedModels, "referencedModels");
EdmUtil.CheckArgumentNull(annotationsManager, "annotationsManager");
this.referencedEdmModels = new List<IEdmModel>(referencedModels);
this.referencedEdmModels.Add(EdmCoreModel.Instance);
if (CoreVocabularyModel.Instance != null)
{
this.referencedEdmModels.Add(CoreVocabularyModel.Instance);
}
if (CapabilitiesVocabularyModel.Instance != null)
{
this.referencedEdmModels.Add(CapabilitiesVocabularyModel.Instance);
}
this.annotationsManager = annotationsManager;
}
/// <summary>
/// Gets the collection of schema elements that are contained in this model and referenced models.
/// </summary>
public abstract IEnumerable<IEdmSchemaElement> SchemaElements
{
get;
}
/// <summary>
/// Gets the collection of namespaces that schema elements use contained in this model.
/// </summary>
public abstract IEnumerable<string> DeclaredNamespaces
{
get;
}
/// <summary>
/// Gets the collection of vocabulary annotations that are contained in this model.
/// </summary>
public virtual IEnumerable<IEdmVocabularyAnnotation> VocabularyAnnotations
{
get { return Enumerable.Empty<IEdmVocabularyAnnotation>(); }
}
/// <summary>
/// Gets the collection of models referred to by this model.
/// </summary>
public IEnumerable<IEdmModel> ReferencedModels
{
get { return this.referencedEdmModels; }
}
/// <summary>
/// Gets the model's annotations manager.
/// </summary>
public IEdmDirectValueAnnotationsManager DirectValueAnnotationsManager
{
get { return this.annotationsManager; }
}
/// <summary>
/// Gets the only one entity container of the model.
/// </summary>
public IEdmEntityContainer EntityContainer
{
get { return this.containersDictionary.Values.FirstOrDefault(); }
}
/// <summary>
/// Searches for a type with the given name in this model only and returns null if no such type exists.
/// </summary>
/// <param name="qualifiedName">The qualified name of the type being found.</param>
/// <returns>The requested type, or null if no such type exists.</returns>
public IEdmSchemaType FindDeclaredType(string qualifiedName)
{
IEdmSchemaType result;
this.schemaTypeDictionary.TryGetValue(qualifiedName, out result);
return result;
}
/// <summary>
/// Searches for a value term with the given name in this model and returns null if no such value term exists.
/// </summary>
/// <param name="qualifiedName">The qualified name of the value term being found.</param>
/// <returns>The requested value term, or null if no such value term exists.</returns>
public IEdmValueTerm FindDeclaredValueTerm(string qualifiedName)
{
IEdmValueTerm result;
this.valueTermDictionary.TryGetValue(qualifiedName, out result);
return result;
}
/// <summary>
/// Searches for a operation with the given name in this model and returns null if no such operation exists.
/// </summary>
/// <param name="qualifiedName">The qualified name of the operation being found.</param>
/// <returns>A group of operations sharing the specified qualified name, or an empty enumerable if no such operation exists.</returns>
public IEnumerable<IEdmOperation> FindDeclaredOperations(string qualifiedName)
{
IList<IEdmOperation> elements;
if (this.functionDictionary.TryGetValue(qualifiedName, out elements))
{
return elements;
}
return Enumerable.Empty<IEdmOperation>();
}
/// <summary>
/// Searches for bound operations based on the binding type, returns an empty enumerable if no operation exists.
/// </summary>
/// <param name="bindingType">Type of the binding.</param>
/// <returns> A set of operations that share the binding type or empty enumerable if no such operation exists. </returns>
public virtual IEnumerable<IEdmOperation> FindDeclaredBoundOperations(IEdmType bindingType)
{
foreach (IEnumerable<IEdmOperation> operations in this.functionDictionary.Values.Distinct())
{
foreach (IEdmOperation operation in operations.Where(o => o.IsBound && o.Parameters.Any() && o.HasEquivalentBindingType(bindingType)))
{
yield return operation;
}
}
}
/// <summary>
/// Searches for bound operations based on the qualified name and binding type, returns an empty enumerable if no operation exists.
/// </summary>
/// <param name="qualifiedName">The qualifeid name of the operation.</param>
/// <param name="bindingType">Type of the binding.</param>
/// <returns>
/// A set of operations that share the name and binding type or empty enumerable if no such operation exists.
/// </returns>
public virtual IEnumerable<IEdmOperation> FindDeclaredBoundOperations(string qualifiedName, IEdmType bindingType)
{
return this.FindDeclaredOperations(qualifiedName).Where(o => o.IsBound && o.Parameters.Any() && o.HasEquivalentBindingType(bindingType));
}
/// <summary>
/// Searches for vocabulary annotations specified by this model or a referenced model for a given element.
/// </summary>
/// <param name="element">The annotated element.</param>
/// <returns>The vocabulary annotations for the element.</returns>
public virtual IEnumerable<IEdmVocabularyAnnotation> FindDeclaredVocabularyAnnotations(IEdmVocabularyAnnotatable element)
{
return Enumerable.Empty<IEdmVocabularyAnnotation>();
}
/// <summary>
/// Finds a list of types that derive directly from the supplied type.
/// </summary>
/// <param name="baseType">The base type that derived types are being searched for.</param>
/// <returns>A list of types that derive directly from the base type.</returns>
public abstract IEnumerable<IEdmStructuredType> FindDirectlyDerivedTypes(IEdmStructuredType baseType);
/// <summary>
/// Adds a schema element to this model.
/// </summary>
/// <param name="element">The element to register.</param>
protected void RegisterElement(IEdmSchemaElement element)
{
EdmUtil.CheckArgumentNull(element, "element");
RegistrationHelper.RegisterSchemaElement(element, this.schemaTypeDictionary, this.valueTermDictionary, this.functionDictionary, this.containersDictionary);
}
/// <summary>
/// Adds a model reference to this model.
/// </summary>
/// <param name="model">The model to reference.</param>
protected void AddReferencedModel(IEdmModel model)
{
EdmUtil.CheckArgumentNull(model, "model");
this.referencedEdmModels.Add(model);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using NetGore.IO;
namespace NetGore
{
/// <summary>
/// Represents the index of a slot in the Inventory.
/// </summary>
[Serializable]
[TypeConverter(typeof(InventorySlotTypeConverter))]
public struct InventorySlot : IComparable<InventorySlot>, IConvertible, IFormattable, IComparable<int>, IEquatable<int>
{
/// <summary>
/// Represents the largest possible value of InventorySlot. This field is constant.
/// </summary>
public const int MaxValue = byte.MaxValue;
/// <summary>
/// Represents the smallest possible value of InventorySlot. This field is constant.
/// </summary>
public const int MinValue = byte.MinValue;
/// <summary>
/// The underlying value. This contains the actual value of the struct instance.
/// </summary>
readonly byte _value;
/// <summary>
/// Initializes a new instance of the <see cref="InventorySlot"/> struct.
/// </summary>
/// <param name="value">Value to assign to the new InventorySlot.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="value"/> is out of range.</exception>
public InventorySlot(int value)
{
if (value < MinValue || value > MaxValue)
throw new ArgumentOutOfRangeException("value");
_value = (byte)value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="other">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public bool Equals(InventorySlot other)
{
return other._value == _value;
}
/// <summary>
/// Indicates whether this instance and a specified object are equal.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns>
/// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false.
/// </returns>
public override bool Equals(object obj)
{
return obj is InventorySlot && this == (InventorySlot)obj;
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>
/// A 32-bit signed integer that is the hash code for this instance.
/// </returns>
public override int GetHashCode()
{
return _value.GetHashCode();
}
/// <summary>
/// Gets the raw internal value of this InventorySlot.
/// </summary>
/// <returns>The raw internal value.</returns>
public byte GetRawValue()
{
return _value;
}
/// <summary>
/// Reads an InventorySlot from an IValueReader.
/// </summary>
/// <param name="reader">IValueReader to read from.</param>
/// <param name="name">Unique name of the value to read.</param>
/// <returns>The InventorySlot read from the IValueReader.</returns>
public static InventorySlot Read(IValueReader reader, string name)
{
var value = reader.ReadByte(name);
return new InventorySlot(value);
}
/// <summary>
/// Reads an InventorySlot from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="i">The index of the field to find.</param>
/// <returns>The InventorySlot read from the <see cref="IDataRecord"/>.</returns>
public static InventorySlot Read(IDataRecord reader, int i)
{
var value = reader.GetValue(i);
if (value is byte)
return new InventorySlot((byte)value);
var convertedValue = Convert.ToByte(value);
return new InventorySlot(convertedValue);
}
/// <summary>
/// Reads an InventorySlot from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param>
/// <param name="name">The name of the field to find.</param>
/// <returns>The InventorySlot read from the <see cref="IDataRecord"/>.</returns>
public static InventorySlot Read(IDataRecord reader, string name)
{
return Read(reader, reader.GetOrdinal(name));
}
/// <summary>
/// Reads an InventorySlot from an IValueReader.
/// </summary>
/// <param name="bitStream">BitStream to read from.</param>
/// <returns>The InventorySlot read from the BitStream.</returns>
public static InventorySlot Read(BitStream bitStream)
{
var value = bitStream.ReadByte();
return new InventorySlot(value);
}
/// <summary>
/// Converts the numeric value of this instance to its equivalent string representation.
/// </summary>
/// <returns>The string representation of the value of this instance, consisting of a sequence
/// of digits ranging from 0 to 9, without leading zeroes.</returns>
public override string ToString()
{
return _value.ToString();
}
/// <summary>
/// Writes the InventorySlot to an IValueWriter.
/// </summary>
/// <param name="writer">IValueWriter to write to.</param>
/// <param name="name">Unique name of the InventorySlot that will be used to distinguish it
/// from other values when reading.</param>
public void Write(IValueWriter writer, string name)
{
writer.Write(name, _value);
}
/// <summary>
/// Writes the InventorySlot to an IValueWriter.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
public void Write(BitStream bitStream)
{
bitStream.Write(_value);
}
#region IComparable<int> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(int other)
{
return _value.CompareTo(other);
}
#endregion
#region IComparable<InventorySlot> Members
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// A 32-bit signed integer that indicates the relative order of the objects being compared.
/// The return value has the following meanings:
/// Value
/// Meaning
/// Less than zero
/// This object is less than the <paramref name="other"/> parameter.
/// Zero
/// This object is equal to <paramref name="other"/>.
/// Greater than zero
/// This object is greater than <paramref name="other"/>.
/// </returns>
public int CompareTo(InventorySlot other)
{
return _value.CompareTo(other._value);
}
#endregion
#region IConvertible Members
/// <summary>
/// Returns the <see cref="T:System.TypeCode"/> for this instance.
/// </summary>
/// <returns>
/// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface.
/// </returns>
public TypeCode GetTypeCode()
{
return _value.GetTypeCode();
}
/// <summary>
/// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation
/// that supplies culture-specific formatting information.</param>
/// <returns>
/// A Boolean value equivalent to the value of this instance.
/// </returns>
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return ((IConvertible)_value).ToBoolean(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit unsigned integer equivalent to the value of this instance.
/// </returns>
byte IConvertible.ToByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A Unicode character equivalent to the value of this instance.
/// </returns>
char IConvertible.ToChar(IFormatProvider provider)
{
return ((IConvertible)_value).ToChar(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance.
/// </returns>
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
return ((IConvertible)_value).ToDateTime(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance.
/// </returns>
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return ((IConvertible)_value).ToDecimal(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A double-precision floating-point number equivalent to the value of this instance.
/// </returns>
double IConvertible.ToDouble(IFormatProvider provider)
{
return ((IConvertible)_value).ToDouble(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit signed integer equivalent to the value of this instance.
/// </returns>
short IConvertible.ToInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit signed integer equivalent to the value of this instance.
/// </returns>
int IConvertible.ToInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit signed integer equivalent to the value of this instance.
/// </returns>
long IConvertible.ToInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToInt64(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 8-bit signed integer equivalent to the value of this instance.
/// </returns>
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return ((IConvertible)_value).ToSByte(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information. </param>
/// <returns>
/// A single-precision floating-point number equivalent to the value of this instance.
/// </returns>
float IConvertible.ToSingle(IFormatProvider provider)
{
return ((IConvertible)_value).ToSingle(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// A <see cref="T:System.String"/> instance equivalent to the value of this instance.
/// </returns>
public string ToString(IFormatProvider provider)
{
return ((IConvertible)_value).ToString(provider);
}
/// <summary>
/// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information.
/// </summary>
/// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance.
/// </returns>
object IConvertible.ToType(Type conversionType, IFormatProvider provider)
{
return ((IConvertible)_value).ToType(conversionType, provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 16-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt16(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 32-bit unsigned integer equivalent to the value of this instance.
/// </returns>
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt32(provider);
}
/// <summary>
/// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information.
/// </summary>
/// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies
/// culture-specific formatting information.</param>
/// <returns>
/// An 64-bit unsigned integer equivalent to the value of this instance.
/// </returns>
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return ((IConvertible)_value).ToUInt64(provider);
}
#endregion
#region IEquatable<int> Members
/// <summary>
/// Indicates whether the current object is equal to another object of the same type.
/// </summary>
/// <param name="other">An object to compare with this object.</param>
/// <returns>
/// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false.
/// </returns>
public bool Equals(int other)
{
return _value.Equals(other);
}
#endregion
#region IFormattable Members
/// <summary>
/// Formats the value of the current instance using the specified format.
/// </summary>
/// <param name="format">The <see cref="T:System.String"/> specifying the format to use.
/// -or-
/// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.
/// </param>
/// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value.
/// -or-
/// null to obtain the numeric format information from the current locale setting of the operating system.
/// </param>
/// <returns>
/// A <see cref="T:System.String"/> containing the value of the current instance in the specified format.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider)
{
return _value.ToString(format, formatProvider);
}
#endregion
/// <summary>
/// Implements operator ++.
/// </summary>
/// <param name="l">The InventorySlot to increment.</param>
/// <returns>The incremented InventorySlot.</returns>
public static InventorySlot operator ++(InventorySlot l)
{
return new InventorySlot(l._value + 1);
}
/// <summary>
/// Implements operator --.
/// </summary>
/// <param name="l">The InventorySlot to decrement.</param>
/// <returns>The decremented InventorySlot.</returns>
public static InventorySlot operator --(InventorySlot l)
{
return new InventorySlot(l._value - 1);
}
/// <summary>
/// Implements operator +.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side plus the right side.</returns>
public static InventorySlot operator +(InventorySlot left, InventorySlot right)
{
return new InventorySlot(left._value + right._value);
}
/// <summary>
/// Implements operator -.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>Result of the left side minus the right side.</returns>
public static InventorySlot operator -(InventorySlot left, InventorySlot right)
{
return new InventorySlot(left._value - right._value);
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(InventorySlot left, int right)
{
return left._value == right;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(InventorySlot left, int right)
{
return left._value != right;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(int left, InventorySlot right)
{
return left == right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(int left, InventorySlot right)
{
return left != right._value;
}
/// <summary>
/// Casts a InventorySlot to an Int32.
/// </summary>
/// <param name="InventorySlot">InventorySlot to cast.</param>
/// <returns>The Int32.</returns>
public static explicit operator int(InventorySlot InventorySlot)
{
return InventorySlot._value;
}
/// <summary>
/// Casts an Int32 to a InventorySlot.
/// </summary>
/// <param name="value">Int32 to cast.</param>
/// <returns>The InventorySlot.</returns>
public static explicit operator InventorySlot(int value)
{
return new InventorySlot(value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(int left, InventorySlot right)
{
return left > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(int left, InventorySlot right)
{
return left < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(InventorySlot left, InventorySlot right)
{
return left._value > right._value;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(InventorySlot left, InventorySlot right)
{
return left._value < right._value;
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than the right.</returns>
public static bool operator >(InventorySlot left, int right)
{
return left._value > right;
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than the left.</returns>
public static bool operator <(InventorySlot left, int right)
{
return left._value < right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(int left, InventorySlot right)
{
return left >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(int left, InventorySlot right)
{
return left <= right._value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(InventorySlot left, int right)
{
return left._value >= right;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(InventorySlot left, int right)
{
return left._value <= right;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the left argument is greater than or equal to the right.</returns>
public static bool operator >=(InventorySlot left, InventorySlot right)
{
return left._value >= right._value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the right argument is greater than or equal to the left.</returns>
public static bool operator <=(InventorySlot left, InventorySlot right)
{
return left._value <= right._value;
}
/// <summary>
/// Implements operator !=.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are not equal.</returns>
public static bool operator !=(InventorySlot left, InventorySlot right)
{
return left._value != right._value;
}
/// <summary>
/// Implements operator ==.
/// </summary>
/// <param name="left">Left side argument.</param>
/// <param name="right">Right side argument.</param>
/// <returns>If the two arguments are equal.</returns>
public static bool operator ==(InventorySlot left, InventorySlot right)
{
return left._value == right._value;
}
}
/// <summary>
/// Adds extensions to some data I/O objects for performing Read and Write operations for the InventorySlot.
/// All of the operations are implemented in the InventorySlot struct. These extensions are provided
/// purely for the convenience of accessing all the I/O operations from the same place.
/// </summary>
public static class InventorySlotReadWriteExtensions
{
/// <summary>
/// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type InventorySlot.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as a InventorySlot.</returns>
public static InventorySlot AsInventorySlot<T>(this IDictionary<T, string> dict, T key)
{
return Parser.Invariant.ParseInventorySlot(dict[key]);
}
/// <summary>
/// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type InventorySlot.
/// </summary>
/// <typeparam name="T">The key Type.</typeparam>
/// <param name="dict">The IDictionary.</param>
/// <param name="key">The key for the value to get.</param>
/// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param>
/// <returns>The value at the given <paramref name="key"/> parsed as an int, or the
/// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/>
/// or the value at the given <paramref name="key"/> could not be parsed.</returns>
public static InventorySlot AsInventorySlot<T>(this IDictionary<T, string> dict, T key, InventorySlot defaultValue)
{
string value;
if (!dict.TryGetValue(key, out value))
return defaultValue;
InventorySlot parsed;
if (!Parser.Invariant.TryParse(value, out parsed))
return defaultValue;
return parsed;
}
/// <summary>
/// Reads the InventorySlot from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the InventorySlot from.</param>
/// <param name="i">The field index to read.</param>
/// <returns>The InventorySlot read from the <see cref="IDataRecord"/>.</returns>
public static InventorySlot GetInventorySlot(this IDataRecord r, int i)
{
return InventorySlot.Read(r, i);
}
/// <summary>
/// Reads the InventorySlot from an <see cref="IDataRecord"/>.
/// </summary>
/// <param name="r"><see cref="IDataRecord"/> to read the InventorySlot from.</param>
/// <param name="name">The name of the field to read the value from.</param>
/// <returns>The InventorySlot read from the <see cref="IDataRecord"/>.</returns>
public static InventorySlot GetInventorySlot(this IDataRecord r, string name)
{
return InventorySlot.Read(r, name);
}
/// <summary>
/// Parses the InventorySlot from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <returns>The InventorySlot parsed from the string.</returns>
public static InventorySlot ParseInventorySlot(this Parser parser, string value)
{
return new InventorySlot(parser.ParseByte(value));
}
/// <summary>
/// Reads the InventorySlot from a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to read the InventorySlot from.</param>
/// <returns>The InventorySlot read from the BitStream.</returns>
public static InventorySlot ReadInventorySlot(this BitStream bitStream)
{
return InventorySlot.Read(bitStream);
}
/// <summary>
/// Reads the InventorySlot from an IValueReader.
/// </summary>
/// <param name="valueReader">IValueReader to read the InventorySlot from.</param>
/// <param name="name">The unique name of the value to read.</param>
/// <returns>The InventorySlot read from the IValueReader.</returns>
public static InventorySlot ReadInventorySlot(this IValueReader valueReader, string name)
{
return InventorySlot.Read(valueReader, name);
}
/// <summary>
/// Tries to parse the InventorySlot from a string.
/// </summary>
/// <param name="parser">The Parser to use.</param>
/// <param name="value">The string to parse.</param>
/// <param name="outValue">If this method returns true, contains the parsed InventorySlot.</param>
/// <returns>True if the parsing was successfully; otherwise false.</returns>
public static bool TryParse(this Parser parser, string value, out InventorySlot outValue)
{
byte tmp;
var ret = parser.TryParse(value, out tmp);
outValue = new InventorySlot(tmp);
return ret;
}
/// <summary>
/// Writes a InventorySlot to a BitStream.
/// </summary>
/// <param name="bitStream">BitStream to write to.</param>
/// <param name="value">InventorySlot to write.</param>
public static void Write(this BitStream bitStream, InventorySlot value)
{
value.Write(bitStream);
}
/// <summary>
/// Writes a InventorySlot to a IValueWriter.
/// </summary>
/// <param name="valueWriter">IValueWriter to write to.</param>
/// <param name="name">Unique name of the InventorySlot that will be used to distinguish it
/// from other values when reading.</param>
/// <param name="value">InventorySlot to write.</param>
public static void Write(this IValueWriter valueWriter, string name, InventorySlot value)
{
value.Write(valueWriter, name);
}
}
}
| |
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Vevo;
public partial class AdminAdvanced_Components_Template_AdminContent : System.Web.UI.UserControl
{
private ITemplate _messageTemplate;
private ITemplate _validationSummaryTemplate;
private ITemplate _validationDenotesTemplate;
private ITemplate _languageControlTemplate;
private ITemplate _buttonEventTemplate;
private ITemplate _buttonCommandTemplate;
private ITemplate _buttonEventInnerBoxTemplate;
private ITemplate _topContentBoxTemplate;
private ITemplate _headerMessageTemplate;
//For Grid Template.
private ITemplate _filterTemplate;
private ITemplate _specialFilterTemplate;
private ITemplate _pageNumberTemplate;
private ITemplate _gridTemplate;
private ITemplate _bottomContentBoxTemplate;
private ITemplate _contentTemplate;
private ITemplate _plainContentTemplate;
private string _headerText;
private bool _showBorderContent = true;
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate PlainContentTemplate
{
get { return _plainContentTemplate; }
set { _plainContentTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ContentTemplate
{
get { return _contentTemplate; }
set { _contentTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate MessageTemplate
{
get { return _messageTemplate; }
set { _messageTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ValidationSummaryTemplate
{
get { return _validationSummaryTemplate; }
set { _validationSummaryTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ValidationDenotesTemplate
{
get { return _validationDenotesTemplate; }
set { _validationDenotesTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate LanguageControlTemplate
{
get { return _languageControlTemplate; }
set { _languageControlTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ButtonEventTemplate
{
get { return _buttonEventTemplate; }
set { _buttonEventTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ButtonCommandTemplate
{
get { return _buttonCommandTemplate; }
set { _buttonCommandTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate ButtonEventInnerBoxTemplate
{
get { return _buttonEventInnerBoxTemplate; }
set { _buttonEventInnerBoxTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate TopContentBoxTemplate
{
get { return _topContentBoxTemplate; }
set { _topContentBoxTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate HeaderMessageTemplate
{
get { return _headerMessageTemplate; }
set { _headerMessageTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate FilterTemplate
{
get { return _filterTemplate; }
set { _filterTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate SpecialFilterTemplate
{
get { return _specialFilterTemplate; }
set { _specialFilterTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate PageNumberTemplate
{
get { return _pageNumberTemplate; }
set { _pageNumberTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate GridTemplate
{
get { return _gridTemplate; }
set { _gridTemplate = value; }
}
[TemplateInstance( TemplateInstance.Single )]
[PersistenceMode( PersistenceMode.InnerProperty )]
public ITemplate BottomContentBoxTemplate
{
get { return _bottomContentBoxTemplate; }
set { _bottomContentBoxTemplate = value; }
}
[PersistenceMode( PersistenceMode.Attribute )]
public String HeaderText
{
get { return _headerText; }
set { _headerText = value; }
}
[PersistenceMode( PersistenceMode.Attribute )]
public Boolean ShowBorderContent
{
get { return _showBorderContent; }
set { _showBorderContent = value; }
}
protected override void OnInit( EventArgs e )
{
base.OnInit( e );
uxMessagePlaceHolder.Controls.Clear();
uxValidationSummaryPlaceHolder.Controls.Clear();
uxValidationDenotePlaceHolder.Controls.Clear();
uxLanguageControlPlaceHolder.Controls.Clear();
uxButtonEventPlaceHolder.Controls.Clear();
uxButtonCommandPlaceHolder.Controls.Clear();
uxButtonEventInnerBoxPlaceHolder.Controls.Clear();
uxTopContentBoxPlaceHolder.Controls.Clear();
uxFilterPlaceHolder.Controls.Clear();
uxSpecialFilterPlaceHolder.Controls.Clear();
uxPageNumberPlaceHolder.Controls.Clear();
uxGridPlaceHolder.Controls.Clear();
uxBottomContentBoxPlaceHolder.Controls.Clear();
uxContentPlaceHolder.Controls.Clear();
// Message.
ContentContainer container = new ContentContainer();
if (MessageTemplate != null)
{
MessageTemplate.InstantiateIn( container );
uxMessagePlaceHolder.Controls.Add( container );
uxMessagePlaceHolder.Visible = true;
}
else
{
uxMessagePlaceHolder.Controls.Add( new LiteralControl( "No Message Defined" ) );
uxMessagePlaceHolder.Visible = false;
}
// Validation Summary
container = new ContentContainer();
if (ValidationSummaryTemplate != null)
{
ValidationSummaryTemplate.InstantiateIn( container );
uxValidationSummaryPlaceHolder.Controls.Add( container );
uxValidationSummaryPanel.Visible = true;
}
else
{
uxValidationSummaryPlaceHolder.Controls.Add( new LiteralControl( "No Validation Summary Defined" ) );
uxValidationSummaryPanel.Visible = false;
}
// Validation Denotes
container = new ContentContainer();
if (ValidationDenotesTemplate != null)
{
ValidationDenotesTemplate.InstantiateIn( container );
uxValidationDenotePlaceHolder.Controls.Add( container );
uxValidationDenotePanel.Visible = true;
}
else
{
uxValidationDenotePlaceHolder.Controls.Add( new LiteralControl( "No Validation Denotes Defined" ) );
uxValidationDenotePanel.Visible = false;
}
// If all message disapear message panel will not show.
if (!uxMessagePlaceHolder.Visible & !uxValidationSummaryPanel.Visible)
uxMessagePanel.Visible = false;
else
uxMessagePanel.Visible = true;
container = new ContentContainer();
if (LanguageControlTemplate != null)
{
LanguageControlTemplate.InstantiateIn( container );
uxLanguageControlPlaceHolder.Controls.Add( container );
uxLanguageControlPanel.Visible = true;
}
else
{
uxLanguageControlPlaceHolder.Controls.Add( new LiteralControl( "No Language Control Defined" ) );
uxLanguageControlPanel.Visible = false;
}
// If don't have any language and message top panel will not show.
if (!uxFilterPanel.Visible & !uxLanguageControlPanel.Visible & !uxSpecialFilterPanel.Visible)
uxTopPagePanel.Visible = false;
else
uxTopPagePanel.Visible = true;
if (ButtonEventTemplate == null)
uxButtonEventPanel.Visible = false;
else
{
container = new ContentContainer();
ButtonEventTemplate.InstantiateIn( container );
uxButtonEventPlaceHolder.Controls.Add( container );
uxButtonEventPanel.Visible = true;
}
if (ButtonCommandTemplate == null)
{
uxButtonCommandPanel.Visible = false;
}
else
{
container = new ContentContainer();
ButtonCommandTemplate.InstantiateIn( container );
uxButtonCommandPlaceHolder.Controls.Add( container );
uxButtonCommandPanel.Visible = true;
}
if (ButtonEventInnerBoxTemplate == null)
uxButtonEventInnerBoxPanel.Visible = false;
else
{
container = new ContentContainer();
ButtonEventInnerBoxTemplate.InstantiateIn( container );
uxButtonEventInnerBoxPlaceHolder.Controls.Add( container );
uxButtonEventInnerBoxPanel.Visible = true;
}
container = new ContentContainer();
if (TopContentBoxTemplate != null)
{
TopContentBoxTemplate.InstantiateIn( container );
uxTopContentBoxPlaceHolder.Controls.Add( container );
uxTopContentBoxPanel.Visible = true;
}
else
{
uxTopContentBoxPlaceHolder.Controls.Add( new LiteralControl( "No TopContentBox Content Defined" ) );
uxTopContentBoxPlaceHolder.Visible = false;
uxTopContentBoxPanel.Visible = false;
}
container = new ContentContainer();
if (ContentTemplate != null)
{
ContentTemplate.InstantiateIn( container );
uxContentPlaceHolder.Controls.Add( container );
uxContentPanel.Visible = true;
}
else
{
uxContentPlaceHolder.Controls.Add( new LiteralControl( "No Template Defined" ) );
uxContentPanel.Visible = false;
}
container = new ContentContainer();
if (PlainContentTemplate != null)
{
PlainContentTemplate.InstantiateIn( container );
uxPlainContentPlaceHolder.Controls.Add( container );
uxPlainContentPanel.Visible = true;
}
else
{
uxPlainContentPlaceHolder.Controls.Add( new LiteralControl( "No Template Defined" ) );
uxPlainContentPanel.Visible = false;
}
if (FilterTemplate == null)
uxFilterPanel.Visible = false;
else
{
container = new ContentContainer();
FilterTemplate.InstantiateIn( container );
uxFilterPlaceHolder.Controls.Add( container );
uxFilterPanel.Visible = true;
}
if (SpecialFilterTemplate == null)
uxSpecialFilterPanel.Visible = false;
else
{
container = new ContentContainer();
SpecialFilterTemplate.InstantiateIn( container );
uxSpecialFilterPlaceHolder.Controls.Add( container );
uxSpecialFilterPanel.Visible = true;
}
if (PageNumberTemplate == null)
uxPageNumberPanel.Visible = false;
else
{
container = new ContentContainer();
PageNumberTemplate.InstantiateIn( container );
uxPageNumberPlaceHolder.Controls.Add( container );
uxPageNumberPanel.Visible = true;
}
if (GridTemplate == null)
uxGridPanel.Visible = false;
else
{
container = new ContentContainer();
GridTemplate.InstantiateIn( container );
uxGridPlaceHolder.Controls.Add( container );
uxGridPanel.Visible = true;
}
if (uxGridPanel.Visible || uxPageNumberPanel.Visible || uxTopContentBoxPlaceHolder.Visible || uxButtonCommandPanel.Visible || uxButtonEventInnerBoxPanel.Visible)
uxTopContentBoxSet.Visible = true;
else
uxTopContentBoxSet.Visible = false;
if (BottomContentBoxTemplate == null)
{
uxBottomContentBoxPlaceHolder.Visible = false;
uxBottomContentBoxPanel.Visible = false;
}
else
{
container = new ContentContainer();
BottomContentBoxTemplate.InstantiateIn( container );
uxBottomContentBoxPlaceHolder.Controls.Add( container );
uxBottomContentBoxPlaceHolder.Visible = true;
}
if (HeaderMessageTemplate != null)
{
HeaderMessageTemplate.InstantiateIn( container );
uxHeaderMeassagePlaceHolder.Controls.Add( container );
uxHeaderMeassagePanel.Visible = true;
}
else
{
uxHeaderMeassagePlaceHolder.Controls.Add( new LiteralControl( "No Template Defined" ) );
uxHeaderMeassagePanel.Visible = false;
}
}
protected void Page_Load( object sender, EventArgs e )
{
}
protected void Page_PreRender( object sender, EventArgs e )
{
if (!ShowBorderContent)
uxTopContentBoxSet.CssClass = "CssAdminContentPanel dn";
else
uxTopContentBoxSet.CssClass = "CssAdminContentPanel";
}
}
| |
///<summary>
///HTTP Method: POST
///Access: Private
public string UpdateUserAdmin( ) {
RestRequest request = new RestRequest($"/User/UpdateUserAdmin/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string CreateConversation( ) {
RestRequest request = new RestRequest($"/Message/CreateConversation/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string CreateConversationV2( ) {
RestRequest request = new RestRequest($"/Message/CreateConversationV2/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetAllianceInvitedToJoinInvitations( ) {
RestRequest request = new RestRequest($"/Message/AllianceInvitations/InvitationsToJoinAnotherGroup/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetAllianceJoinInvitations( ) {
RestRequest request = new RestRequest($"/Message/AllianceInvitations/RequestsToJoinYourGroup/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetConversationById( ) {
RestRequest request = new RestRequest($"/Message/GetConversationById/{conversationId}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
///<param name="format"></param>
///</summary>
public string GetConversationByIdV2( object format ) {
RestRequest request = new RestRequest($"/Message/GetConversationByIdV2/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetConversationsV2( ) {
RestRequest request = new RestRequest($"/Message/GetConversationsV2/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetConversationsV3( ) {
RestRequest request = new RestRequest($"/Message/GetConversationsV3/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
///<param name="format"></param>
///</summary>
public string GetConversationsV4( object format ) {
RestRequest request = new RestRequest($"/Message/GetConversationsV4/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access: Private
///<param name="format">Unknown. Default is 0.</param>
///</summary>
public string GetConversationsV5( object format ) {
RestRequest request = new RestRequest($"/Message/GetConversationsV5/{currentPage}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetConversationThreadV2( ) {
RestRequest request = new RestRequest($"/Message/GetConversationThreadV2/{param1}/{param2}/{param3}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
///<param name="format"></param>
///<param name="before"></param>
///<param name="after"></param>
///</summary>
public string GetConversationThreadV3( object format, object before, object after ) {
RestRequest request = new RestRequest($"/Message/GetConversationThreadV3/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");request.AddParameter("before, before");request.AddParameter("after, after");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetConversationWithMemberId( ) {
RestRequest request = new RestRequest($"/Message/GetConversationWithMember/{memberId}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
///<param name="format"></param>
///</summary>
public string GetConversationWithMemberIdV2( object format ) {
RestRequest request = new RestRequest($"/Message/GetConversationWithMemberV2/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
///<param name="format"></param>
///</summary>
public string GetGroupConversations( object format ) {
RestRequest request = new RestRequest($"/Message/GetGroupConversations/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
request.AddParameter("format, format");
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetInvitationDetails( ) {
RestRequest request = new RestRequest($"/Message/Invitations/{param1}/Details/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetTotalConversationCount( ) {
RestRequest request = new RestRequest($"/Message/GetTotalConversationCount/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetUnreadConversationCountV2( ) {
RestRequest request = new RestRequest($"/Message/GetUnreadPrivateConversationCount/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetUnreadConversationCountV3( ) {
RestRequest request = new RestRequest($"/Message/GetUnreadConversationCountV3/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetUnreadConversationCountV4( ) {
RestRequest request = new RestRequest($"/Message/GetUnreadConversationCountV4/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string GetUnreadGroupConversationCount( ) {
RestRequest request = new RestRequest($"/Message/GetUnreadGroupConversationCount/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: GET
///Access:
public string LeaveConversation( ) {
RestRequest request = new RestRequest($"/Message/LeaveConversation/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string ModerateGroupWall( ) {
RestRequest request = new RestRequest($"/Message/ModerateGroupWall/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string ReviewAllInvitations( ) {
RestRequest request = new RestRequest($"/Message/Invitations/ReviewAllDirect/{param1}/{param2}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string ReviewInvitation( ) {
RestRequest request = new RestRequest($"/Message/Invitations/{param1}/{param2}/{param3}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string ReviewInvitationDirect( ) {
RestRequest request = new RestRequest($"/Message/Invitations/ReviewDirect/{invitationId}/{invitationResponseState}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string ReviewInvitations( ) {
RestRequest request = new RestRequest($"/Message/Invitations/ReviewListDirect/{param1}/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string SaveMessageV2( ) {
RestRequest request = new RestRequest($"/Message/SaveMessageV2/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string SaveMessageV3( ) {
RestRequest request = new RestRequest($"/Message/SaveMessageV3/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string SaveMessageV4( ) {
RestRequest request = new RestRequest($"/Message/SaveMessageV4/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
///<summary>
///HTTP Method: POST
///Access: Private
public string UpdateConversationLastViewedTimestamp( ) {
RestRequest request = new RestRequest($"/Message/Conversations/UpdateLastViewedTimestamp/");
request.AddHeader("X-API-KEY", Apikey);
IRestResponse response = client.Execute(request);
return response.Response;
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Orleans;
using Orleans.Runtime;
namespace OrleansManager
{
class Program
{
private static IManagementGrain systemManagement;
static void Main(string[] args)
{
Console.WriteLine("Invoked OrleansManager.exe with arguments {0}", Utils.EnumerableToString(args));
var command = args.Length > 0 ? args[0].ToLowerInvariant() : "";
if (String.IsNullOrEmpty(command) || command.Equals("/?") || command.Equals("-?"))
{
PrintUsage();
Environment.Exit(-1);
}
try
{
RunCommand(command, args);
Environment.Exit(0);
}
catch (Exception exc)
{
Console.WriteLine("Terminating due to exception:");
Console.WriteLine(exc.ToString());
}
}
private static void RunCommand(string command, string[] args)
{
GrainClient.Initialize();
systemManagement = GrainClient.GrainFactory.GetGrain<IManagementGrain>(0);
Dictionary<string, string> options = args.Skip(1)
.Where(s => s.StartsWith("-"))
.Select(s => s.Substring(1).Split('='))
.ToDictionary(a => a[0].ToLowerInvariant(), a => a.Length > 1 ? a[1] : "");
var restWithoutOptions = args.Skip(1).Where(s => !s.StartsWith("-")).ToArray();
switch (command)
{
case "grainstats":
PrintSimpleGrainStatistics(restWithoutOptions);
break;
case "fullgrainstats":
PrintGrainStatistics(restWithoutOptions);
break;
case "collect":
CollectActivations(options, restWithoutOptions);
break;
case "unregister":
var unregisterArgs = args.Skip(1).ToArray();
UnregisterGrain(unregisterArgs);
break;
case "lookup":
var lookupArgs = args.Skip(1).ToArray();
LookupGrain(lookupArgs);
break;
case "grainreport":
var grainReportArgs = args.Skip(1).ToArray();
GrainReport(grainReportArgs);
break;
default:
PrintUsage();
break;
}
}
private static void PrintUsage()
{
Console.WriteLine(@"Usage:
OrleansManager grainstats [silo1 silo2 ...]
OrleansManager fullgrainstats [silo1 silo2 ...]
OrleansManager collect [-memory=nnn] [-age=nnn] [silo1 silo2 ...]
OrleansManager unregister <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid>
OrleansManager lookup <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid>
OrleansManager grainReport <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid>");
}
private static void CollectActivations(IReadOnlyDictionary<string, string> options, IEnumerable<string> args)
{
var silos = args.Select(ParseSilo).ToArray();
int ageLimitSeconds = 0;
string s;
if (options.TryGetValue("age", out s))
Int32.TryParse(s, out ageLimitSeconds);
var ageLimit = TimeSpan.FromSeconds(ageLimitSeconds);
if (ageLimit > TimeSpan.Zero)
systemManagement.ForceActivationCollection(silos, ageLimit);
else
systemManagement.ForceGarbageCollection(silos);
}
private static void PrintSimpleGrainStatistics(IEnumerable<string> args)
{
var silos = args.Select(ParseSilo).ToArray();
var stats = systemManagement.GetSimpleGrainStatistics(silos).Result;
Console.WriteLine("Silo Activations Type");
Console.WriteLine("--------------------- ----------- ------------");
foreach (var s in stats.OrderBy(s => s.SiloAddress + s.GrainType))
Console.WriteLine("{0} {1} {2}", s.SiloAddress.ToString().PadRight(21), Pad(s.ActivationCount, 11), s.GrainType);
}
private static void PrintGrainStatistics(IEnumerable<string> args)
{
var silos = args.Select(ParseSilo).ToArray();
var stats = systemManagement.GetSimpleGrainStatistics(silos).Result;
Console.WriteLine("Act Type");
Console.WriteLine("-------- ----- ------ ------------");
foreach (var s in stats.OrderBy(s => Tuple.Create(s.GrainType, s.ActivationCount)))
Console.WriteLine("{0} {1}", Pad(s.ActivationCount, 8), s.GrainType);
}
private static void GrainReport(string[] args)
{
var grainId = ConstructGrainId(args, "GrainReport");
var silos = GetSiloAddresses();
if (silos == null || silos.Count == 0) return;
var reports = new List<DetailedGrainReport>();
foreach (var silo in silos)
{
WriteStatus(string.Format("**Calling GetDetailedGrainReport({0}, {1})", silo, grainId));
try
{
var siloControl = GrainClient.InternalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo);
DetailedGrainReport grainReport = siloControl.GetDetailedGrainReport(grainId).Result;
reports.Add(grainReport);
}
catch (Exception exc)
{
WriteStatus(string.Format("**Failed to get grain report from silo {0}. Exc: {1}", silo, exc.ToString()));
}
}
foreach (var grainReport in reports)
WriteStatus(grainReport.ToString());
LookupGrain(args);
}
private static void UnregisterGrain(string[] args)
{
var grainId = ConstructGrainId(args, "unregister");
var silo = GetSiloAddress();
if (silo == null) return;
var directory = GrainClient.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
WriteStatus(string.Format("**Calling DeleteGrain({0}, {1})", silo, grainId));
directory.DeleteGrainAsync(grainId).Wait();
WriteStatus(string.Format("**DeleteGrain finished OK."));
}
private static async void LookupGrain(string[] args)
{
var grainId = ConstructGrainId(args, "lookup");
var silo = GetSiloAddress();
if (silo == null) return;
var directory = GrainClient.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo);
WriteStatus(string.Format("**Calling LookupGrain({0}, {1})", silo, grainId));
//Tuple<List<Tuple<SiloAddress, ActivationId>>, int> lookupResult = await directory.FullLookUp(grainId, true);
var lookupResult = await directory.LookupAsync(grainId);
WriteStatus(string.Format("**LookupGrain finished OK. Lookup result is:"));
var list = lookupResult.Addresses;
if (list == null)
{
WriteStatus(string.Format("**The returned activation list is null."));
return;
}
if (list.Count == 0)
{
WriteStatus(string.Format("**The returned activation list is empty."));
return;
}
Console.WriteLine("**There {0} {1} activations registered in the directory for this grain. The activations are:", (list.Count > 1) ? "are" : "is", list.Count);
foreach (var tuple in list)
{
WriteStatus(string.Format("**Activation {0} on silo {1}", tuple.Activation, tuple.Silo));
}
}
private static GrainId ConstructGrainId(string[] args, string operation)
{
if (args == null || args.Length < 2)
{
PrintUsage();
return null;
}
string interfaceTypeCodeOrImplClassName = args[0];
int interfaceTypeCodeDataLong;
long implementationTypeCode;
if (Int32.TryParse(interfaceTypeCodeOrImplClassName, out interfaceTypeCodeDataLong))
{
// parsed it as int, so it is an interface type code.
implementationTypeCode = TypeCodeMapper.GetImplementation(interfaceTypeCodeDataLong).GrainTypeCode;
}
else
{
// interfaceTypeCodeOrImplClassName is the implementation class name
implementationTypeCode = TypeCodeMapper.GetImplementation(interfaceTypeCodeOrImplClassName).GrainTypeCode;
}
var grainIdStr = args[1];
GrainId grainId = null;
long grainIdLong;
Guid grainIdGuid;
if (Int64.TryParse(grainIdStr, out grainIdLong))
grainId = GrainId.GetGrainId(implementationTypeCode, grainIdLong);
else if (Guid.TryParse(grainIdStr, out grainIdGuid))
grainId = GrainId.GetGrainId(implementationTypeCode, grainIdGuid);
WriteStatus(string.Format("**Full Grain Id to {0} is: GrainId = {1}", operation, grainId.ToFullString()));
return grainId;
}
private static SiloAddress GetSiloAddress()
{
List<SiloAddress> silos = GetSiloAddresses();
if (silos == null || silos.Count==0) return null;
return silos.FirstOrDefault();
}
private static List<SiloAddress> GetSiloAddresses()
{
IList<Uri> gateways = GrainClient.Gateways;
if (gateways.Count >= 1)
return gateways.Select(Utils.ToSiloAddress).ToList();
WriteStatus(string.Format("**Retrieved only zero gateways from Client.Gateways"));
return null;
}
private static string Pad(int value, int width)
{
return value.ToString("d").PadRight(width);
}
private static SiloAddress ParseSilo(string s)
{
return SiloAddress.FromParsableString(s);
}
public static void WriteStatus(string msg)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(msg);
Console.ResetColor();
}
}
}
| |
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 ForumSystem.Web.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 2008-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
* __ _ _ ___
* ( )( \/\/ )/ __)
* /__\ \ / \__ \
* (_)(_) \/\/ (___/
*
* AWS SDK for .NET
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
namespace Amazon.EC2.Model
{
/// <summary>
/// Conversion task
/// </summary>
[XmlRootAttribute(IsNullable = false)]
public class ConversionTaskType
{
private string conversionTaskIdField;
private string expirationTimeField;
private ImportVolumeTaskDetailsType importVolumeRequestField;
private ImportInstanceTaskDetailsType importInstanceRequestField;
private string stateField;
private string statusMessageField;
/// <summary>
/// ID of the conversion task.
/// </summary>
[XmlElementAttribute(ElementName = "ConversionTaskId")]
public string ConversionTaskId
{
get { return this.conversionTaskIdField; }
set { this.conversionTaskIdField = value; }
}
/// <summary>
/// Sets the ID of the conversion task.
/// </summary>
/// <param name="conversionTaskId">ID of the conversion task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithConversionTaskId(string conversionTaskId)
{
this.conversionTaskIdField = conversionTaskId;
return this;
}
/// <summary>
/// Checks if ConversionTaskId property is set
/// </summary>
/// <returns>true if ConversionTaskId property is set</returns>
public bool IsSetConversionTaskId()
{
return this.conversionTaskIdField != null;
}
/// <summary>
/// The time when the task expires.
/// If the upload isn't complete before the expiration time, the task is automatically canceled.
/// </summary>
[XmlElementAttribute(ElementName = "ExpirationTime")]
public string ExpirationTime
{
get { return this.expirationTimeField; }
set { this.expirationTimeField = value; }
}
/// <summary>
/// Sets the time when the task expires.
/// </summary>
/// <param name="expirationTime">When the task expires. If the upload isn't complete before the expiration time, the task is automatically canceled.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithExpirationTime(string expirationTime)
{
this.expirationTimeField = expirationTime;
return this;
}
/// <summary>
/// Checks if ExpirationTime property is set
/// </summary>
/// <returns>true if ExpirationTime property is set</returns>
public bool IsSetExpirationTime()
{
return this.expirationTimeField != null;
}
/// <summary>
/// If the task is for importing a volume, this contains information about the import volume task.
/// </summary>
[XmlElementAttribute(ElementName = "ImportVolumeRequest")]
public ImportVolumeTaskDetailsType ImportVolumeRequest
{
get { return this.importVolumeRequestField; }
set { this.importVolumeRequestField = value; }
}
/// <summary>
/// Sets the import volume task information.
/// </summary>
/// <param name="importVolumeRequest">If the task is for importing a volume, this contains information about the import volume task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithImportVolumeRequest(ImportVolumeTaskDetailsType importVolumeRequest)
{
this.importVolumeRequestField = importVolumeRequest;
return this;
}
/// <summary>
/// Checks if ImportVolumeRequest property is set
/// </summary>
/// <returns>true if ImportVolumeRequest property is set</returns>
public bool IsSetImportVolumeRequest()
{
return this.importVolumeRequestField != null;
}
/// <summary>
/// If the task is for importing an instance, this contains information about the import instance task.
/// </summary>
[XmlElementAttribute(ElementName = "ImportInstanceRequest")]
public ImportInstanceTaskDetailsType ImportInstanceRequest
{
get { return this.importInstanceRequestField; }
set { this.importInstanceRequestField = value; }
}
/// <summary>
/// Sets the import instance task information.
/// </summary>
/// <param name="importInstanceRequest">If the task is for importing an instance, this contains information about the import instance task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithImportInstanceRequest(ImportInstanceTaskDetailsType importInstanceRequest)
{
this.importInstanceRequestField = importInstanceRequest;
return this;
}
/// <summary>
/// Checks if ImportInstanceRequest property is set
/// </summary>
/// <returns>true if ImportInstanceRequest property is set</returns>
public bool IsSetImportInstanceRequest()
{
return this.importInstanceRequestField != null;
}
/// <summary>
/// The state of the conversion task.
/// </summary>
[XmlElementAttribute(ElementName = "State")]
public string State
{
get { return this.stateField; }
set { this.stateField = value; }
}
/// <summary>
/// Sets the state of the conversion task.
/// Valid values: active | cancelling | cancelled | completed
/// </summary>
/// <param name="state">State of the conversion task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithState(string state)
{
this.stateField = state;
return this;
}
/// <summary>
/// Checks if State property is set
/// </summary>
/// <returns>true if State property is set</returns>
public bool IsSetState()
{
return this.stateField != null;
}
/// <summary>
/// Status message related to the conversion task.
/// </summary>
[XmlElementAttribute(ElementName = "StatusMessage")]
public string StatusMessage
{
get { return this.statusMessageField; }
set { this.statusMessageField = value; }
}
/// <summary>
/// Sets the status message related to the conversion task.
/// </summary>
/// <param name="statusMessage">Status message related to the conversion task.</param>
/// <returns>this instance</returns>
[Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
public ConversionTaskType WithStatusMessage(string statusMessage)
{
this.statusMessageField = statusMessage;
return this;
}
/// <summary>
/// Checks if StatusMessage property is set
/// </summary>
/// <returns>true if StatusMessage property is set</returns>
public bool IsSetStatusMessage()
{
return this.statusMessageField != null;
}
}
}
| |
/*
* Created by SharpDevelop.
* User: lextm
* Date: 2008/4/28
* Time: 18:35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
using System.Collections.Generic;
using System.Net;
using Lextm.SharpSnmpLib.Security;
using NUnit.Framework;
using System.Net.Sockets;
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Lextm.SharpSnmpLib.Objects;
using Lextm.SharpSnmpLib.Pipeline;
#pragma warning disable 1591
namespace Lextm.SharpSnmpLib.Messaging.Tests
{
using JetBrains.dotMemoryUnit;
/// <summary>
/// Description of TestGetMessage.
/// </summary>
[TestFixture]
public class GetRequestMessageTestFixture
{
[Test]
[Category("Default")]
public void Test()
{
byte[] expected = Properties.Resources.get;
ISnmpMessage message = MessageFactory.ParseMessages(expected, new UserRegistry())[0];
Assert.AreEqual(SnmpType.GetRequestPdu, message.TypeCode());
GetRequestPdu pdu = (GetRequestPdu)message.Pdu();
Assert.AreEqual(1, pdu.Variables.Count);
Variable v = pdu.Variables[0];
Assert.AreEqual(new uint[] { 1, 3, 6, 1, 2, 1, 1, 6, 0 }, v.Id.ToNumerical());
Assert.AreEqual(typeof(Null), v.Data.GetType());
Assert.GreaterOrEqual(expected.Length, message.ToBytes().Length);
}
[Test]
[Category("Default")]
public void TestConstructor()
{
List<Variable> list = new List<Variable>(1)
{
new Variable(new ObjectIdentifier(new uint[] {1, 3, 6, 1, 2, 1, 1, 6, 0}),
new Null())
};
GetRequestMessage message = new GetRequestMessage(0, VersionCode.V2, new OctetString("public"), list);
Assert.GreaterOrEqual(Properties.Resources.get.Length, message.ToBytes().Length);
}
[Test]
[Category("Default")]
public void TestConstructorV3Auth1()
{
const string bytes = "30 73" +
"02 01 03 " +
"30 0F " +
"02 02 35 41 " +
"02 03 00 FF E3" +
"04 01 05" +
"02 01 03" +
"04 2E " +
"30 2C" +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"02 01 0D " +
"02 01 57 " +
"04 05 6C 65 78 6C 69 " +
"04 0C 1C 6D 67 BF B2 38 ED 63 DF 0A 05 24 " +
"04 00 " +
"30 2D " +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"04 00 " +
"A0 1A 02 02 01 AF 02 01 00 02 01 00 30 0E 30 0C 06 08 2B 06 01 02 01 01 03 00 05 00";
ReportMessage report = new ReportMessage(
VersionCode.V3,
new Header(
new Integer32(13633),
new Integer32(0xFFE3),
0),
new SecurityParameters(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
new Integer32(0x0d),
new Integer32(0x57),
new OctetString("lexli"),
new OctetString(new byte[12]),
OctetString.Empty),
new Scope(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
OctetString.Empty,
new ReportPdu(
0x01AF,
ErrorCode.NoError,
0,
new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })),
DefaultPrivacyProvider.DefaultPair,
null);
IPrivacyProvider privacy = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass")));
GetRequestMessage request = new GetRequestMessage(
VersionCode.V3,
13633,
0x01AF,
new OctetString("lexli"),
new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) },
privacy,
Messenger.MaxMessageSize,
report);
Assert.AreEqual(Levels.Authentication | Levels.Reportable, request.Header.SecurityLevel);
Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
}
[Test]
[Category("Default")]
public void TestConstructorV2AuthMd5PrivDes()
{
const string bytes = "30 81 80 02 01 03 30 0F 02 02 6C 99 02 03 00 FF" +
"E3 04 01 07 02 01 03 04 38 30 36 04 0D 80 00 1F" +
"88 80 E9 63 00 00 D6 1F F4 49 02 01 14 02 01 35" +
"04 07 6C 65 78 6D 61 72 6B 04 0C 80 50 D9 A1 E7" +
"81 B6 19 80 4F 06 C0 04 08 00 00 00 01 44 2C A3" +
"B5 04 30 4B 4F 10 3B 73 E1 E4 BD 91 32 1B CB 41" +
"1B A1 C1 D1 1D 2D B7 84 16 CA 41 BF B3 62 83 C4" +
"29 C5 A4 BC 32 DA 2E C7 65 A5 3D 71 06 3C 5B 56" +
"FB 04 A4";
MD5AuthenticationProvider auth = new MD5AuthenticationProvider(new OctetString("testpass"));
IPrivacyProvider privacy = new DESPrivacyProvider(new OctetString("passtest"), auth);
GetRequestMessage request = new GetRequestMessage(
VersionCode.V3,
new Header(
new Integer32(0x6C99),
new Integer32(0xFFE3),
Levels.Authentication | Levels.Privacy | Levels.Reportable),
new SecurityParameters(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
new Integer32(0x14),
new Integer32(0x35),
new OctetString("lexmark"),
new OctetString(ByteTool.Convert("80 50 D9 A1 E7 81 B6 19 80 4F 06 C0")),
new OctetString(ByteTool.Convert("00 00 00 01 44 2C A3 B5"))),
new Scope(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
OctetString.Empty,
new GetRequestPdu(
0x3A25,
new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0")) })),
privacy,
null);
Assert.AreEqual(Levels.Authentication | Levels.Privacy | Levels.Reportable, request.Header.SecurityLevel);
Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
}
[Test]
[Category("Default")]
public void TestConstructorV3AuthMd5()
{
const string bytes = "30 73" +
"02 01 03 " +
"30 0F " +
"02 02 35 41 " +
"02 03 00 FF E3" +
"04 01 05" +
"02 01 03" +
"04 2E " +
"30 2C" +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"02 01 0D " +
"02 01 57 " +
"04 05 6C 65 78 6C 69 " +
"04 0C 1C 6D 67 BF B2 38 ED 63 DF 0A 05 24 " +
"04 00 " +
"30 2D " +
"04 0D 80 00 1F 88 80 E9 63 00 00 D6 1F F4 49 " +
"04 00 " +
"A0 1A 02 02 01 AF 02 01 00 02 01 00 30 0E 30 0C 06 08 2B 06 01 02 01 01 03 00 05 00";
IPrivacyProvider pair = new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("testpass")));
GetRequestMessage request = new GetRequestMessage(
VersionCode.V3,
new Header(
new Integer32(13633),
new Integer32(0xFFE3),
Levels.Authentication | Levels.Reportable),
new SecurityParameters(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
new Integer32(0x0d),
new Integer32(0x57),
new OctetString("lexli"),
new OctetString(ByteTool.Convert("1C 6D 67 BF B2 38 ED 63 DF 0A 05 24")),
OctetString.Empty),
new Scope(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
OctetString.Empty,
new GetRequestPdu(
0x01AF,
new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), new Null()) })),
pair,
null);
Assert.AreEqual(Levels.Authentication | Levels.Reportable, request.Header.SecurityLevel);
Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
}
[Test]
[Category("Default")]
public void TestConstructorV3AuthSha()
{
const string bytes = "30 77 02 01 03 30 0F 02 02 47 21 02 03 00 FF E3" +
"04 01 05 02 01 03 04 32 30 30 04 0D 80 00 1F 88" +
"80 E9 63 00 00 D6 1F F4 49 02 01 15 02 02 01 5B" +
"04 08 6C 65 78 74 75 64 69 6F 04 0C 7B 62 65 AE" +
"D3 8F E3 7D 58 45 5C 6C 04 00 30 2D 04 0D 80 00" +
"1F 88 80 E9 63 00 00 D6 1F F4 49 04 00 A0 1A 02" +
"02 56 FF 02 01 00 02 01 00 30 0E 30 0C 06 08 2B" +
"06 01 02 01 01 03 00 05 00";
IPrivacyProvider pair = new DefaultPrivacyProvider(new SHA1AuthenticationProvider(new OctetString("password")));
GetRequestMessage request = new GetRequestMessage(
VersionCode.V3,
new Header(
new Integer32(0x4721),
new Integer32(0xFFE3),
Levels.Authentication | Levels.Reportable),
new SecurityParameters(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
new Integer32(0x15),
new Integer32(0x015B),
new OctetString("lextudio"),
new OctetString(ByteTool.Convert("7B 62 65 AE D3 8F E3 7D 58 45 5C 6C")),
OctetString.Empty),
new Scope(
new OctetString(ByteTool.Convert("80 00 1F 88 80 E9 63 00 00 D6 1F F4 49")),
OctetString.Empty,
new GetRequestPdu(
0x56FF,
new List<Variable>(1) { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.3.0"), new Null()) })),
pair,
null);
Assert.AreEqual(Levels.Authentication | Levels.Reportable, request.Header.SecurityLevel);
Assert.AreEqual(ByteTool.Convert(bytes), request.ToBytes());
}
[Test]
[Category("Default")]
public void TestDiscoveryV3()
{
const string bytes = "30 3A 02 01 03 30 0F 02 02 6A 09 02 03 00 FF E3" +
" 04 01 04 02 01 03 04 10 30 0E 04 00 02 01 00 02" +
" 01 00 04 00 04 00 04 00 30 12 04 00 04 00 A0 0C" +
" 02 02 2C 6B 02 01 00 02 01 00 30 00";
GetRequestMessage request = new GetRequestMessage(
VersionCode.V3,
new Header(
new Integer32(0x6A09),
new Integer32(0xFFE3),
Levels.Reportable),
new SecurityParameters(
OctetString.Empty,
Integer32.Zero,
Integer32.Zero,
OctetString.Empty,
OctetString.Empty,
OctetString.Empty),
new Scope(
OctetString.Empty,
OctetString.Empty,
new GetRequestPdu(0x2C6B, new List<Variable>())),
DefaultPrivacyProvider.DefaultPair,
null
);
string test = ByteTool.Convert(request.ToBytes());
Assert.AreEqual(bytes, test);
}
[Test]
[Category("Default")]
public void TestToBytes()
{
const string s = "30 27 02 01 01 04 06 70 75 62 6C 69 63 A0 1A 02" +
"02 4B ED 02 01 00 02 01 00 30 0E 30 0C 06 08 2B" +
"06 01 02 01 01 01 00 05 00 ";
byte[] expected = ByteTool.Convert(s);
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
Assert.AreEqual(expected, message.ToBytes());
}
[Test]
[Category("Default")]
public async Task TestResponseAsync()
{
var engine = CreateEngine();
engine.Listener.ClearBindings();
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, 16100));
engine.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
var users1 = new UserRegistry();
var response = await message.GetResponseAsync(new IPEndPoint(IPAddress.Loopback, 16100), users1, socket);
engine.Stop();
Assert.AreEqual(SnmpType.ResponsePdu, response.TypeCode());
}
[Test]
[Category("Default")]
public void TestResponse()
{
var engine = CreateEngine();
engine.Listener.ClearBindings();
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, 16101));
engine.Start();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
const int time = 1500;
var response = message.GetResponse(time, new IPEndPoint(IPAddress.Loopback, 16101), socket);
Assert.AreEqual(0x4bed, response.RequestId());
engine.Stop();
}
[Test]
[Category("Default")]
public async void TestResponsesFromMultipleSources()
{
var start = 16102;
var end = start + 512;
var engine = CreateEngine();
engine.Listener.ClearBindings();
for (var index = start; index < end; index++)
{
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, index));
}
// IMPORTANT: need to set min thread count so as to boost performance.
int minWorker, minIOC;
// Get the current settings.
ThreadPool.GetMinThreads(out minWorker, out minIOC);
var threads = engine.Listener.Bindings.Count;
ThreadPool.SetMinThreads(threads + 1, minIOC);
var time = DateTime.Now;
engine.Start();
Console.WriteLine(DateTime.Now - time);
const int timeout = 100000;
for (int index = start; index < end; index++)
//Parallel.For(start, end, async index =>
{
GetRequestMessage message = new GetRequestMessage(index, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Stopwatch watch = new Stopwatch();
watch.Start();
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
//var response = message.GetResponse(timeout, new IPEndPoint(IPAddress.Loopback, index), socket);
var response =
await
message.GetResponseAsync(new IPEndPoint(IPAddress.Loopback, index), new UserRegistry(), socket);
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
watch.Stop();
Console.WriteLine("manager {0}: {1}: port {2}", index, watch.Elapsed, ((IPEndPoint)socket.LocalEndPoint).Port);
Assert.AreEqual(index, response.RequestId());
}
// );
engine.Stop();
}
[Test]
[Category("Default")]
public async void TestResponsesFromSingleSource()
{
var start = 0;
var end = start + 32;
var engine = CreateEngine();
engine.Listener.ClearBindings();
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, 17000));
//// IMPORTANT: need to set min thread count so as to boost performance.
//int minWorker, minIOC;
//// Get the current settings.
//ThreadPool.GetMinThreads(out minWorker, out minIOC);
//var threads = engine.Listener.Bindings.Count;
//ThreadPool.SetMinThreads(threads + 1, minIOC);
var time = DateTime.Now;
engine.Start();
Console.WriteLine(DateTime.Now - time);
const int timeout = 100000;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
for (int index = start; index < end; index++)
//Parallel.For(start, end, async index =>
{
GetRequestMessage message = new GetRequestMessage(0, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
Stopwatch watch = new Stopwatch();
watch.Start();
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
//var response = message.GetResponse(timeout, new IPEndPoint(IPAddress.Loopback, 17000), socket);
var response =
await
message.GetResponseAsync(new IPEndPoint(IPAddress.Loopback, 17000), new UserRegistry(), socket);
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
watch.Stop();
Console.WriteLine("manager {0}: {1}: port {2}", index, watch.Elapsed, ((IPEndPoint)socket.LocalEndPoint).Port);
Assert.AreEqual(0, response.RequestId());
}
// );
engine.Stop();
}
[Test]
[Category("Default")]
public async void TestResponsesFromSingleSourceWithMultipleThreads()
{
var start = 0;
var end = start + 32;
var engine = CreateEngine();
engine.Listener.ClearBindings();
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, 17000));
// IMPORTANT: need to set min thread count so as to boost performance.
int minWorker, minIOC;
// Get the current settings.
ThreadPool.GetMinThreads(out minWorker, out minIOC);
var threads = engine.Listener.Bindings.Count;
ThreadPool.SetMinThreads(threads + 1, minIOC);
var time = DateTime.Now;
engine.Start();
Console.WriteLine(DateTime.Now - time);
const int timeout = 10000;
// Uncomment below to reveal wrong sequence number issue.
// Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//for (int index = start; index < end; index++)
Parallel.For(start, end, async index =>
{
GetRequestMessage message = new GetRequestMessage(index, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
// Comment below to reveal wrong sequence number issue.
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Stopwatch watch = new Stopwatch();
watch.Start();
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
var response = message.GetResponse(timeout, new IPEndPoint(IPAddress.Loopback, 17000), socket);
//var response =
// await
// message.GetResponseAsync(new IPEndPoint(IPAddress.Loopback, 17000), new UserRegistry(), socket);
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
watch.Stop();
Console.WriteLine("manager {0}: {1}: port {2}", index, watch.Elapsed, ((IPEndPoint)socket.LocalEndPoint).Port);
Assert.AreEqual(index, response.RequestId());
}
);
engine.Stop();
}
[Test]
[Category("Default")]
public async void TestResponsesFromSingleSourceWithMultipleThreadsFromManager()
{
var start = 0;
var end = start + 256;
var engine = CreateEngine();
engine.Listener.ClearBindings();
engine.Listener.AddBinding(new IPEndPoint(IPAddress.Loopback, 17000));
var time = DateTime.Now;
engine.Start();
Console.WriteLine(DateTime.Now - time);
const int timeout = 60000;
//for (int index = start; index < end; index++)
Parallel.For(start, end, async index =>
{
Stopwatch watch = new Stopwatch();
watch.Start();
var result = Messenger.Get(VersionCode.V2, new IPEndPoint(IPAddress.Loopback, 17000), new OctetString("public"),
new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) }, timeout);
Console.WriteLine("manager [{0}]{1}", Thread.CurrentThread.ManagedThreadId, DateTime.UtcNow);
watch.Stop();
Assert.AreEqual(1, result.Count);
}
);
engine.Stop();
}
private SnmpEngine CreateEngine()
{
// TODO: this is a hack. review it later.
var store = new ObjectStore();
store.Add(new SysDescr());
store.Add(new SysObjectId());
store.Add(new SysUpTime());
store.Add(new SysContact());
store.Add(new SysName());
store.Add(new SysLocation());
store.Add(new SysServices());
store.Add(new SysORLastChange());
store.Add(new SysORTable());
store.Add(new IfNumber());
store.Add(new IfTable());
var users = new UserRegistry();
users.Add(new OctetString("neither"), DefaultPrivacyProvider.DefaultPair);
users.Add(new OctetString("authen"), new DefaultPrivacyProvider(new MD5AuthenticationProvider(new OctetString("authentication"))));
users.Add(new OctetString("privacy"), new DESPrivacyProvider(new OctetString("privacyphrase"),
new MD5AuthenticationProvider(new OctetString("authentication"))));
var getv1 = new GetV1MessageHandler();
var getv1Mapping = new HandlerMapping("v1", "GET", getv1);
var getv23 = new GetMessageHandler();
var getv23Mapping = new HandlerMapping("v2,v3", "GET", getv23);
var setv1 = new SetV1MessageHandler();
var setv1Mapping = new HandlerMapping("v1", "SET", setv1);
var setv23 = new SetMessageHandler();
var setv23Mapping = new HandlerMapping("v2,v3", "SET", setv23);
var getnextv1 = new GetNextV1MessageHandler();
var getnextv1Mapping = new HandlerMapping("v1", "GETNEXT", getnextv1);
var getnextv23 = new GetNextMessageHandler();
var getnextv23Mapping = new HandlerMapping("v2,v3", "GETNEXT", getnextv23);
var getbulk = new GetBulkMessageHandler();
var getbulkMapping = new HandlerMapping("v2,v3", "GETBULK", getbulk);
var v1 = new Version1MembershipProvider(new OctetString("public"), new OctetString("public"));
var v2 = new Version2MembershipProvider(new OctetString("public"), new OctetString("public"));
var v3 = new Version3MembershipProvider();
var membership = new ComposedMembershipProvider(new IMembershipProvider[] { v1, v2, v3 });
var handlerFactory = new MessageHandlerFactory(new[]
{
getv1Mapping,
getv23Mapping,
setv1Mapping,
setv23Mapping,
getnextv1Mapping,
getnextv23Mapping,
getbulkMapping
});
var pipelineFactory = new SnmpApplicationFactory(store, membership, handlerFactory);
return new SnmpEngine(pipelineFactory, new Listener { Users = users }, new EngineGroup());
}
[Test]
[Category("Default")]
public void TestTimeOut()
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
const int time = 1500;
var timer = new Stopwatch();
timer.Start();
//IMPORTANT: test against an agent that doesn't exist.
Assert.Throws<TimeoutException>(() => message.GetResponse(time, new IPEndPoint(IPAddress.Parse("8.8.8.8"), 161), socket));
timer.Stop();
long elapsedMilliseconds = timer.ElapsedMilliseconds;
Console.WriteLine(@"elapsed: " + elapsedMilliseconds);
Console.WriteLine(@"timeout: " + time);
Assert.LessOrEqual(time, elapsedMilliseconds);
// FIXME: these values are valid on my machine openSUSE 11.2. (lex)
// This test case usually fails on Windows, as strangely WinSock API call adds an extra 500-ms.
if (SnmpMessageExtension.IsRunningOnMono)
{
Assert.LessOrEqual(elapsedMilliseconds, time + 100);
}
}
//[Test]
//[Category("Default")]
public void TestMemory()
{
GC.Collect();
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
//IMPORTANT: test against an agent that doesn't exist.
Assert.Throws<SocketException>(() => message.BeginGetResponse(new IPEndPoint(IPAddress.Loopback, 80), new UserRegistry(), socket, ar =>
{
var response = message.EndGetResponse(ar);
Console.WriteLine(response);
}, null));
GC.Collect();
var memoryCheckPoint1 = dotMemory.Check();
for (int i = 0; i < 100; i++)
{
//Thread.Sleep(100);
Assert.Throws<SocketException>(
() =>
message.BeginGetResponse(
new IPEndPoint(IPAddress.Loopback, 80),
new UserRegistry(),
socket,
ar =>
{
var response = message.EndGetResponse(ar);
Console.WriteLine(response);
},
null));
}
socket.Close();
socket = null;
message = null;
GC.Collect();
dotMemory.Check(memory =>
{
Assert.That(memory.GetDifference(memoryCheckPoint1)
.GetNewObjects().ObjectsCount, Is.LessThanOrEqualTo(15));
});
}
//[Test]
//[Category("Default")]
public void TestMemory2()
{
GC.Collect();
GetRequestMessage message = new GetRequestMessage(0x4bed, VersionCode.V2, new OctetString("public"), new List<Variable> { new Variable(new ObjectIdentifier("1.3.6.1.2.1.1.1.0")) });
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
//IMPORTANT: test against an agent that doesn't exist.
Assert.Throws<SocketException>(
() =>
message.BeginGetResponse(
new IPEndPoint(IPAddress.Loopback, 80),
new UserRegistry(),
socket,
ar =>
{
var response = message.EndGetResponse(ar);
Console.WriteLine(response);
},
null));
socket.Close();
socket = null;
}
GC.Collect();
var memoryCheckPoint1 = dotMemory.Check();
for (int i = 0; i < 100; i++)
{
//Thread.Sleep(100);
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
Assert.Throws<SocketException>(
() =>
message.BeginGetResponse(
new IPEndPoint(IPAddress.Loopback, 80),
new UserRegistry(),
socket,
ar =>
{
var response = message.EndGetResponse(ar);
Console.WriteLine(response);
},
null));
socket.Close();
socket = null;
}
message = null;
GC.Collect();
dotMemory.Check(memory =>
{
Assert.That(memory.GetDifference(memoryCheckPoint1)
.GetNewObjects().ObjectsCount, Is.LessThanOrEqualTo(31));
});
}
}
}
#pragma warning restore 1591
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Windows.Forms;
using OpenSource.UPnP;
namespace UPnPStackBuilder
{
/// <summary>
/// Summary description for SourceCodeRepository.
/// </summary>
public class SourceCodeRepository
{
public SourceCodeRepository()
{
}
private static void ProcessService(UPnPService s, Hashtable RetVal)
{
RetVal[s] = ((ServiceGenerator.ServiceConfiguration)s.User).Name;
}
private static void ProcessDevice(UPnPDevice d, Hashtable RetVal)
{
foreach (UPnPDevice ed in d.EmbeddedDevices) { ProcessDevice(ed, RetVal); }
foreach (UPnPService s in d.Services) { ProcessService(s, RetVal); }
}
public static Hashtable CreateTableOfServiceNames(UPnPDevice rootDevice)
{
Hashtable RetVal = new Hashtable();
foreach (UPnPDevice d in rootDevice.EmbeddedDevices) { ProcessDevice(d, RetVal); }
foreach (UPnPService s in rootDevice.Services) { ProcessService(s, RetVal); }
return (RetVal);
}
public static string ReadString(string s) { return (UTF8Encoding.UTF8.GetString(Base64.Decode(s))); }
public static string ReadFileStore(string filename)
{
DirectoryInfo di = new DirectoryInfo(Application.StartupPath + "\\FileStore");
if (di.Exists == false) di = new DirectoryInfo(Application.StartupPath + "\\..\\..\\FileStore");
if (di.Exists == false) di = new DirectoryInfo(Application.StartupPath + "\\..\\..\\..\\FileStore");
FileStream f = new FileStream(di.FullName + "\\" + filename, FileMode.Open, FileAccess.Read);
byte[] buf = new byte[f.Length];
f.Read(buf, 0, buf.Length);
f.Close();
return (UTF8Encoding.UTF8.GetString(buf, 0, buf.Length));
}
public static byte[] ReadFileStoreBin(string filename)
{
DirectoryInfo di = new DirectoryInfo(Application.StartupPath + "\\FileStore");
if (di.Exists == false) di = new DirectoryInfo(Application.StartupPath + "\\..\\..\\FileStore");
if (di.Exists == false) di = new DirectoryInfo(Application.StartupPath + "\\..\\..\\..\\FileStore");
FileStream f = new FileStream(di.FullName + "\\" + filename, FileMode.Open, FileAccess.Read);
byte[] buf = new byte[f.Length];
f.Read(buf, 0, buf.Length);
f.Close();
return buf;
}
public static byte[] Get_SampleProject_ico() { return ReadFileStoreBin("PPC\\SampleProject.ico"); }
public static string Get_SampleProject_vcp() { return ReadFileStore("PPC\\SampleProject.vcp"); }
public static string Get_SampleProject_vcw() { return ReadFileStore("PPC\\SampleProject.vcw"); }
public static string Get_StdAfx_cpp() { return ReadFileStore("PPC\\StdAfx.cpp"); }
public static string Get_StdAfx_h() { return ReadFileStore("PPC\\StdAfx.h"); }
public static string Get_SampleProject_rc() { return ReadFileStore("PPC\\SampleProject.rc"); }
public static string Get_SampleProjectDlg_h() { return ReadFileStore("PPC\\SampleProjectDlg.h"); }
public static string Get_SampleProjectDlg_cpp() { return ReadFileStore("PPC\\SampleProjectDlg.cpp"); }
public static string Get_SampleProject_h() { return ReadFileStore("PPC\\SampleProject.h"); }
public static string Get_SampleProject_cpp() { return ReadFileStore("PPC\\SampleProject.cpp"); }
public static string Get_resource_h() { return ReadFileStore("PPC\\resource.h"); }
public static string Get_newres_h() { return ReadFileStore("PPC\\newres.h"); }
public static string Get_Makefile() { return ReadFileStore("posix\\makefile"); }
public static string Get_UPnPSample_sln() { return ReadFileStore("Win32\\UPnPSample.sln"); }
public static string Get_UPnPSample_vcproj() { return ReadFileStore("Win32\\UPnPSample.vcproj"); }
public static string Get_Win32_stdafx_h() { return ReadFileStore("Win32\\stdafx.h"); }
public static string Get_Win32_stdafx_cpp() { return ReadFileStore("Win32\\stdafx.cpp"); }
public static byte[] Get_CP_SampleProject_ico() { return ReadFileStoreBin("Sample.ico"); }
public static string Get_CP_SampleProject_vcp() { return ReadFileStore("PPC_CP\\SampleProject.vcp"); }
public static string Get_CP_SampleProject_vcw() { return ReadFileStore("PPC_CP\\SampleProject.vcw"); }
public static string Get_CP_StdAfx_cpp() { return ReadFileStore("PPC_CP\\StdAfx.cpp"); }
public static string Get_CP_StdAfx_h() { return ReadFileStore("PPC_CP\\StdAfx.h"); }
public static string Get_CP_SampleProject_rc() { return ReadFileStore("PPC_CP\\SampleProject.rc"); }
public static string Get_CP_SampleProjectDlg_h() { return ReadFileStore("PPC_CP\\SampleProjectDlg.h"); }
public static string Get_CP_SampleProjectDlg_cpp() { return ReadFileStore("PPC_CP\\SampleProjectDlg.cpp"); }
public static string Get_CP_SampleProject_h() { return ReadFileStore("PPC_CP\\SampleProject.h"); }
public static string Get_CP_SampleProject_cpp() { return ReadFileStore("PPC_CP\\SampleProject.cpp"); }
public static string Get_CP_resource_h() { return ReadFileStore("PPC_CP\\resource.h"); }
public static string Get_CP_newres_h() { return ReadFileStore("PPC_CP\\newres.h"); }
public static string Get_Generic(string VariableName)
{
string varData;
System.Reflection.FieldInfo fi = typeof(SourceCodeRepository).GetField(
VariableName,
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public);
if (fi != null)
{
varData = (string)fi.GetValue(null);
return (ReadString(varData));
}
return "";
}
public static void Generate_ThreadPool(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "ThreadPool.h", "") + RemoveOldEULA(ReadFileStore("ILibThreadPool.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "ThreadPool.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "ThreadPool.c", "") + RemoveOldEULA(ReadFileStore("ILibThreadPool.c"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "ThreadPool.c");
writer.Write(lib);
writer.Close();
}
public static string GetMain_C_Template() { return (GetEULA("Main.c", "") + RemoveOldEULA(ReadFileStore("Main.c"))); }
public static string GetControlPoint_C_Template(string PreFix) { return (GetEULA(PreFix + "ControlPoint.c", "") + RemoveOldEULA(ReadFileStore("UPnPControlPoint.c"))); }
public static string GetControlPoint_H_Template(string PreFix) { return (GetEULA(PreFix + "ControlPoint.h", "") + RemoveOldEULA(ReadFileStore("UPnPControlPoint.h"))); }
public static string GetMicroStack_C_Template(string PreFix) { return (GetEULA(PreFix + "MicroStack.c", "") + RemoveOldEULA(ReadFileStore("UPnPMicroStack.c"))); }
public static string GetMicroStack_H_Template(string PreFix) { return (GetEULA(PreFix + "MicroStack.h", "") + RemoveOldEULA(ReadFileStore("UPnPMicroStack.h"))); }
public static string GetCPlusPlus_Template_H(string PreFix) { return (GetEULA(PreFix + "Abstraction.h", "") + RemoveOldEULA(ReadFileStore("CPlusPlus\\UPnPAbstraction.h"))); }
public static string GetCPlusPlus_Template_CPP(string PreFix) { return (GetEULA(PreFix + "Abstraction.cpp", "") + RemoveOldEULA(ReadFileStore("CPlusPlus\\UPnPAbstraction.cpp"))); }
private static string GetEULA(string FileName, string Settings)
{
string RetVal = ReadFileStore("EULA.txt");
if (Settings == "") { Settings = "*"; }
RetVal = RetVal.Replace("<REVISION>", "#" + Application.ProductVersion);
RetVal = RetVal.Replace("<DATE>", DateTime.Now.ToLongDateString());
RetVal = RetVal.Replace("<FILE>", FileName);
RetVal = RetVal.Replace("<SETTINGS>", Settings);
return (RetVal);
}
private static string RemoveOldEULA(string InVal)
{
string RetVal = InVal;
RetVal = RetVal.Substring(2 + RetVal.IndexOf("*/"));
return (RetVal);
}
public static void Generate_Parsers(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "Parsers.h", "") + RemoveOldEULA(ReadFileStore("ILibParsers.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "Parsers.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "Parsers.c", "") + RemoveOldEULA(ReadFileStore("ILibParsers.c"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "Parsers.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_AsyncUDPSocket(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "AsyncSocket.h", "") + RemoveOldEULA(ReadFileStore("ILibAsyncUDPSocket.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncUDPSocket.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "AsyncSocket.c", "") + RemoveOldEULA(ReadFileStore("ILibAsyncUDPSocket.c"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncUDPSocket.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_AsyncSocket(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "AsyncSocket.h", "") + RemoveOldEULA(ReadFileStore("ILibAsyncSocket.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncSocket.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "AsyncSocket.c", "") + RemoveOldEULA(ReadFileStore("ILibAsyncSocket.c"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncSocket.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_AsyncServerSocket(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "AsyncServerSocket.h", "") + RemoveOldEULA(ReadFileStore("ILibAsyncServerSocket.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncServerSocket.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "AsyncServerSocket.c", "") + RemoveOldEULA(ReadFileStore("ILibAsyncServerSocket.c"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "AsyncServerSocket.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_WebClient(ServiceGenerator.StackConfiguration config, DirectoryInfo outputDir)
{
bool Legacy = !config.HTTP_1dot1;
string PreFix = config.prefixlib;
int i;
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "WebClient.h", "") + RemoveOldEULA(ReadFileStore("ILibWebClient.h"));
lib = lib.Replace("ILib", PreFix);
//
// Buffer Limitations
//
lib = ReplaceLine(lib, "#define INITIAL_BUFFER_SIZE", "#define INITIAL_BUFFER_SIZE " + config.InitialHTTPBufferSize.ToString() + "\n");
i = lib.IndexOf("#define MAX_HTTP_HEADER_SIZE");
if (i != -1)
{
if (config.MaxHTTPHeaderSize > 0)
{
lib = ReplaceLine(lib, "#define MAX_HTTP_HEADER_SIZE", "#define MAX_HTTP_HEADER_SIZE " + config.MaxHTTPHeaderSize.ToString() + "\n");
}
else
{
lib = DeleteLine(lib, "#define MAX_HTTP_HEADER_SIZE");
}
}
else
{
if (config.MaxHTTPHeaderSize > 0)
{
i = GetIndexOfNextLine(lib, "#define INITIAL_BUFFER_SIZE");
if (i != -1)
{
lib = lib.Insert(i, "#define MAX_HTTP_HEADER_SIZE " + config.MaxHTTPHeaderSize.ToString() + "\n");
}
}
}
i = lib.IndexOf("#define MAX_HTTP_PACKET_SIZE");
if (i != -1)
{
if (config.MaxHTTPPacketSize > 0)
{
lib = ReplaceLine(lib, "#define MAX_HTTP_PACKET_SIZE", "#define MAX_HTTP_PACKET_SIZE " + config.MaxHTTPPacketSize.ToString() + "\n");
}
else
{
lib = DeleteLine(lib, "#define MAX_HTTP_PACKET_SIZE");
}
}
else
{
if (config.MaxHTTPPacketSize > 0)
{
i = GetIndexOfNextLine(lib, "#define INITIAL_BUFFER_SIZE");
if (i != -1)
{
lib = lib.Insert(i, "#define MAX_HTTP_PACKET_SIZE " + config.MaxHTTPPacketSize.ToString() + "\n");
}
}
}
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "WebClient.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "WebClient.c", "") + RemoveOldEULA(ReadFileStore("ILibWebClient.c"));
lib = lib.Replace("ILib", PreFix);
if (Legacy)
{
// Remove HTTP/1.1 Specific Code
string xx = "//{{{ REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT--> }}}";
string yy = "//{{{ <--REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT }}}";
int ix = lib.IndexOf(xx);
int iy;
while (ix != -1)
{
iy = lib.IndexOf(yy) + yy.Length;
lib = lib.Remove(ix, iy - ix);
ix = lib.IndexOf(xx);
}
}
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "WebClient.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_WebServer(ServiceGenerator.StackConfiguration config, DirectoryInfo outputDir)
{
bool Legacy = !config.HTTP_1dot1;
string PreFix = config.prefixlib;
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "WebServer.h", "") + RemoveOldEULA(ReadFileStore("ILibWebServer.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "WebServer.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "WebServer.c", "") + "\r\n";
if (Legacy)
{
lib += "#define HTTPVERSION \"1.0\"";
}
else
{
lib += "#define HTTPVERSION \"1.1\"";
}
lib += RemoveOldEULA(ReadFileStore("ILibWebServer.c"));
lib = lib.Replace("ILib", PreFix);
if (Legacy)
{
// Remove HTTP/1.1 Specific Code
string xx = "//{{{ REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT--> }}}";
string yy = "//{{{ <--REMOVE_THIS_FOR_HTTP/1.0_ONLY_SUPPORT }}}";
int ix = lib.IndexOf(xx);
int iy;
while (ix != -1)
{
iy = lib.IndexOf(yy) + yy.Length;
lib = lib.Remove(ix, iy - ix);
ix = lib.IndexOf(xx);
}
}
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "WebServer.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_Generic(string PreFix, DirectoryInfo outputDir, string FileName, string VariableName)
{
StreamWriter writer;
string lib;
string varData;
System.Reflection.FieldInfo fi = typeof(SourceCodeRepository).GetField(
VariableName,
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public);
if (fi != null)
{
varData = (string)fi.GetValue(null);
lib = GetEULA(PreFix + FileName, "") + "\r\n" + RemoveOldEULA(ReadString(varData));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + FileName);
writer.Write(lib);
writer.Close();
}
}
public static string RemoveAndClearTag(string BeginTag, string EndTag, string data)
{
// Remove HTTP/1.1 Specific Code
int ix = data.IndexOf(BeginTag);
int iy;
while (ix != -1)
{
iy = data.IndexOf(EndTag) + EndTag.Length;
if (data.Substring(iy, 2).Equals("\r\n") == true) iy += 2;
data = data.Remove(ix, iy - ix);
ix = data.IndexOf(BeginTag);
}
return data;
}
public static string RemoveTag(string BeginTag, string EndTag, string data)
{
data = data.Replace(BeginTag + "\r\n", "");
data = data.Replace(BeginTag, "");
data = data.Replace(EndTag + "\r\n", "");
data = data.Replace(EndTag, "");
return data;
}
public static void Generate_SSDPClient(string PreFix, DirectoryInfo outputDir, bool UPNP_1_1)
{
StreamWriter writer;
string lib;
lib = GetEULA(PreFix + "SSDPClient.h", "") + RemoveOldEULA(ReadFileStore("ILibSSDPClient.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "SSDPClient.h");
writer.Write(lib);
writer.Close();
lib = GetEULA(PreFix + "SSDPClient.c", "") + RemoveOldEULA(ReadFileStore("ILibSSDPClient.c"));
lib = lib.Replace("ILib", PreFix);
if (!UPNP_1_1)
{
// Legacy
lib = SourceCodeRepository.RemoveTag("//{{{BEGIN_UPNP_1_0}}}", "//{{{END_UPNP_1_0}}}", lib);
lib = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_UPNP_1_1}}}", "//{{{END_UPNP_1_1}}}", lib);
}
else
{
// UPnP/1.1+
lib = SourceCodeRepository.RemoveTag("//{{{BEGIN_UPNP_1_1}}}", "//{{{END_UPNP_1_1}}}", lib);
lib = SourceCodeRepository.RemoveAndClearTag("//{{{BEGIN_UPNP_1_0}}}", "//{{{END_UPNP_1_0}}}", lib);
}
writer = File.CreateText(outputDir.FullName + "\\" + PreFix + "SSDPClient.c");
writer.Write(lib);
writer.Close();
}
public static void Generate_UPnPControlPointStructs(string PreFix, DirectoryInfo outputDir)
{
StreamWriter writer;
string lib;
lib = GetEULA("UPnPControlPointStructs.h", "") + RemoveOldEULA(ReadFileStore("UPnPControlPointStructs.h"));
lib = lib.Replace("ILib", PreFix);
writer = File.CreateText(outputDir.FullName + "\\UPnPControlPointStructs.h");
writer.Write(lib);
writer.Close();
}
public static string GetTextBetweenTags(string WS, string BeginTag, string EndTag)
{
// Remove HTTP/1.1 Specific Code
int ix = WS.IndexOf(BeginTag);
int iy = WS.IndexOf(EndTag);
ix += BeginTag.Length;
string RetVal = WS.Substring(ix, iy - ix);
return (RetVal);
}
public static string InsertTextBeforeTag(string WS, string Tag, string TextToInsert)
{
int ix = WS.IndexOf(Tag);
return (WS.Insert(ix, TextToInsert));
}
public static int GetIndexOfNextLine(string WS, int StartPos)
{
for (int i = StartPos; i < WS.Length; ++i) if (WS[i] == '\n') return (i + 1);
return -1;
}
public static int GetIndexOfNextLine(string WS, string SearchString)
{
int i = WS.IndexOf(SearchString);
if (i != -1) return (GetIndexOfNextLine(WS, i)); else return -1;
}
public static string ReplaceLine(string WS, string SearchString, string NewString)
{
int i = WS.IndexOf(SearchString);
string RetVal = WS;
if (i != -1)
{
int nline = GetIndexOfNextLine(WS, i);
if (nline != -1)
{
RetVal = WS.Remove(i, nline - i);
RetVal = RetVal.Insert(i, NewString);
}
}
return (RetVal);
}
public static string DeleteLine(string WS, string SearchString)
{
int i = WS.IndexOf(SearchString);
string RetVal = WS;
if (i != -1)
{
int nline = GetIndexOfNextLine(WS, i);
if (nline != -1) RetVal = WS.Remove(i, nline - i);
}
return (RetVal);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gagr = Google.Api.Gax.ResourceNames;
using gcnv = Google.Cloud.NetworkSecurity.V1Beta1;
using sys = System;
namespace Google.Cloud.NetworkSecurity.V1Beta1
{
/// <summary>Resource name for the <c>ClientTlsPolicy</c> resource.</summary>
public sealed partial class ClientTlsPolicyName : gax::IResourceName, sys::IEquatable<ClientTlsPolicyName>
{
/// <summary>The possible contents of <see cref="ClientTlsPolicyName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>.
/// </summary>
ProjectLocationClientTlsPolicy = 1,
}
private static gax::PathTemplate s_projectLocationClientTlsPolicy = new gax::PathTemplate("projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}");
/// <summary>Creates a <see cref="ClientTlsPolicyName"/> 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="ClientTlsPolicyName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static ClientTlsPolicyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new ClientTlsPolicyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="ClientTlsPolicyName"/> with the pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="ClientTlsPolicyName"/> constructed from the provided ids.</returns>
public static ClientTlsPolicyName FromProjectLocationClientTlsPolicy(string projectId, string locationId, string clientTlsPolicyId) =>
new ClientTlsPolicyName(ResourceNameType.ProjectLocationClientTlsPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clientTlsPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ClientTlsPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ClientTlsPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string clientTlsPolicyId) =>
FormatProjectLocationClientTlsPolicy(projectId, locationId, clientTlsPolicyId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="ClientTlsPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="ClientTlsPolicyName"/> with pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>.
/// </returns>
public static string FormatProjectLocationClientTlsPolicy(string projectId, string locationId, string clientTlsPolicyId) =>
s_projectLocationClientTlsPolicy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="clientTlsPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="ClientTlsPolicyName"/> if successful.</returns>
public static ClientTlsPolicyName Parse(string clientTlsPolicyName) => Parse(clientTlsPolicyName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="clientTlsPolicyName">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="ClientTlsPolicyName"/> if successful.</returns>
public static ClientTlsPolicyName Parse(string clientTlsPolicyName, bool allowUnparsed) =>
TryParse(clientTlsPolicyName, allowUnparsed, out ClientTlsPolicyName 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="ClientTlsPolicyName"/> 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}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>
/// </description>
/// </item>
/// </list>
/// </remarks>
/// <param name="clientTlsPolicyName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="ClientTlsPolicyName"/>, 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 clientTlsPolicyName, out ClientTlsPolicyName result) =>
TryParse(clientTlsPolicyName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="ClientTlsPolicyName"/> 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}/locations/{location}/clientTlsPolicies/{client_tls_policy}</c>
/// </description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="clientTlsPolicyName">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="ClientTlsPolicyName"/>, 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 clientTlsPolicyName, bool allowUnparsed, out ClientTlsPolicyName result)
{
gax::GaxPreconditions.CheckNotNull(clientTlsPolicyName, nameof(clientTlsPolicyName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationClientTlsPolicy.TryParseName(clientTlsPolicyName, out resourceName))
{
result = FromProjectLocationClientTlsPolicy(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(clientTlsPolicyName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private ClientTlsPolicyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string clientTlsPolicyId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
ClientTlsPolicyId = clientTlsPolicyId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="ClientTlsPolicyName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/clientTlsPolicies/{client_tls_policy}</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="clientTlsPolicyId">The <c>ClientTlsPolicy</c> ID. Must not be <c>null</c> or empty.</param>
public ClientTlsPolicyName(string projectId, string locationId, string clientTlsPolicyId) : this(ResourceNameType.ProjectLocationClientTlsPolicy, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), clientTlsPolicyId: gax::GaxPreconditions.CheckNotNullOrEmpty(clientTlsPolicyId, nameof(clientTlsPolicyId)))
{
}
/// <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>ClientTlsPolicy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string ClientTlsPolicyId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationClientTlsPolicy: return s_projectLocationClientTlsPolicy.Expand(ProjectId, LocationId, ClientTlsPolicyId);
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 ClientTlsPolicyName);
/// <inheritdoc/>
public bool Equals(ClientTlsPolicyName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(ClientTlsPolicyName a, ClientTlsPolicyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(ClientTlsPolicyName a, ClientTlsPolicyName b) => !(a == b);
}
public partial class ClientTlsPolicy
{
/// <summary>
/// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcnv::ClientTlsPolicyName ClientTlsPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class ListClientTlsPoliciesRequest
{
/// <summary>
/// <see cref="gagr::LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public gagr::LocationName ParentAsLocationName
{
get => string.IsNullOrEmpty(Parent) ? null : gagr::LocationName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class GetClientTlsPolicyRequest
{
/// <summary>
/// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcnv::ClientTlsPolicyName ClientTlsPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class CreateClientTlsPolicyRequest
{
/// <summary>
/// <see cref="ClientTlsPolicyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public ClientTlsPolicyName ParentAsClientTlsPolicyName
{
get => string.IsNullOrEmpty(Parent) ? null : ClientTlsPolicyName.Parse(Parent, allowUnparsed: true);
set => Parent = value?.ToString() ?? "";
}
}
public partial class DeleteClientTlsPolicyRequest
{
/// <summary>
/// <see cref="gcnv::ClientTlsPolicyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcnv::ClientTlsPolicyName ClientTlsPolicyName
{
get => string.IsNullOrEmpty(Name) ? null : gcnv::ClientTlsPolicyName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Accident Involvements/Sickbay Visits Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class SAIDataSet : EduHubDataSet<SAI>
{
/// <inheritdoc />
public override string Name { get { return "SAI"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal SAIDataSet(EduHubContext Context)
: base(Context)
{
Index_ACCIDENTID = new Lazy<NullDictionary<int?, IReadOnlyList<SAI>>>(() => this.ToGroupedNullDictionary(i => i.ACCIDENTID));
Index_SAIKEY = new Lazy<Dictionary<int, SAI>>(() => this.ToDictionary(i => i.SAIKEY));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="SAI" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="SAI" /> fields for each CSV column header</returns>
internal override Action<SAI, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<SAI, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SAIKEY":
mapper[i] = (e, v) => e.SAIKEY = int.Parse(v);
break;
case "ENTRY_TYPE":
mapper[i] = (e, v) => e.ENTRY_TYPE = v;
break;
case "ACCIDENTID":
mapper[i] = (e, v) => e.ACCIDENTID = v == null ? (int?)null : int.Parse(v);
break;
case "INV_PERSON_TYPE":
mapper[i] = (e, v) => e.INV_PERSON_TYPE = v;
break;
case "INV_PERSONKEY":
mapper[i] = (e, v) => e.INV_PERSONKEY = v;
break;
case "INV_PERSON_DFAB":
mapper[i] = (e, v) => e.INV_PERSON_DFAB = v;
break;
case "INV_FULL_NAME":
mapper[i] = (e, v) => e.INV_FULL_NAME = v;
break;
case "INV_ADDRESS":
mapper[i] = (e, v) => e.INV_ADDRESS = v;
break;
case "INV_TELEPHONE":
mapper[i] = (e, v) => e.INV_TELEPHONE = v;
break;
case "INV_BIRTHDATE":
mapper[i] = (e, v) => e.INV_BIRTHDATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "INV_GENDER":
mapper[i] = (e, v) => e.INV_GENDER = v;
break;
case "INV_PAYROLL_REC_NO":
mapper[i] = (e, v) => e.INV_PAYROLL_REC_NO = v;
break;
case "INV_STAFF_TYPE":
mapper[i] = (e, v) => e.INV_STAFF_TYPE = v;
break;
case "HELP_PERSON_TYPE":
mapper[i] = (e, v) => e.HELP_PERSON_TYPE = v;
break;
case "HELP_PERSONKEY":
mapper[i] = (e, v) => e.HELP_PERSONKEY = v;
break;
case "HELP_PERSON_DFAB":
mapper[i] = (e, v) => e.HELP_PERSON_DFAB = v;
break;
case "HELP_FULL_NAME":
mapper[i] = (e, v) => e.HELP_FULL_NAME = v;
break;
case "INCIDENT_NO":
mapper[i] = (e, v) => e.INCIDENT_NO = v;
break;
case "SENT_TO_DEPT":
mapper[i] = (e, v) => e.SENT_TO_DEPT = v;
break;
case "CLAIM_LODGED":
mapper[i] = (e, v) => e.CLAIM_LODGED = v;
break;
case "CLAIM_DATE":
mapper[i] = (e, v) => e.CLAIM_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "WORK_CEASED_DATE":
mapper[i] = (e, v) => e.WORK_CEASED_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "SUCCESSFUL_CONTACT":
mapper[i] = (e, v) => e.SUCCESSFUL_CONTACT = v;
break;
case "OTHER_SUCCESSFUL_CONTACT":
mapper[i] = (e, v) => e.OTHER_SUCCESSFUL_CONTACT = v;
break;
case "DOCTOR":
mapper[i] = (e, v) => e.DOCTOR = v;
break;
case "OTHER_DOCTOR":
mapper[i] = (e, v) => e.OTHER_DOCTOR = v;
break;
case "HOSPITAL":
mapper[i] = (e, v) => e.HOSPITAL = v;
break;
case "AMBULANCE":
mapper[i] = (e, v) => e.AMBULANCE = v;
break;
case "ATTENDANCE_DATE":
mapper[i] = (e, v) => e.ATTENDANCE_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "ATTENDANCE_IN_TIME":
mapper[i] = (e, v) => e.ATTENDANCE_IN_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "ATTENDANCE_OUT_TIME":
mapper[i] = (e, v) => e.ATTENDANCE_OUT_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "SYMPTOMS":
mapper[i] = (e, v) => e.SYMPTOMS = v;
break;
case "SICKBAY_ACTION":
mapper[i] = (e, v) => e.SICKBAY_ACTION = v;
break;
case "ACTION_OUTCOME":
mapper[i] = (e, v) => e.ACTION_OUTCOME = v;
break;
case "SMS_KEY":
mapper[i] = (e, v) => e.SMS_KEY = v == null ? (int?)null : int.Parse(v);
break;
case "EMAIL_KEY":
mapper[i] = (e, v) => e.EMAIL_KEY = v == null ? (int?)null : int.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="SAI" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="SAI" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="SAI" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{SAI}"/> of entities</returns>
internal override IEnumerable<SAI> ApplyDeltaEntities(IEnumerable<SAI> Entities, List<SAI> DeltaEntities)
{
HashSet<int> Index_SAIKEY = new HashSet<int>(DeltaEntities.Select(i => i.SAIKEY));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SAIKEY;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SAIKEY.Remove(entity.SAIKEY);
if (entity.SAIKEY.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<NullDictionary<int?, IReadOnlyList<SAI>>> Index_ACCIDENTID;
private Lazy<Dictionary<int, SAI>> Index_SAIKEY;
#endregion
#region Index Methods
/// <summary>
/// Find SAI by ACCIDENTID field
/// </summary>
/// <param name="ACCIDENTID">ACCIDENTID value used to find SAI</param>
/// <returns>List of related SAI entities</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAI> FindByACCIDENTID(int? ACCIDENTID)
{
return Index_ACCIDENTID.Value[ACCIDENTID];
}
/// <summary>
/// Attempt to find SAI by ACCIDENTID field
/// </summary>
/// <param name="ACCIDENTID">ACCIDENTID value used to find SAI</param>
/// <param name="Value">List of related SAI entities</param>
/// <returns>True if the list of related SAI entities is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindByACCIDENTID(int? ACCIDENTID, out IReadOnlyList<SAI> Value)
{
return Index_ACCIDENTID.Value.TryGetValue(ACCIDENTID, out Value);
}
/// <summary>
/// Attempt to find SAI by ACCIDENTID field
/// </summary>
/// <param name="ACCIDENTID">ACCIDENTID value used to find SAI</param>
/// <returns>List of related SAI entities, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public IReadOnlyList<SAI> TryFindByACCIDENTID(int? ACCIDENTID)
{
IReadOnlyList<SAI> value;
if (Index_ACCIDENTID.Value.TryGetValue(ACCIDENTID, out value))
{
return value;
}
else
{
return null;
}
}
/// <summary>
/// Find SAI by SAIKEY field
/// </summary>
/// <param name="SAIKEY">SAIKEY value used to find SAI</param>
/// <returns>Related SAI entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SAI FindBySAIKEY(int SAIKEY)
{
return Index_SAIKEY.Value[SAIKEY];
}
/// <summary>
/// Attempt to find SAI by SAIKEY field
/// </summary>
/// <param name="SAIKEY">SAIKEY value used to find SAI</param>
/// <param name="Value">Related SAI entity</param>
/// <returns>True if the related SAI entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySAIKEY(int SAIKEY, out SAI Value)
{
return Index_SAIKEY.Value.TryGetValue(SAIKEY, out Value);
}
/// <summary>
/// Attempt to find SAI by SAIKEY field
/// </summary>
/// <param name="SAIKEY">SAIKEY value used to find SAI</param>
/// <returns>Related SAI entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public SAI TryFindBySAIKEY(int SAIKEY)
{
SAI value;
if (Index_SAIKEY.Value.TryGetValue(SAIKEY, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a SAI table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SAI]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[SAI](
[SAIKEY] int IDENTITY NOT NULL,
[ENTRY_TYPE] varchar(1) NULL,
[ACCIDENTID] int NULL,
[INV_PERSON_TYPE] varchar(2) NULL,
[INV_PERSONKEY] varchar(10) NULL,
[INV_PERSON_DFAB] varchar(1) NULL,
[INV_FULL_NAME] varchar(64) NULL,
[INV_ADDRESS] varchar(120) NULL,
[INV_TELEPHONE] varchar(20) NULL,
[INV_BIRTHDATE] datetime NULL,
[INV_GENDER] varchar(1) NULL,
[INV_PAYROLL_REC_NO] varchar(9) NULL,
[INV_STAFF_TYPE] varchar(2) NULL,
[HELP_PERSON_TYPE] varchar(2) NULL,
[HELP_PERSONKEY] varchar(10) NULL,
[HELP_PERSON_DFAB] varchar(1) NULL,
[HELP_FULL_NAME] varchar(32) NULL,
[INCIDENT_NO] varchar(6) NULL,
[SENT_TO_DEPT] varchar(1) NULL,
[CLAIM_LODGED] varchar(1) NULL,
[CLAIM_DATE] datetime NULL,
[WORK_CEASED_DATE] datetime NULL,
[SUCCESSFUL_CONTACT] varchar(40) NULL,
[OTHER_SUCCESSFUL_CONTACT] varchar(40) NULL,
[DOCTOR] varchar(40) NULL,
[OTHER_DOCTOR] varchar(40) NULL,
[HOSPITAL] varchar(40) NULL,
[AMBULANCE] varchar(1) NULL,
[ATTENDANCE_DATE] datetime NULL,
[ATTENDANCE_IN_TIME] smallint NULL,
[ATTENDANCE_OUT_TIME] smallint NULL,
[SYMPTOMS] varchar(MAX) NULL,
[SICKBAY_ACTION] varchar(MAX) NULL,
[ACTION_OUTCOME] varchar(MAX) NULL,
[SMS_KEY] int NULL,
[EMAIL_KEY] int NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [SAI_Index_SAIKEY] PRIMARY KEY CLUSTERED (
[SAIKEY] ASC
)
);
CREATE NONCLUSTERED INDEX [SAI_Index_ACCIDENTID] ON [dbo].[SAI]
(
[ACCIDENTID] ASC
);
END");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes.
/// Typically called before <see cref="SqlBulkCopy"/> to improve performance.
/// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAI]') AND name = N'SAI_Index_ACCIDENTID')
ALTER INDEX [SAI_Index_ACCIDENTID] ON [dbo].[SAI] DISABLE;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[SAI]') AND name = N'SAI_Index_ACCIDENTID')
ALTER INDEX [SAI_Index_ACCIDENTID] ON [dbo].[SAI] REBUILD PARTITION = ALL;
");
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="SAI"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="SAI"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<SAI> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<int> Index_SAIKEY = new List<int>();
foreach (var entity in Entities)
{
Index_SAIKEY.Add(entity.SAIKEY);
}
builder.AppendLine("DELETE [dbo].[SAI] WHERE");
// Index_SAIKEY
builder.Append("[SAIKEY] IN (");
for (int index = 0; index < Index_SAIKEY.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SAIKEY
var parameterSAIKEY = $"@p{parameterIndex++}";
builder.Append(parameterSAIKEY);
command.Parameters.Add(parameterSAIKEY, SqlDbType.Int).Value = Index_SAIKEY[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SAI data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SAI data set</returns>
public override EduHubDataSetDataReader<SAI> GetDataSetDataReader()
{
return new SAIDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the SAI data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the SAI data set</returns>
public override EduHubDataSetDataReader<SAI> GetDataSetDataReader(List<SAI> Entities)
{
return new SAIDataReader(new EduHubDataSetLoadedReader<SAI>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class SAIDataReader : EduHubDataSetDataReader<SAI>
{
public SAIDataReader(IEduHubDataSetReader<SAI> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 39; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SAIKEY
return Current.SAIKEY;
case 1: // ENTRY_TYPE
return Current.ENTRY_TYPE;
case 2: // ACCIDENTID
return Current.ACCIDENTID;
case 3: // INV_PERSON_TYPE
return Current.INV_PERSON_TYPE;
case 4: // INV_PERSONKEY
return Current.INV_PERSONKEY;
case 5: // INV_PERSON_DFAB
return Current.INV_PERSON_DFAB;
case 6: // INV_FULL_NAME
return Current.INV_FULL_NAME;
case 7: // INV_ADDRESS
return Current.INV_ADDRESS;
case 8: // INV_TELEPHONE
return Current.INV_TELEPHONE;
case 9: // INV_BIRTHDATE
return Current.INV_BIRTHDATE;
case 10: // INV_GENDER
return Current.INV_GENDER;
case 11: // INV_PAYROLL_REC_NO
return Current.INV_PAYROLL_REC_NO;
case 12: // INV_STAFF_TYPE
return Current.INV_STAFF_TYPE;
case 13: // HELP_PERSON_TYPE
return Current.HELP_PERSON_TYPE;
case 14: // HELP_PERSONKEY
return Current.HELP_PERSONKEY;
case 15: // HELP_PERSON_DFAB
return Current.HELP_PERSON_DFAB;
case 16: // HELP_FULL_NAME
return Current.HELP_FULL_NAME;
case 17: // INCIDENT_NO
return Current.INCIDENT_NO;
case 18: // SENT_TO_DEPT
return Current.SENT_TO_DEPT;
case 19: // CLAIM_LODGED
return Current.CLAIM_LODGED;
case 20: // CLAIM_DATE
return Current.CLAIM_DATE;
case 21: // WORK_CEASED_DATE
return Current.WORK_CEASED_DATE;
case 22: // SUCCESSFUL_CONTACT
return Current.SUCCESSFUL_CONTACT;
case 23: // OTHER_SUCCESSFUL_CONTACT
return Current.OTHER_SUCCESSFUL_CONTACT;
case 24: // DOCTOR
return Current.DOCTOR;
case 25: // OTHER_DOCTOR
return Current.OTHER_DOCTOR;
case 26: // HOSPITAL
return Current.HOSPITAL;
case 27: // AMBULANCE
return Current.AMBULANCE;
case 28: // ATTENDANCE_DATE
return Current.ATTENDANCE_DATE;
case 29: // ATTENDANCE_IN_TIME
return Current.ATTENDANCE_IN_TIME;
case 30: // ATTENDANCE_OUT_TIME
return Current.ATTENDANCE_OUT_TIME;
case 31: // SYMPTOMS
return Current.SYMPTOMS;
case 32: // SICKBAY_ACTION
return Current.SICKBAY_ACTION;
case 33: // ACTION_OUTCOME
return Current.ACTION_OUTCOME;
case 34: // SMS_KEY
return Current.SMS_KEY;
case 35: // EMAIL_KEY
return Current.EMAIL_KEY;
case 36: // LW_DATE
return Current.LW_DATE;
case 37: // LW_TIME
return Current.LW_TIME;
case 38: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // ENTRY_TYPE
return Current.ENTRY_TYPE == null;
case 2: // ACCIDENTID
return Current.ACCIDENTID == null;
case 3: // INV_PERSON_TYPE
return Current.INV_PERSON_TYPE == null;
case 4: // INV_PERSONKEY
return Current.INV_PERSONKEY == null;
case 5: // INV_PERSON_DFAB
return Current.INV_PERSON_DFAB == null;
case 6: // INV_FULL_NAME
return Current.INV_FULL_NAME == null;
case 7: // INV_ADDRESS
return Current.INV_ADDRESS == null;
case 8: // INV_TELEPHONE
return Current.INV_TELEPHONE == null;
case 9: // INV_BIRTHDATE
return Current.INV_BIRTHDATE == null;
case 10: // INV_GENDER
return Current.INV_GENDER == null;
case 11: // INV_PAYROLL_REC_NO
return Current.INV_PAYROLL_REC_NO == null;
case 12: // INV_STAFF_TYPE
return Current.INV_STAFF_TYPE == null;
case 13: // HELP_PERSON_TYPE
return Current.HELP_PERSON_TYPE == null;
case 14: // HELP_PERSONKEY
return Current.HELP_PERSONKEY == null;
case 15: // HELP_PERSON_DFAB
return Current.HELP_PERSON_DFAB == null;
case 16: // HELP_FULL_NAME
return Current.HELP_FULL_NAME == null;
case 17: // INCIDENT_NO
return Current.INCIDENT_NO == null;
case 18: // SENT_TO_DEPT
return Current.SENT_TO_DEPT == null;
case 19: // CLAIM_LODGED
return Current.CLAIM_LODGED == null;
case 20: // CLAIM_DATE
return Current.CLAIM_DATE == null;
case 21: // WORK_CEASED_DATE
return Current.WORK_CEASED_DATE == null;
case 22: // SUCCESSFUL_CONTACT
return Current.SUCCESSFUL_CONTACT == null;
case 23: // OTHER_SUCCESSFUL_CONTACT
return Current.OTHER_SUCCESSFUL_CONTACT == null;
case 24: // DOCTOR
return Current.DOCTOR == null;
case 25: // OTHER_DOCTOR
return Current.OTHER_DOCTOR == null;
case 26: // HOSPITAL
return Current.HOSPITAL == null;
case 27: // AMBULANCE
return Current.AMBULANCE == null;
case 28: // ATTENDANCE_DATE
return Current.ATTENDANCE_DATE == null;
case 29: // ATTENDANCE_IN_TIME
return Current.ATTENDANCE_IN_TIME == null;
case 30: // ATTENDANCE_OUT_TIME
return Current.ATTENDANCE_OUT_TIME == null;
case 31: // SYMPTOMS
return Current.SYMPTOMS == null;
case 32: // SICKBAY_ACTION
return Current.SICKBAY_ACTION == null;
case 33: // ACTION_OUTCOME
return Current.ACTION_OUTCOME == null;
case 34: // SMS_KEY
return Current.SMS_KEY == null;
case 35: // EMAIL_KEY
return Current.EMAIL_KEY == null;
case 36: // LW_DATE
return Current.LW_DATE == null;
case 37: // LW_TIME
return Current.LW_TIME == null;
case 38: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SAIKEY
return "SAIKEY";
case 1: // ENTRY_TYPE
return "ENTRY_TYPE";
case 2: // ACCIDENTID
return "ACCIDENTID";
case 3: // INV_PERSON_TYPE
return "INV_PERSON_TYPE";
case 4: // INV_PERSONKEY
return "INV_PERSONKEY";
case 5: // INV_PERSON_DFAB
return "INV_PERSON_DFAB";
case 6: // INV_FULL_NAME
return "INV_FULL_NAME";
case 7: // INV_ADDRESS
return "INV_ADDRESS";
case 8: // INV_TELEPHONE
return "INV_TELEPHONE";
case 9: // INV_BIRTHDATE
return "INV_BIRTHDATE";
case 10: // INV_GENDER
return "INV_GENDER";
case 11: // INV_PAYROLL_REC_NO
return "INV_PAYROLL_REC_NO";
case 12: // INV_STAFF_TYPE
return "INV_STAFF_TYPE";
case 13: // HELP_PERSON_TYPE
return "HELP_PERSON_TYPE";
case 14: // HELP_PERSONKEY
return "HELP_PERSONKEY";
case 15: // HELP_PERSON_DFAB
return "HELP_PERSON_DFAB";
case 16: // HELP_FULL_NAME
return "HELP_FULL_NAME";
case 17: // INCIDENT_NO
return "INCIDENT_NO";
case 18: // SENT_TO_DEPT
return "SENT_TO_DEPT";
case 19: // CLAIM_LODGED
return "CLAIM_LODGED";
case 20: // CLAIM_DATE
return "CLAIM_DATE";
case 21: // WORK_CEASED_DATE
return "WORK_CEASED_DATE";
case 22: // SUCCESSFUL_CONTACT
return "SUCCESSFUL_CONTACT";
case 23: // OTHER_SUCCESSFUL_CONTACT
return "OTHER_SUCCESSFUL_CONTACT";
case 24: // DOCTOR
return "DOCTOR";
case 25: // OTHER_DOCTOR
return "OTHER_DOCTOR";
case 26: // HOSPITAL
return "HOSPITAL";
case 27: // AMBULANCE
return "AMBULANCE";
case 28: // ATTENDANCE_DATE
return "ATTENDANCE_DATE";
case 29: // ATTENDANCE_IN_TIME
return "ATTENDANCE_IN_TIME";
case 30: // ATTENDANCE_OUT_TIME
return "ATTENDANCE_OUT_TIME";
case 31: // SYMPTOMS
return "SYMPTOMS";
case 32: // SICKBAY_ACTION
return "SICKBAY_ACTION";
case 33: // ACTION_OUTCOME
return "ACTION_OUTCOME";
case 34: // SMS_KEY
return "SMS_KEY";
case 35: // EMAIL_KEY
return "EMAIL_KEY";
case 36: // LW_DATE
return "LW_DATE";
case 37: // LW_TIME
return "LW_TIME";
case 38: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SAIKEY":
return 0;
case "ENTRY_TYPE":
return 1;
case "ACCIDENTID":
return 2;
case "INV_PERSON_TYPE":
return 3;
case "INV_PERSONKEY":
return 4;
case "INV_PERSON_DFAB":
return 5;
case "INV_FULL_NAME":
return 6;
case "INV_ADDRESS":
return 7;
case "INV_TELEPHONE":
return 8;
case "INV_BIRTHDATE":
return 9;
case "INV_GENDER":
return 10;
case "INV_PAYROLL_REC_NO":
return 11;
case "INV_STAFF_TYPE":
return 12;
case "HELP_PERSON_TYPE":
return 13;
case "HELP_PERSONKEY":
return 14;
case "HELP_PERSON_DFAB":
return 15;
case "HELP_FULL_NAME":
return 16;
case "INCIDENT_NO":
return 17;
case "SENT_TO_DEPT":
return 18;
case "CLAIM_LODGED":
return 19;
case "CLAIM_DATE":
return 20;
case "WORK_CEASED_DATE":
return 21;
case "SUCCESSFUL_CONTACT":
return 22;
case "OTHER_SUCCESSFUL_CONTACT":
return 23;
case "DOCTOR":
return 24;
case "OTHER_DOCTOR":
return 25;
case "HOSPITAL":
return 26;
case "AMBULANCE":
return 27;
case "ATTENDANCE_DATE":
return 28;
case "ATTENDANCE_IN_TIME":
return 29;
case "ATTENDANCE_OUT_TIME":
return 30;
case "SYMPTOMS":
return 31;
case "SICKBAY_ACTION":
return 32;
case "ACTION_OUTCOME":
return 33;
case "SMS_KEY":
return 34;
case "EMAIL_KEY":
return 35;
case "LW_DATE":
return 36;
case "LW_TIME":
return 37;
case "LW_USER":
return 38;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Net;
using System.Security;
namespace CameraLib
{
/// <summary>
/// MJPEG video source.
/// </summary>
///
/// <remarks><para>The video source downloads JPEG images from the specified URL, which represents
/// MJPEG stream.</para>
///
/// <para>Sample usage:</para>
/// <code>
/// // create MJPEG video source
/// MJPEGStream stream = new MJPEGStream( "some url" );
/// // set event handlers
/// stream.NewFrame += new NewFrameEventHandler( video_NewFrame );
/// // start the video source
/// stream.Start( );
/// // ...
/// </code>
///
/// <para><note>Some cameras produce HTTP header, which does not conform strictly to
/// standard, what leads to .NET exception. To avoid this exception the <b>useUnsafeHeaderParsing</b>
/// configuration option of <b>httpWebRequest</b> should be set, what may be done using application
/// configuration file.</note></para>
/// <code>
/// <configuration>
/// <system.net>
/// <settings>
/// <httpWebRequest useUnsafeHeaderParsing="true" />
/// </settings>
/// </system.net>
/// </configuration>
/// </code>
/// </remarks>
///
public class MJPEGStream : IVideoSource
{
// URL for MJPEG stream
private string source;
// login and password for HTTP authentication
private string login = null;
private string password = null;
// proxy information
private IWebProxy proxy = null;
// received frames count
private int framesReceived;
// recieved byte count
private long bytesReceived;
// use separate HTTP connection group or use default
private bool useSeparateConnectionGroup = true;
// timeout value for web request
private int requestTimeout = 10000;
// if we should use basic authentication when connecting to the video source
private bool forceBasicAuthentication = false;
// buffer size used to download MJPEG stream
private const int bufSize = 1024 * 1024;
// size of portion to read at once
private const int readSize = 1024;
private Thread thread = null;
private ManualResetEvent stopEvent = null;
private ManualResetEvent reloadEvent = null;
private string userAgent = "Mozilla/5.0";
/// <summary>
/// New frame event.
/// </summary>
///
/// <remarks><para>Notifies clients about new available frame from video source.</para>
///
/// <para><note>Since video source may have multiple clients, each client is responsible for
/// making a copy (cloning) of the passed video frame, because the video source disposes its
/// own original copy after notifying of clients.</note></para>
/// </remarks>
///
public event NewFrameEventHandler NewFrame;
/// <summary>
/// Video source error event.
/// </summary>
///
/// <remarks>This event is used to notify clients about any type of errors occurred in
/// video source object, for example internal exceptions.</remarks>
///
public event VideoSourceErrorEventHandler VideoSourceError;
/// <summary>
/// Video playing finished event.
/// </summary>
///
/// <remarks><para>This event is used to notify clients that the video playing has finished.</para>
/// </remarks>
///
public event PlayingFinishedEventHandler PlayingFinished;
/// <summary>
/// Use or not separate connection group.
/// </summary>
///
/// <remarks>The property indicates to open web request in separate connection group.</remarks>
///
public bool SeparateConnectionGroup
{
get { return useSeparateConnectionGroup; }
set { useSeparateConnectionGroup = value; }
}
/// <summary>
/// Video source.
/// </summary>
///
/// <remarks>URL, which provides MJPEG stream.</remarks>
///
public string Source
{
get { return source; }
set
{
source = value;
// signal to reload
if ( thread != null )
reloadEvent.Set( );
}
}
/// <summary>
/// Login value.
/// </summary>
///
/// <remarks>Login required to access video source.</remarks>
///
public string Login
{
get { return login; }
set { login = value; }
}
/// <summary>
/// Password value.
/// </summary>
///
/// <remarks>Password required to access video source.</remarks>
///
public string Password
{
get { return password; }
set { password = value; }
}
/// <summary>
/// Gets or sets proxy information for the request.
/// </summary>
///
/// <remarks><para>The local computer or application config file may specify that a default
/// proxy to be used. If the Proxy property is specified, then the proxy settings from the Proxy
/// property overridea the local computer or application config file and the instance will use
/// the proxy settings specified. If no proxy is specified in a config file
/// and the Proxy property is unspecified, the request uses the proxy settings
/// inherited from Internet Explorer on the local computer. If there are no proxy settings
/// in Internet Explorer, the request is sent directly to the server.
/// </para></remarks>
///
public IWebProxy Proxy
{
get { return proxy; }
set { proxy = value; }
}
/// <summary>
/// User agent to specify in HTTP request header.
/// </summary>
///
/// <remarks><para>Some IP cameras check what is the requesting user agent and depending
/// on it they provide video in different formats or do not provide it at all. The property
/// sets the value of user agent string, which is sent to camera in request header.
/// </para>
///
/// <para>Default value is set to "Mozilla/5.0". If the value is set to <see langword="null"/>,
/// the user agent string is not sent in request header.</para>
/// </remarks>
///
public string HttpUserAgent
{
get { return userAgent; }
set { userAgent = value; }
}
/// <summary>
/// Received frames count.
/// </summary>
///
/// <remarks>Number of frames the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public int FramesReceived
{
get
{
int frames = framesReceived;
framesReceived = 0;
return frames;
}
}
/// <summary>
/// Received bytes count.
/// </summary>
///
/// <remarks>Number of bytes the video source provided from the moment of the last
/// access to the property.
/// </remarks>
///
public long BytesReceived
{
get
{
long bytes = bytesReceived;
bytesReceived = 0;
return bytes;
}
}
/// <summary>
/// Request timeout value.
/// </summary>
///
/// <remarks>The property sets timeout value in milliseconds for web requests.
/// Default value is 10000 milliseconds.</remarks>
///
public int RequestTimeout
{
get { return requestTimeout; }
set { requestTimeout = value; }
}
/// <summary>
/// State of the video source.
/// </summary>
///
/// <remarks>Current state of video source object - running or not.</remarks>
///
public bool IsRunning
{
get
{
if ( thread != null )
{
// check thread status
if ( thread.Join( 0 ) == false )
return true;
// the thread is not running, so free resources
Free( );
}
return false;
}
}
/// <summary>
/// Force using of basic authentication when connecting to the video source.
/// </summary>
///
/// <remarks><para>For some IP cameras (TrendNET IP cameras, for example) using standard .NET's authentication via credentials
/// does not seem to be working (seems like camera does not request for authentication, but expects corresponding headers to be
/// present on connection request). So this property allows to force basic authentication by adding required HTTP headers when
/// request is sent.</para>
///
/// <para>Default value is set to <see langword="false"/>.</para>
/// </remarks>
///
public bool ForceBasicAuthentication
{
get { return forceBasicAuthentication; }
set { forceBasicAuthentication = value; }
}
/// <summary>
/// Initializes a new instance of the <see cref="MJPEGStream"/> class.
/// </summary>
///
public MJPEGStream( ) { }
/// <summary>
/// Initializes a new instance of the <see cref="MJPEGStream"/> class.
/// </summary>
///
/// <param name="source">URL, which provides MJPEG stream.</param>
///
public MJPEGStream( string source )
{
this.source = source;
}
/// <summary>
/// Start video source.
/// </summary>
///
/// <remarks>Starts video source and return execution to caller. Video source
/// object creates background thread and notifies about new frames with the
/// help of <see cref="NewFrame"/> event.</remarks>
///
/// <exception cref="ArgumentException">Video source is not specified.</exception>
///
public void Start( )
{
if ( !IsRunning )
{
// check source
if ( ( source == null ) || ( source == string.Empty ) )
throw new ArgumentException( "Video source is not specified." );
framesReceived = 0;
bytesReceived = 0;
// create events
stopEvent = new ManualResetEvent( false );
reloadEvent = new ManualResetEvent( false );
// create and start new thread
thread = new Thread( new ThreadStart( WorkerThread ) );
thread.Name = source;
thread.Start( );
}
}
/// <summary>
/// Signal video source to stop its work.
/// </summary>
///
/// <remarks>Signals video source to stop its background thread, stop to
/// provide new frames and free resources.</remarks>
///
public void SignalToStop( )
{
// stop thread
if ( thread != null )
{
// signal to stop
stopEvent.Set( );
}
}
/// <summary>
/// Wait for video source has stopped.
/// </summary>
///
/// <remarks>Waits for source stopping after it was signalled to stop using
/// <see cref="SignalToStop"/> method.</remarks>
///
public void WaitForStop( )
{
if ( thread != null )
{
// wait for thread stop
thread.Join( );
Free( );
}
}
/// <summary>
/// Stop video source.
/// </summary>
///
/// <remarks><para>Stops video source aborting its thread.</para>
///
/// <para><note>Since the method aborts background thread, its usage is highly not preferred
/// and should be done only if there are no other options. The correct way of stopping camera
/// is <see cref="SignalToStop">signaling it stop</see> and then
/// <see cref="WaitForStop">waiting</see> for background thread's completion.</note></para>
/// </remarks>
///
public void Stop( )
{
if ( this.IsRunning )
{
stopEvent.Set( );
thread.Abort( );
WaitForStop( );
}
}
public bool TestConnecting()
{
return false;
}
/// <summary>
/// Free resource.
/// </summary>
///
private void Free( )
{
thread = null;
// release events
stopEvent.Close( );
stopEvent = null;
reloadEvent.Close( );
reloadEvent = null;
}
// Worker thread
private void WorkerThread( )
{
// buffer to read stream
byte[] buffer = new byte[bufSize];
// JPEG magic number
byte[] jpegMagic = new byte[] { 0xFF, 0xD8, 0xFF };
int jpegMagicLength = 3;
ASCIIEncoding encoding = new ASCIIEncoding( );
while ( !stopEvent.WaitOne( 0, false ) )
{
// reset reload event
reloadEvent.Reset( );
// HTTP web request
HttpWebRequest request = null;
// web responce
WebResponse response = null;
// stream for MJPEG downloading
Stream stream = null;
// boundary betweeen images (string and binary versions)
byte[] boundary = null;
string boudaryStr = null;
// length of boundary
int boundaryLen;
// flag signaling if boundary was checked or not
bool boundaryIsChecked = false;
// read amounts and positions
int read, todo = 0, total = 0, pos = 0, align = 1;
int start = 0, stop = 0;
// align
// 1 = searching for image start
// 2 = searching for image end
try
{
// create request
request = (HttpWebRequest) WebRequest.Create( source );
// set user agent
if ( userAgent != null )
{
request.UserAgent = userAgent;
}
// set proxy
if ( proxy != null )
{
request.Proxy = proxy;
}
// set timeout value for the request
request.Timeout = requestTimeout;
// set login and password
if ((login != null) && (password != null) && (login != string.Empty))
{
request.Credentials = new NetworkCredential(login, password);
}
// set connection group name
if ( useSeparateConnectionGroup )
request.ConnectionGroupName = GetHashCode( ).ToString( );
// force basic authentication through extra headers if required
if ( forceBasicAuthentication )
{
string authInfo = string.Format( "{0}:{1}", login, password );
authInfo = Convert.ToBase64String( Encoding.Default.GetBytes( authInfo ) );
request.Headers["Authorization"] = "Basic " + authInfo;
}
// get response
response = request.GetResponse( );
// check content type
string contentType = response.ContentType;
string[] contentTypeArray = contentType.Split( '/' );
// "application/octet-stream"
if ( ( contentTypeArray[0] == "application" ) && ( contentTypeArray[1] == "octet-stream" ) )
{
boundaryLen = 0;
boundary = new byte[0];
}
else if ( ( contentTypeArray[0] == "multipart" ) && ( contentType.Contains( "mixed" ) ) )
{
// get boundary
int boundaryIndex = contentType.IndexOf( "boundary", 0 );
if ( boundaryIndex != -1 )
{
boundaryIndex = contentType.IndexOf( "=", boundaryIndex + 8 );
}
if ( boundaryIndex == -1 )
{
// try same scenario as with octet-stream, i.e. without boundaries
boundaryLen = 0;
boundary = new byte[0];
}
else
{
boudaryStr = contentType.Substring( boundaryIndex + 1 );
// remove spaces and double quotes, which may be added by some IP cameras
boudaryStr = boudaryStr.Trim( ' ', '"' );
boundary = encoding.GetBytes( boudaryStr );
boundaryLen = boundary.Length;
boundaryIsChecked = false;
}
}
else
{
throw new Exception( "Invalid content type." );
}
// get response stream
stream = response.GetResponseStream( );
stream.ReadTimeout = requestTimeout;
// loop
while ( ( !stopEvent.WaitOne( 0, false ) ) && ( !reloadEvent.WaitOne( 0, false ) ) )
{
// check total read
if ( total > bufSize - readSize )
{
total = pos = todo = 0;
}
// read next portion from stream
if ( ( read = stream.Read( buffer, total, readSize ) ) == 0 )
throw new ApplicationException( );
total += read;
todo += read;
// increment received bytes counter
bytesReceived += read;
// do we need to check boundary ?
if ( ( boundaryLen != 0 ) && ( !boundaryIsChecked ) )
{
// some IP cameras, like AirLink, claim that boundary is "myboundary",
// when it is really "--myboundary". this needs to be corrected.
pos = ByteArrayUtils.Find( buffer, boundary, 0, todo );
// continue reading if boudary was not found
if ( pos == -1 )
continue;
for ( int i = pos - 1; i >= 0; i-- )
{
byte ch = buffer[i];
if ( ( ch == (byte) '\n' ) || ( ch == (byte) '\r' ) )
{
break;
}
boudaryStr = (char) ch + boudaryStr;
}
boundary = encoding.GetBytes( boudaryStr );
boundaryLen = boundary.Length;
boundaryIsChecked = true;
}
// search for image start
if ( ( align == 1 ) && ( todo >= jpegMagicLength ) )
{
start = ByteArrayUtils.Find( buffer, jpegMagic, pos, todo );
if ( start != -1 )
{
// found JPEG start
pos = start + jpegMagicLength;
todo = total - pos;
align = 2;
}
else
{
// delimiter not found
todo = jpegMagicLength - 1;
pos = total - todo;
}
}
// search for image end ( boundaryLen can be 0, so need extra check )
while ( ( align == 2 ) && ( todo != 0 ) && ( todo >= boundaryLen ) )
{
stop = ByteArrayUtils.Find( buffer,
( boundaryLen != 0 ) ? boundary : jpegMagic,
pos, todo );
if ( stop != -1 )
{
pos = stop;
todo = total - pos;
// increment frames counter
framesReceived ++;
// image at stop
if ( ( NewFrame != null ) && ( !stopEvent.WaitOne( 0, false ) ) )
{
Bitmap bitmap = (Bitmap) Bitmap.FromStream ( new MemoryStream( buffer, start, stop - start ) );
// notify client
NewFrame( this, new NewFrameEventArgs( bitmap ) );
// release the image
bitmap.Dispose( );
bitmap = null;
}
// shift array
pos = stop + boundaryLen;
todo = total - pos;
Array.Copy( buffer, pos, buffer, 0, todo );
total = todo;
pos = 0;
align = 1;
}
else
{
// boundary not found
if ( boundaryLen != 0 )
{
todo = boundaryLen - 1;
pos = total - todo;
}
else
{
todo = 0;
pos = total;
}
}
}
}
}
catch ( ApplicationException )
{
// do nothing for Application Exception, which we raised on our own
// wait for a while before the next try
Thread.Sleep( 250 );
}
catch ( ThreadAbortException )
{
break;
}
catch ( Exception exception )
{
// provide information to clients
if ( VideoSourceError != null )
{
VideoSourceError( this, new VideoSourceErrorEventArgs( exception.Message ) );
}
// wait for a while before the next try
Thread.Sleep( 250 );
}
finally
{
// abort request
if ( request != null)
{
request.Abort( );
request = null;
}
// close response stream
if ( stream != null )
{
stream.Close( );
stream = null;
}
// close response
if ( response != null )
{
response.Close( );
response = null;
}
}
// need to stop ?
if ( stopEvent.WaitOne( 0, false ) )
break;
}
if ( PlayingFinished != null )
{
PlayingFinished( this, ReasonToFinishPlaying.StoppedByUser );
}
}
}
}
| |
using System;
using CocosSharp;
namespace tests
{
public class TextInputTest : TestNavigationLayer
{
KeyboardNotificationLayer notificationLayer;
TextInputTestScene textinputTestScene = new TextInputTestScene();
public override void RestartCallback(object sender)
{
CCScene s = new TextInputTestScene();
s.AddChild(textinputTestScene.restartTextInputTest());
Scene.Director.ReplaceScene(s);
}
public override void NextCallback(object sender)
{
CCScene s = new TextInputTestScene();
s.AddChild(textinputTestScene.nextTextInputTest());
Scene.Director.ReplaceScene(s);
}
public override void BackCallback(object sender)
{
CCScene s = new TextInputTestScene();
s.AddChild(textinputTestScene.backTextInputTest());
Scene.Director.ReplaceScene(s);
}
public void addKeyboardNotificationLayer(KeyboardNotificationLayer layer)
{
notificationLayer = layer;
AddChild(layer);
}
public override string Title
{
get
{
return "CCTextField Text Input Test";
}
}
public override string Subtitle
{
get
{
return (notificationLayer != null) ? notificationLayer.Subtitle : string.Empty;
}
}
}
public class KeyboardNotificationLayer : CCNode
{
CCTextField trackNode;
protected CCPoint beginPosition;
public KeyboardNotificationLayer()
{
// Register Touch Event
var touchListener = new CCEventListenerTouchOneByOne();
touchListener.IsSwallowTouches = true;
touchListener.OnTouchBegan = OnTouchBegan;
touchListener.OnTouchEnded = OnTouchEnded;
AddEventListener(touchListener);
}
public virtual string Subtitle
{
get { return string.Empty; }
}
public virtual void OnClickTrackNode(bool bClicked)
{
throw new NotFiniteNumberException();
}
bool OnTouchBegan(CCTouch pTouch, CCEvent touchEvent)
{
beginPosition = pTouch.Location;
return true;
}
void OnTouchEnded(CCTouch pTouch, CCEvent touchEvent)
{
if (trackNode == null)
{
return;
}
var endPos = pTouch.Location;
if (trackNode.BoundingBox.ContainsPoint(beginPosition) && trackNode.BoundingBox.ContainsPoint(endPos))
{
OnClickTrackNode(true);
}
else
{
OnClickTrackNode(false);
}
}
public override void OnExit()
{
base.OnExit();
if (trackNode != null)
{
trackNode.EndEdit();
DetachListeners();
}
}
protected CCTextField TrackNode
{
get { return trackNode; }
set
{
if (value == null)
{
if (trackNode != null)
{
DetachListeners();
trackNode = value;
return;
}
}
if (trackNode != value)
{
DetachListeners();
}
trackNode = value;
AttachListeners();
}
}
void AttachListeners ()
{
// Remember to remove our event listeners.
var imeImplementation = trackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.KeyboardWillHide += OnKeyboardWillHide;
imeImplementation.KeyboardWillShow += OnKeyboardWillShow;
}
void DetachListeners ()
{
if (TrackNode != null)
{
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.KeyboardWillHide -= OnKeyboardWillHide;
imeImplementation.KeyboardWillShow -= OnKeyboardWillShow;
}
}
void OnKeyboardWillShow(object sender, CCIMEKeyboardNotificationInfo e)
{
CCLog.Log("Keyboard will show");
}
void OnKeyboardWillHide(object sender, CCIMEKeyboardNotificationInfo e)
{
CCLog.Log("Keyboard will Hide");
}
void OnKeyboardDidShow(object sender, CCIMEKeyboardNotificationInfo e)
{
CCLog.Log("Keyboard did show");
}
void OnKeyboardDidHide(object sender, CCIMEKeyboardNotificationInfo e)
{
CCLog.Log("Keyboard did hide");
}
}
public class TextFieldDefaultTest : KeyboardNotificationLayer
{
CCMoveTo scrollUp;
CCMoveTo scrollDown;
public override void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
TrackNode.Edit();
}
else
{
if (TrackNode != null && TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
public override void OnEnter()
{
base.OnEnter();
var s = VisibleBoundsWorldspace.Size;
var textField = new CCTextField("<click here for input>",
TextInputTestScene.FONT_NAME,
TextInputTestScene.FONT_SIZE,
CCLabelFormat.SpriteFont);
textField.BeginEditing += OnBeginEditing;
textField.EndEditing += OnEndEditing;
textField.Position = s.Center;
textField.AutoEdit = true;
AddChild(textField);
TrackNode = textField;
scrollUp = new CCMoveTo(0.5f, VisibleBoundsWorldspace.Top() - new CCPoint(0, s.Height / 4));
scrollDown = new CCMoveTo(0.5f, textField.Position);
}
private void OnEndEditing(object sender, ref string text, ref bool canceled)
{
((CCNode)sender).RunAction(scrollDown);
}
private void OnBeginEditing(object sender, ref string text, ref bool canceled)
{
((CCNode)sender).RunAction(scrollUp);
}
public override string Subtitle
{
get {
return "TextField with default behavior test";
}
}
}
//////////////////////////////////////////////////////////////////////////
// TextFieldActionTest
//////////////////////////////////////////////////////////////////////////
public class TextFieldActionTest : KeyboardNotificationLayer
{
CCTextField textField;
static CCFiniteTimeAction textFieldAction = new CCSequence(
new CCFadeOut(0.25f),
new CCFadeIn(0.25f));
CCActionState textFieldActionState;
bool action;
int charLimit; // the textfield max char limit
const int RANDOM_MAX = 32767;
public void callbackRemoveNodeWhenDidAction(CCNode node)
{
this.RemoveChild(node, true);
}
public override string Subtitle
{
get {
return "CCTextField with action and char limit test";
}
}
public override void OnClickTrackNode(bool bClicked)
{
if (bClicked)
{
TrackNode.Edit();
}
else
{
TrackNode.EndEdit();
}
}
// CCLayer
public override void OnEnter()
{
base.OnEnter();
charLimit = 12;
action = false;
textField = new CCTextField("<click here for input>",
TextInputTestScene.FONT_NAME,
TextInputTestScene.FONT_SIZE,
CCLabelFormat.SpriteFont);
var imeImplementation = textField.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide += OnKeyboardDidHide;
imeImplementation.KeyboardDidShow += OnKeyboardDidShow;
imeImplementation.InsertText += OnInsertText;
imeImplementation.ReplaceText += OnReplaceText;
imeImplementation.DeleteBackward += OnDeleteBackward;
textField.Position = VisibleBoundsWorldspace.Center;
textField.PositionY += VisibleBoundsWorldspace.Size.Height / 4;
AddChild(textField);
TrackNode = textField;
}
public override void OnExit()
{
base.OnExit();
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.KeyboardDidHide -= OnKeyboardDidHide;
imeImplementation.KeyboardDidShow -= OnKeyboardDidShow;
imeImplementation.InsertText -= OnInsertText;
imeImplementation.ReplaceText -= OnReplaceText;
imeImplementation.DeleteBackward -= OnDeleteBackward;
}
void OnDeleteBackward (object sender, CCIMEKeybardEventArgs e)
{
var focusedTextField = sender as CCTextField;
if (focusedTextField == null || string.IsNullOrEmpty(focusedTextField.Text))
{
e.Cancel = true;
return;
}
// Just cancel this if we would backspace over the PlaceHolderText as it would just be
// replaced anyway and the Action below should not be executed.
var delText = focusedTextField.Text;
if (delText == focusedTextField.PlaceHolderText)
{
e.Cancel = true;
return;
}
delText = delText.Substring(delText.Length - 1);
// create a delete text sprite and do some action
var label = new CCLabel(delText, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE + 3, CCLabelFormat.SpriteFont);
this.AddChild(label);
// move the sprite to fly out
CCPoint beginPos = focusedTextField.Position;
CCSize textfieldSize = focusedTextField.ContentSize;
CCSize labelSize = label.ContentSize;
beginPos.X += (textfieldSize.Width - labelSize.Width) / 2.0f;
var nextRandom = (float)CCRandom.Next(RANDOM_MAX);
CCSize winSize = VisibleBoundsWorldspace.Size;
CCPoint endPos = new CCPoint(-winSize.Width / 4.0f, winSize.Height * (0.5f + nextRandom / (2.0f * RANDOM_MAX)));
float duration = 1;
float rotateDuration = 0.2f;
int repeatTime = 5;
label.Position = beginPos;
var delAction = new CCSpawn(new CCMoveTo(duration, endPos),
new CCRepeat(
new CCRotateBy(rotateDuration, (CCRandom.Next() % 2 > 0) ? 360 : -360),
(uint)repeatTime),
new CCFadeOut(duration)
);
label.RunActionsAsync(delAction, new CCRemoveSelf(true));
}
void OnInsertText (object sender, CCIMEKeybardEventArgs e)
{
var focusedTextField = sender as CCTextField;
if (focusedTextField == null)
{
e.Cancel = true;
return;
}
var text = e.Text;
var currentText = focusedTextField.Text;
// if insert enter, treat as default to detach with ime
if ("\n" == text)
{
return;
}
// if the textfield's char count is more than charLimit, don't insert text anymore.
if (focusedTextField.CharacterCount >= charLimit)
{
e.Cancel = true;
return;
}
// create a insert text sprite and do some action
var label = new CCLabel(text, TextInputTestScene.FONT_NAME, TextInputTestScene.FONT_SIZE, CCLabelFormat.SpriteFont);
this.AddChild(label);
var color = new CCColor3B { R = 226, G = 121, B = 7 };
label.Color = color;
var inputTextSize = focusedTextField.CharacterCount == 0 ? CCSize.Zero : focusedTextField.ContentSize;
// move the sprite from top to position
var endPos = focusedTextField.Position;
endPos.Y -= inputTextSize.Height;
if (currentText.Length > 0)
{
endPos.X += inputTextSize.Width / 2;
}
var beginPos = new CCPoint(endPos.X, VisibleBoundsWorldspace.Size.Height - inputTextSize.Height * 2);
var duration = 0.5f;
label.Position = beginPos;
label.Scale = 8;
CCAction seq = new CCSequence(
new CCSpawn(
new CCMoveTo(duration, endPos),
new CCScaleTo(duration, 1),
new CCFadeOut(duration)),
new CCRemoveSelf(true));
label.RunAction(seq);
}
void OnReplaceText (object sender, CCIMEKeybardEventArgs e)
{
var focusedTextField = sender as CCTextField;
if (e.Length > charLimit)
e.Text = e.Text.Substring (0, charLimit - 1);
}
void OnKeyboardDidShow(object sender, CCIMEKeyboardNotificationInfo e)
{
if (!action)
{
textFieldActionState = textField.RepeatForever(textFieldAction);
action = true;
}
}
void OnKeyboardDidHide(object sender, CCIMEKeyboardNotificationInfo e)
{
if (action)
{
textField.StopAction(textFieldActionState);
textField.Opacity = 255;
action = false;
}
}
}
public class TextFieldUpperCaseTest : KeyboardNotificationLayer
{
public override void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
TrackNode.Edit();
}
else
{
if (TrackNode != null && TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
public override void OnEnter()
{
base.OnEnter();
var s = VisibleBoundsWorldspace.Size;
var textField = new CCTextField("<CLICK HERE FOR INPUT>",
TextInputTestScene.FONT_NAME,
TextInputTestScene.FONT_SIZE,
CCLabelFormat.SpriteFont);
var imeImplementation = textField.TextFieldIMEImplementation;
imeImplementation.InsertText += OnInsertText;
imeImplementation.ReplaceText += OnReplaceText;
textField.Position = s.Center;
textField.AutoEdit = true;
AddChild(textField);
TrackNode = textField;
}
public override void OnExit()
{
base.OnExit();
// Remember to remove our event listeners.
var imeImplementation = TrackNode.TextFieldIMEImplementation;
imeImplementation.InsertText -= OnInsertText;
imeImplementation.ReplaceText -= OnReplaceText;
}
void OnInsertText (object sender, CCIMEKeybardEventArgs e)
{
var focusedTextField = sender as CCTextField;
e.Text = e.Text.ToUpper();
}
void OnReplaceText (object sender, CCIMEKeybardEventArgs e)
{
var focusedTextField = sender as CCTextField;
e.Text = e.Text.ToUpper();
}
public override string Subtitle
{
get {
return "TextField Uppercase test";
}
}
}
public class TextFieldCustomIMETest : KeyboardNotificationLayer
{
public override void OnClickTrackNode(bool bClicked)
{
if (bClicked && TrackNode != null)
{
TrackNode.Edit();
}
else
{
if (TrackNode != null && TrackNode != null)
{
TrackNode.EndEdit();
}
}
}
public override void OnEnter()
{
base.OnEnter();
var s = VisibleBoundsWorldspace.Size;
var textField = new CCTextField("<CLICK HERE FOR INPUT>",
TextInputTestScene.FONT_NAME,
TextInputTestScene.FONT_SIZE,
CCLabelFormat.SpriteFont);
// Override the default implementation
textField.TextFieldIMEImplementation = null; //IMEKeyboardImpl.SharedInstance;
textField.Position = s.Center;
textField.AutoEdit = true;
AddChild(textField);
TrackNode = textField;
}
public override string Subtitle
{
get {
return "TextField Custom Uppercase IME implementation";
}
}
}
}
| |
// ------------------------------------------------------------------------------
// 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.
// Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Linq.Expressions;
/// <summary>
/// The type DomainDnsUnavailableRecordRequest.
/// </summary>
public partial class DomainDnsUnavailableRecordRequest : BaseRequest, IDomainDnsUnavailableRecordRequest
{
/// <summary>
/// Constructs a new DomainDnsUnavailableRecordRequest.
/// </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 DomainDnsUnavailableRecordRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
}
/// <summary>
/// Creates the specified DomainDnsUnavailableRecord using POST.
/// </summary>
/// <param name="domainDnsUnavailableRecordToCreate">The DomainDnsUnavailableRecord to create.</param>
/// <returns>The created DomainDnsUnavailableRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsUnavailableRecord> CreateAsync(DomainDnsUnavailableRecord domainDnsUnavailableRecordToCreate)
{
return this.CreateAsync(domainDnsUnavailableRecordToCreate, CancellationToken.None);
}
/// <summary>
/// Creates the specified DomainDnsUnavailableRecord using POST.
/// </summary>
/// <param name="domainDnsUnavailableRecordToCreate">The DomainDnsUnavailableRecord to create.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The created DomainDnsUnavailableRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsUnavailableRecord> CreateAsync(DomainDnsUnavailableRecord domainDnsUnavailableRecordToCreate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "POST";
var newEntity = await this.SendAsync<DomainDnsUnavailableRecord>(domainDnsUnavailableRecordToCreate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(newEntity);
return newEntity;
}
/// <summary>
/// Deletes the specified DomainDnsUnavailableRecord.
/// </summary>
/// <returns>The task to await.</returns>
public System.Threading.Tasks.Task DeleteAsync()
{
return this.DeleteAsync(CancellationToken.None);
}
/// <summary>
/// Deletes the specified DomainDnsUnavailableRecord.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await.</returns>
public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken)
{
this.Method = "DELETE";
await this.SendAsync<DomainDnsUnavailableRecord>(null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets the specified DomainDnsUnavailableRecord.
/// </summary>
/// <returns>The DomainDnsUnavailableRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsUnavailableRecord> GetAsync()
{
return this.GetAsync(CancellationToken.None);
}
/// <summary>
/// Gets the specified DomainDnsUnavailableRecord.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The DomainDnsUnavailableRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsUnavailableRecord> GetAsync(CancellationToken cancellationToken)
{
this.Method = "GET";
var retrievedEntity = await this.SendAsync<DomainDnsUnavailableRecord>(null, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(retrievedEntity);
return retrievedEntity;
}
/// <summary>
/// Updates the specified DomainDnsUnavailableRecord using PATCH.
/// </summary>
/// <param name="domainDnsUnavailableRecordToUpdate">The DomainDnsUnavailableRecord to update.</param>
/// <returns>The updated DomainDnsUnavailableRecord.</returns>
public System.Threading.Tasks.Task<DomainDnsUnavailableRecord> UpdateAsync(DomainDnsUnavailableRecord domainDnsUnavailableRecordToUpdate)
{
return this.UpdateAsync(domainDnsUnavailableRecordToUpdate, CancellationToken.None);
}
/// <summary>
/// Updates the specified DomainDnsUnavailableRecord using PATCH.
/// </summary>
/// <param name="domainDnsUnavailableRecordToUpdate">The DomainDnsUnavailableRecord to update.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The updated DomainDnsUnavailableRecord.</returns>
public async System.Threading.Tasks.Task<DomainDnsUnavailableRecord> UpdateAsync(DomainDnsUnavailableRecord domainDnsUnavailableRecordToUpdate, CancellationToken cancellationToken)
{
this.ContentType = "application/json";
this.Method = "PATCH";
var updatedEntity = await this.SendAsync<DomainDnsUnavailableRecord>(domainDnsUnavailableRecordToUpdate, cancellationToken).ConfigureAwait(false);
this.InitializeCollectionProperties(updatedEntity);
return updatedEntity;
}
/// <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 IDomainDnsUnavailableRecordRequest 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 IDomainDnsUnavailableRecordRequest Expand(Expression<Func<DomainDnsUnavailableRecord, 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 IDomainDnsUnavailableRecordRequest 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 IDomainDnsUnavailableRecordRequest Select(Expression<Func<DomainDnsUnavailableRecord, 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>
/// Initializes any collection properties after deserialization, like next requests for paging.
/// </summary>
/// <param name="domainDnsUnavailableRecordToInitialize">The <see cref="DomainDnsUnavailableRecord"/> with the collection properties to initialize.</param>
private void InitializeCollectionProperties(DomainDnsUnavailableRecord domainDnsUnavailableRecordToInitialize)
{
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using MigraDoc.Rendering;
using MigraDoc.Rendering.UnitTest;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.IO;
namespace XGraphicsRendererTester
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
private System.Windows.Forms.Button button4;
private System.Windows.Forms.Button button5;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button button7;
private System.Windows.Forms.Button button8;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button button9;
private System.Windows.Forms.Button button10;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Button Borders;
private System.Windows.Forms.Button button11;
private System.Windows.Forms.Button btnFile;
private System.Windows.Forms.TextBox tbxDdlFile;
private System.Windows.Forms.Button button12;
private System.Windows.Forms.GroupBox groupBox4;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool _disposing)
{
if(_disposing)
{
if (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.button1 = new System.Windows.Forms.Button();
this.textBox1 = new System.Windows.Forms.TextBox();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.button4 = new System.Windows.Forms.Button();
this.button5 = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.button8 = new System.Windows.Forms.Button();
this.button7 = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button10 = new System.Windows.Forms.Button();
this.button9 = new System.Windows.Forms.Button();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.button11 = new System.Windows.Forms.Button();
this.Borders = new System.Windows.Forms.Button();
this.btnFile = new System.Windows.Forms.Button();
this.tbxDdlFile = new System.Windows.Forms.TextBox();
this.button12 = new System.Windows.Forms.Button();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(20, 24);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(116, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Iterator";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(464, 144);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(252, 364);
this.textBox1.TabIndex = 1;
this.textBox1.Text = "";
this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
//
// button2
//
this.button2.Location = new System.Drawing.Point(20, 68);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(116, 24);
this.button2.TabIndex = 2;
this.button2.Text = "Text And Blanks";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Location = new System.Drawing.Point(24, 108);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(112, 24);
this.button3.TabIndex = 3;
this.button3.Text = "Formatted Text";
this.button3.Click += new System.EventHandler(this.button3_Click);
//
// button4
//
this.button4.Location = new System.Drawing.Point(160, 24);
this.button4.Name = "button4";
this.button4.Size = new System.Drawing.Size(108, 24);
this.button4.TabIndex = 4;
this.button4.Text = "Alignment";
this.button4.Click += new System.EventHandler(this.button4_Click);
//
// button5
//
this.button5.Location = new System.Drawing.Point(160, 68);
this.button5.Name = "button5";
this.button5.Size = new System.Drawing.Size(108, 24);
this.button5.TabIndex = 5;
this.button5.Text = "Tabs";
this.button5.Click += new System.EventHandler(this.button5_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(12, 24);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(100, 24);
this.button6.TabIndex = 6;
this.button6.Text = "Dump Paragraph";
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.button8);
this.groupBox1.Controls.Add(this.button7);
this.groupBox1.Controls.Add(this.button6);
this.groupBox1.Location = new System.Drawing.Point(464, 8);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(252, 132);
this.groupBox1.TabIndex = 7;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Layout";
//
// button8
//
this.button8.Location = new System.Drawing.Point(136, 24);
this.button8.Name = "button8";
this.button8.Size = new System.Drawing.Size(104, 24);
this.button8.TabIndex = 8;
this.button8.Text = "1000 Paragraphs";
this.button8.Click += new System.EventHandler(this.button8_Click);
//
// button7
//
this.button7.Location = new System.Drawing.Point(12, 64);
this.button7.Name = "button7";
this.button7.Size = new System.Drawing.Size(100, 28);
this.button7.TabIndex = 7;
this.button7.Text = "2 Paragraphs";
this.button7.Click += new System.EventHandler(this.button7_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.button10);
this.groupBox2.Controls.Add(this.button9);
this.groupBox2.Location = new System.Drawing.Point(12, 8);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(432, 132);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Paragraphs";
//
// button10
//
this.button10.Location = new System.Drawing.Point(292, 20);
this.button10.Name = "button10";
this.button10.Size = new System.Drawing.Size(120, 24);
this.button10.TabIndex = 1;
this.button10.Text = "Fields";
this.button10.Click += new System.EventHandler(this.button10_Click);
//
// button9
//
this.button9.Location = new System.Drawing.Point(148, 100);
this.button9.Name = "button9";
this.button9.Size = new System.Drawing.Size(108, 24);
this.button9.TabIndex = 0;
this.button9.Text = "Borders";
this.button9.Click += new System.EventHandler(this.button9_Click);
//
// groupBox3
//
this.groupBox3.Controls.Add(this.button11);
this.groupBox3.Controls.Add(this.Borders);
this.groupBox3.Location = new System.Drawing.Point(16, 168);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(240, 180);
this.groupBox3.TabIndex = 9;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "Tables";
//
// button11
//
this.button11.Location = new System.Drawing.Point(148, 32);
this.button11.Name = "button11";
this.button11.TabIndex = 1;
this.button11.Text = "Cell Merge";
this.button11.Click += new System.EventHandler(this.button11_Click);
//
// Borders
//
this.Borders.Location = new System.Drawing.Point(12, 32);
this.Borders.Name = "Borders";
this.Borders.Size = new System.Drawing.Size(108, 24);
this.Borders.TabIndex = 0;
this.Borders.Text = "Borders, Shading";
this.Borders.Click += new System.EventHandler(this.Borders_Click);
//
// btnFile
//
this.btnFile.Location = new System.Drawing.Point(216, 376);
this.btnFile.Name = "btnFile";
this.btnFile.Size = new System.Drawing.Size(28, 20);
this.btnFile.TabIndex = 10;
this.btnFile.Text = "...";
this.btnFile.Click += new System.EventHandler(this.btnFile_Click);
//
// tbxDdlFile
//
this.tbxDdlFile.Location = new System.Drawing.Point(16, 376);
this.tbxDdlFile.Name = "tbxDdlFile";
this.tbxDdlFile.Size = new System.Drawing.Size(188, 20);
this.tbxDdlFile.TabIndex = 11;
this.tbxDdlFile.Text = "";
//
// button12
//
this.button12.Location = new System.Drawing.Point(20, 412);
this.button12.Name = "button12";
this.button12.Size = new System.Drawing.Size(60, 20);
this.button12.TabIndex = 12;
this.button12.Text = "PDF";
this.button12.Click += new System.EventHandler(this.button12_Click);
//
// groupBox4
//
this.groupBox4.Location = new System.Drawing.Point(12, 356);
this.groupBox4.Name = "groupBox4";
this.groupBox4.Size = new System.Drawing.Size(248, 140);
this.groupBox4.TabIndex = 13;
this.groupBox4.TabStop = false;
this.groupBox4.Text = "DDL-Rendering";
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(740, 522);
this.Controls.Add(this.button12);
this.Controls.Add(this.tbxDdlFile);
this.Controls.Add(this.btnFile);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.button5);
this.Controls.Add(this.button4);
this.Controls.Add(this.button3);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.groupBox4);
this.Name = "Form1";
this.Text = "Form1";
this.groupBox1.ResumeLayout(false);
this.groupBox2.ResumeLayout(false);
this.groupBox3.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new Form1());
// Document document = new Document();
// Section section = new Section();
// Paragraph paragraph = new Paragraph();
// paragraph.AddText("This is a Text");
// section.Add(paragraph);
// document.Add(section);
//
// PdfPrinter printer = new PdfPrinter();
// printer.Document = document;
// printer.PrintDocument();
}
private void button1_Click(object sender, System.EventArgs e)
{
Document document = new Document();
Section section = document.AddSection();
Paragraph paragraph = section.AddParagraph();
paragraph.AddText("Hallo");
FormattedText formText = paragraph.AddFormattedText("formattedText", TextFormat.Bold);
formText.AddFormattedText("formattedTextNested", TextFormat.Italic);
formText.AddDateField();
this.textBox1.Text = TestParagraphIterator.GetBackIterators(paragraph);
}
private void textBox1_TextChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.TextAndBlanks("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button3_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.Formatted("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button4_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.Alignment("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button5_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.Tabs("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button6_Click(object sender, System.EventArgs e)
{
this.textBox1.Text = TestLayout.DumpParagraph();
}
private void button7_Click(object sender, System.EventArgs e)
{
TestLayout.TwoParagraphs("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button8_Click(object sender, System.EventArgs e)
{
TestLayout.A1000Paragraphs("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button9_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.Borders("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button10_Click(object sender, System.EventArgs e)
{
TestParagraphRenderer.Fields("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void Borders_Click(object sender, System.EventArgs e)
{
TestTable.Borders("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void button11_Click(object sender, System.EventArgs e)
{
TestTable.CellMerge("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
private void btnFile_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() == DialogResult.OK)
{
this.tbxDdlFile.Text = fileDialog.FileName;
}
}
private void button12_Click(object sender, System.EventArgs e)
{
if (this.tbxDdlFile.Text != "")
{
try
{
Document doc = DdlReader.DocumentFromFile(tbxDdlFile.Text);
PdfPrinter pdfPrinter = new PdfPrinter();
pdfPrinter.Document = doc;
pdfPrinter.PrintDocument();
pdfPrinter.PdfDocument.Save("egal.pdf");
System.Diagnostics.Process.Start("egal.pdf");
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}
}
}
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = CrossPlatformInputManager.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, ~0, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
if (!m_UseHeadBob)
{
return;
}
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = CrossPlatformInputManager.GetAxis("Horizontal");
float vertical = CrossPlatformInputManager.GetAxis("Vertical");
/*// Use last device which provided input.
var inputDevice = InputManager.ActiveDevice;
// Disable and hide touch controls if we use a controller.
// If "Enable Controls On Touch" is ticked in Touch Manager inspector,
// controls will be enabled and shown again when the screen is touched.
if (inputDevice != InputDevice.Null && inputDevice != TouchManager.Device) {
TouchManager.ControlsEnabled = false;
}*/
bool waswalking = m_IsWalking;
#if !MOBILE_INPUT
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
#endif
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
#region License
//
// Copyright (c) 2018, Fluent Migrator Project
//
// 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.Data;
using FluentMigrator.Runner.Generators.MySql;
using NUnit.Framework;
using Shouldly;
namespace FluentMigrator.Tests.Unit.Generators.MySql4
{
[TestFixture]
public class MySql4ConstraintsTests : BaseConstraintsTests
{
protected MySql4Generator Generator;
[SetUp]
public void Setup()
{
Generator = new MySql4Generator();
}
[Test]
public override void CanCreateForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestTable2_TestColumn2` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestTable2_TestColumn2` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestTable2_TestColumn2` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_TestTable1_TestColumn1_TestColumn3_TestTable2_TestColumn2_TestColumn4` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `PK_TestTable1_TestColumn1_TestColumn2` PRIMARY KEY (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `PK_TestTable1_TestColumn1_TestColumn2` PRIMARY KEY (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `UC_TestTable1_TestColumn1_TestColumn2` UNIQUE (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `UC_TestTable1_TestColumn1_TestColumn2` UNIQUE (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateNamedForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateNamedForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`)");
}
[Test]
public override void CanCreateNamedForeignKeyWithOnDeleteAndOnUpdateOptions()
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = Rule.Cascade;
expression.ForeignKey.OnUpdate = Rule.SetDefault;
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`) ON DELETE CASCADE ON UPDATE SET DEFAULT");
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnDeleteOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnDelete = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`) ON DELETE {0}", output));
}
[TestCase(Rule.SetDefault, "SET DEFAULT"), TestCase(Rule.SetNull, "SET NULL"), TestCase(Rule.Cascade, "CASCADE")]
public override void CanCreateNamedForeignKeyWithOnUpdateOptions(Rule rule, string output)
{
var expression = GeneratorTestHelper.GetCreateNamedForeignKeyExpression();
expression.ForeignKey.OnUpdate = rule;
var result = Generator.Generate(expression);
result.ShouldBe(string.Format("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`) REFERENCES `TestTable2` (`TestColumn2`) ON UPDATE {0}", output));
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
expression.ForeignKey.PrimaryTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateNamedMultiColumnForeignKeyWithDifferentSchemas()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `FK_Test` FOREIGN KEY (`TestColumn1`, `TestColumn3`) REFERENCES `TestTable2` (`TestColumn2`, `TestColumn4`)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTPRIMARYKEY` PRIMARY KEY (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateNamedMultiColumnPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTPRIMARYKEY` PRIMARY KEY (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTUNIQUECONSTRAINT` UNIQUE (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateNamedMultiColumnUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedMultiColumnUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTUNIQUECONSTRAINT` UNIQUE (`TestColumn1`, `TestColumn2`)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTPRIMARYKEY` PRIMARY KEY (`TestColumn1`)");
}
[Test]
public override void CanCreateNamedPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedPrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTPRIMARYKEY` PRIMARY KEY (`TestColumn1`)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTUNIQUECONSTRAINT` UNIQUE (`TestColumn1`)");
}
[Test]
public override void CanCreateNamedUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateNamedUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `TESTUNIQUECONSTRAINT` UNIQUE (`TestColumn1`)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `PK_TestTable1_TestColumn1` PRIMARY KEY (`TestColumn1`)");
}
[Test]
public override void CanCreatePrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreatePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `PK_TestTable1_TestColumn1` PRIMARY KEY (`TestColumn1`)");
}
[Test]
public override void CanCreateUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `UC_TestTable1_TestColumn1` UNIQUE (`TestColumn1`)");
}
[Test]
public override void CanCreateUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetCreateUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` ADD CONSTRAINT `UC_TestTable1_TestColumn1` UNIQUE (`TestColumn1`)");
}
[Test]
public override void CanDropForeignKeyWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
expression.ForeignKey.ForeignTableSchema = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP FOREIGN KEY `FK_Test`");
}
[Test]
public override void CanDropForeignKeyWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteForeignKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP FOREIGN KEY `FK_Test`");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP PRIMARY KEY");
}
[Test]
public override void CanDropPrimaryKeyConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeletePrimaryKeyExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP PRIMARY KEY");
}
[Test]
public override void CanDropUniqueConstraintWithCustomSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
expression.Constraint.SchemaName = "TestSchema";
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP INDEX `TESTUNIQUECONSTRAINT`");
}
[Test]
public override void CanDropUniqueConstraintWithDefaultSchema()
{
var expression = GeneratorTestHelper.GetDeleteUniqueConstraintExpression();
var result = Generator.Generate(expression);
result.ShouldBe("ALTER TABLE `TestTable1` DROP INDEX `TESTUNIQUECONSTRAINT`");
}
}
}
| |
//---------------------------------------------------------------------
// <copyright file="NavigationPropertyEmitter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.CodeDom;
using System.Data;
using System.Collections.Generic;
using System.Data.Entity.Design;
using Som=System.Data.EntityModel.SchemaObjectModel;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Data.Entity.Design.SsdlGenerator;
using System.Data.Entity.Design.Common;
namespace System.Data.EntityModel.Emitters
{
/// <summary>
/// Summary description for NavigationPropertyEmitter.
/// </summary>
internal sealed class NavigationPropertyEmitter : PropertyEmitterBase
{
private const string ValuePropertyName = "Value";
/// <summary>
///
/// </summary>
/// <param name="generator"></param>
/// <param name="navigationProperty"></param>
public NavigationPropertyEmitter(ClientApiGenerator generator, NavigationProperty navigationProperty, bool declaringTypeUsesStandardBaseType)
: base(generator, navigationProperty, declaringTypeUsesStandardBaseType)
{
}
/// <summary>
/// Generate the navigation property
/// </summary>
/// <param name="typeDecl">The type to add the property to.</param>
protected override void EmitProperty(CodeTypeDeclaration typeDecl)
{
EmitNavigationProperty(typeDecl);
}
/// <summary>
/// Generate the navigation property specified
/// </summary>
/// <param name="typeDecl">The type to add the property to.</param>
private void EmitNavigationProperty( CodeTypeDeclaration typeDecl )
{
// create a regular property
CodeMemberProperty property = EmitNavigationProperty(Item.ToEndMember, false);
typeDecl.Members.Add(property);
if (Item.ToEndMember.RelationshipMultiplicity != RelationshipMultiplicity.Many)
{
// create a ref property
property = EmitNavigationProperty(Item.ToEndMember, true);
typeDecl.Members.Add(property);
}
}
/// <summary>
/// Generate a navigation property
/// </summary>
/// <param name="target">the other end</param>
/// <param name="referenceProperty">True to emit Reference navigation property</param>
/// <returns>the generated property</returns>
private CodeMemberProperty EmitNavigationProperty(RelationshipEndMember target, bool referenceProperty)
{
CodeTypeReference typeRef = GetReturnType(target, referenceProperty);
// raise the PropertyGenerated event
PropertyGeneratedEventArgs eventArgs = new PropertyGeneratedEventArgs(Item,
null, // no backing field
typeRef);
this.Generator.RaisePropertyGeneratedEvent(eventArgs);
// [System.ComponentModel.Browsable(false)]
// public TargetType TargetName
// public EntityReference<TargetType> TargetName
// or
// public EntityCollection<targetType> TargetNames
CodeMemberProperty property = new CodeMemberProperty();
if (referenceProperty)
{
AttributeEmitter.AddBrowsableAttribute(property);
Generator.AttributeEmitter.EmitGeneratedCodeAttribute(property);
}
else
{
Generator.AttributeEmitter.EmitNavigationPropertyAttributes(Generator, target, property, eventArgs.AdditionalAttributes);
// Only reference navigation properties are currently currently supported with XML serialization
// and thus we should use the XmlIgnore and SoapIgnore attributes on other property types.
AttributeEmitter.AddIgnoreAttributes(property);
}
AttributeEmitter.AddDataMemberAttribute(property);
CommentEmitter.EmitSummaryComments(Item, property.Comments);
property.Name = Item.Name;
if (referenceProperty)
{
property.Name += "Reference";
if (IsNameAlreadyAMemberName(Item.DeclaringType, property.Name, Generator.LanguageAppropriateStringComparer))
{
Generator.AddError(Strings.GeneratedNavigationPropertyNameConflict(Item.Name, Item.DeclaringType.Name, property.Name),
ModelBuilderErrorCode.GeneratedNavigationPropertyNameConflict,
EdmSchemaErrorSeverity.Error, Item.DeclaringType.FullName, property.Name);
}
}
if (eventArgs.ReturnType != null && !eventArgs.ReturnType.Equals(typeRef))
{
property.Type = eventArgs.ReturnType;
}
else
{
property.Type = typeRef;
}
property.Attributes = MemberAttributes.Final;
CodeMethodInvokeExpression getMethod = EmitGetMethod(target);
CodeExpression getReturnExpression;
property.Attributes |= AccessibilityFromGettersAndSetters(Item);
// setup the accessibility of the navigation property setter and getter
MemberAttributes propertyAccessibility = property.Attributes & MemberAttributes.AccessMask;
PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
PropertyEmitter.GetGetterAccessibility(Item), propertyAccessibility, true);
PropertyEmitter.AddGetterSetterFixUp(Generator.FixUps, GetFullyQualifiedPropertyName(property.Name),
PropertyEmitter.GetSetterAccessibility(Item), propertyAccessibility, false);
if (target.RelationshipMultiplicity != RelationshipMultiplicity.Many)
{
// insert user-supplied Set code here, before the assignment
//
List<CodeStatement> additionalSetStatements = eventArgs.AdditionalSetStatements;
if (additionalSetStatements != null && additionalSetStatements.Count > 0)
{
try
{
property.SetStatements.AddRange(additionalSetStatements.ToArray());
}
catch (ArgumentNullException ex)
{
Generator.AddError(Strings.InvalidSetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidSetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
ex);
}
}
CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
if(typeRef != eventArgs.ReturnType)
{
// we need to cast to the actual type
valueRef = new CodeCastExpression(typeRef, valueRef);
}
if (referenceProperty)
{
// get
// return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
getReturnExpression = getMethod;
// set
// if (value != null)
// {
// ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<TTargetEntity>"CSpaceQualifiedRelationshipName", "TargetRoleName", value);
// }
CodeMethodReferenceExpression initReferenceMethod = new CodeMethodReferenceExpression();
initReferenceMethod.MethodName = "InitializeRelatedReference";
initReferenceMethod.TypeArguments.Add(Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target)));
initReferenceMethod.TargetObject = new CodePropertyReferenceExpression(
new CodeCastExpression(TypeReference.IEntityWithRelationshipsTypeBaseClass, ThisRef),
"RelationshipManager");
// relationships aren't backed by types so we won't map the namespace
// or we can't find the relationship again later
string cspaceNamespaceNameQualifiedRelationshipName = target.DeclaringType.FullName;
property.SetStatements.Add(
new CodeConditionStatement(
EmitExpressionDoesNotEqualNull(valueRef),
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
initReferenceMethod, new CodeExpression[] {
new CodePrimitiveExpression(cspaceNamespaceNameQualifiedRelationshipName), new CodePrimitiveExpression(target.Name), valueRef}))));
}
else
{
CodePropertyReferenceExpression valueProperty = new CodePropertyReferenceExpression(getMethod, ValuePropertyName);
// get
// return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value;
getReturnExpression = valueProperty;
// set
// ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName").Value = value;
property.SetStatements.Add(
new CodeAssignStatement(valueProperty, valueRef));
}
}
else
{
// get
// return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TTargetEntity>("CSpaceQualifiedRelationshipName", "TargetRoleName");
getReturnExpression = getMethod;
// set
// if (value != null)
// {
// ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<TTargetEntity>"CSpaceQualifiedRelationshipName", "TargetRoleName", value);
// }
CodeExpression valueRef = new CodePropertySetValueReferenceExpression();
CodeMethodReferenceExpression initCollectionMethod = new CodeMethodReferenceExpression();
initCollectionMethod.MethodName = "InitializeRelatedCollection";
initCollectionMethod.TypeArguments.Add(Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target)));
initCollectionMethod.TargetObject = new CodePropertyReferenceExpression(
new CodeCastExpression(TypeReference.IEntityWithRelationshipsTypeBaseClass, ThisRef),
"RelationshipManager");
// relationships aren't backed by types so we won't map the namespace
// or we can't find the relationship again later
string cspaceNamespaceNameQualifiedRelationshipName = target.DeclaringType.FullName;
property.SetStatements.Add(
new CodeConditionStatement(
EmitExpressionDoesNotEqualNull(valueRef),
new CodeExpressionStatement(
new CodeMethodInvokeExpression(
initCollectionMethod, new CodeExpression[] {
new CodePrimitiveExpression(cspaceNamespaceNameQualifiedRelationshipName), new CodePrimitiveExpression(target.Name), valueRef}))));
}
// if additional Get statements were specified by the event subscriber, insert them now
//
List<CodeStatement> additionalGetStatements = eventArgs.AdditionalGetStatements;
if (additionalGetStatements != null && additionalGetStatements.Count > 0)
{
try
{
property.GetStatements.AddRange(additionalGetStatements.ToArray());
}
catch (ArgumentNullException ex)
{
Generator.AddError(Strings.InvalidGetStatementSuppliedForProperty(Item.Name),
ModelBuilderErrorCode.InvalidGetStatementSuppliedForProperty,
EdmSchemaErrorSeverity.Error,
ex);
}
}
property.GetStatements.Add(new CodeMethodReturnStatement(getReturnExpression));
return property;
}
internal static bool IsNameAlreadyAMemberName(StructuralType type, string generatedPropertyName, StringComparison comparison)
{
foreach (EdmMember member in type.Members)
{
if (member.DeclaringType == type &&
member.Name.Equals(generatedPropertyName, comparison))
{
return true;
}
}
return false;
}
private string GetFullyQualifiedPropertyName(string propertyName)
{
return Item.DeclaringType.FullName + "." + propertyName;
}
/// <summary>
/// Gives the SchemaElement back cast to the most
/// appropriate type
/// </summary>
private new NavigationProperty Item
{
get
{
return base.Item as NavigationProperty;
}
}
/// <summary>
/// Get the return type for the get method, given the target end
/// </summary>
/// <param name="target"></param>
/// <param name="referenceMethod">true if the is the return type for a reference property</param>
/// <returns>the return type for a target</returns>
private CodeTypeReference GetReturnType(RelationshipEndMember target, bool referenceMethod)
{
CodeTypeReference returnType = Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target));
if (referenceMethod)
{
returnType = TypeReference.AdoFrameworkGenericDataClass("EntityReference", returnType);
}
else if (target.RelationshipMultiplicity == RelationshipMultiplicity.Many)
{
returnType = TypeReference.AdoFrameworkGenericDataClass("EntityCollection", returnType);
}
return returnType;
}
private static EntityTypeBase GetEntityType(RelationshipEndMember endMember)
{
Debug.Assert(endMember.TypeUsage.EdmType.BuiltInTypeKind == BuiltInTypeKind.RefType, "not a reference type");
EntityTypeBase type = ((RefType)endMember.TypeUsage.EdmType).ElementType;
return type;
}
/// <summary>
/// Emit the GetRelatedCollection or GetRelatedReference methods
/// </summary>
/// <param name="target">Target end of the relationship</param>
/// <returns>Expression to invoke the appropriate method</returns>
private CodeMethodInvokeExpression EmitGetMethod(RelationshipEndMember target)
{
// ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<TargetType>("CSpaceQualifiedRelationshipName", "TargetRoleName");
// or
// ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<TargetType>("CSpaceQualifiedRelationshipName", "TargetRoleName");
CodeMethodReferenceExpression getMethod = new CodeMethodReferenceExpression();
if (target.RelationshipMultiplicity != RelationshipMultiplicity.Many)
getMethod.MethodName = "GetRelatedReference";
else
getMethod.MethodName = "GetRelatedCollection";
getMethod.TypeArguments.Add(Generator.GetLeastPossibleQualifiedTypeReference(GetEntityType(target)));
getMethod.TargetObject = new CodePropertyReferenceExpression(
new CodeCastExpression(TypeReference.IEntityWithRelationshipsTypeBaseClass, ThisRef),
"RelationshipManager");
// relationships aren't backed by types so we won't map the namespace
// or we can't find the relationship again later
string cspaceNamespaceNameQualifiedRelationshipName = target.DeclaringType.FullName;
return new CodeMethodInvokeExpression(
getMethod, new CodeExpression[] { new CodePrimitiveExpression(cspaceNamespaceNameQualifiedRelationshipName), new CodePrimitiveExpression(target.Name)});
}
}
}
| |
/*
* Copyright (C) 2011 Mitsuaki Kuwahara
* Released under the MIT License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Nana.Delegates;
using System.IO;
using Nana.Syntaxes;
using System.Text.RegularExpressions;
using Nana.Infr;
namespace Nana
{
public class LineEditMode
{
public void On()
{
Init();
this.CW.GoLoop();
SaveDefaultSrc();
}
// ref http://msdn.microsoft.com/ja-jp/library/system.console_members%28v=VS.80%29.aspx
public void Init()
{
this.IsEdit = false;
this.EditLn = "";
this.Row = 1;
this.Col = 1;
if (File.Exists(DefaultSrcPath))
{
this.Lines = new List<string>(File.ReadAllLines(this.DefaultSrcPath, Encoding.UTF8));
this.Row = this.Lines.Count + 1;
}
SetEditMode();
}
public void SaveDefaultSrc()
{
File.WriteAllLines(this.DefaultSrcPath, this.Lines.ToArray());
}
public static readonly ConsoleKeyInfo Space = new ConsoleKeyInfo(' ', ConsoleKey.Spacebar, false, false, false);
public ConsoleWrapper CW;
public Dictionary<ConsoleKey, Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>>> OnReads;
public Dictionary<ConsoleKey, Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>>> OnReadsAlt;
public Func<string> EditPrompt;
public Func<string> CmdPrompt;
public string EditLn;
public int Row;
public int Col;
public List<string> Lines;
public string DefaultSrcPath = "";
public bool IsEdit;
public ConsoleLineEdit LE = new ConsoleLineEdit();
public Commands Cmds;
public LineEditMode()
{
this.DefaultSrcPath = "lem_default.nana";
this.Lines = new List<string>();
this.CW = new ConsoleWrapper();
this.CW.OnRead = OnRead;
Cmds = new Commands(this);
this.EditPrompt = delegate() {
return string.Format("{0:D"
+ Lines.Count.ToString().Length
+ "}>", Row);
//return this.Row.ToString() + ">";
};
this.CmdPrompt = delegate() { return ":"; };
// OnReads
Dictionary<ConsoleKey, Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>>> d;
d = new Dictionary<ConsoleKey, Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>>>();
this.OnReads = d;
d.Add(ConsoleKey.Enter /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit)
{
if (IsEdit) EditEnter(c, inf, quit); else CmdEnter(c, inf, quit);
});
d.Add(ConsoleKey.Escape /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit)
{
c.N().Home();
if (IsEdit) SetCmdMode(); else SetEditMode();
});
d.Add(ConsoleKey.Backspace /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { LE.Bs(); });
d.Add(ConsoleKey.Tab /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { LE.Tab(); });
d.Add(ConsoleKey.LeftArrow /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { LE.L(); });
d.Add(ConsoleKey.RightArrow /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { LE.R(); });
d.Add(ConsoleKey.UpArrow /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { });
d.Add(ConsoleKey.DownArrow /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { });
d = new Dictionary<ConsoleKey, Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>>>();
this.OnReadsAlt = d;
d.Add(ConsoleKey.G /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { SimCmd("go"); });
d.Add(ConsoleKey.L /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { SimCmd("list"); });
d.Add(ConsoleKey.P /**/, delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { SimCmd("parse"); });
}
private void SetEditMode()
{
IsEdit = true;
if (Row < 1) Row = 1;
if (Row > (Lines.Count + 1)) Row = Lines.Count + 1;
LE.Prompt = EditPrompt;
LE.Init();
LE.Ins(EditLn);
}
private void SetCmdMode()
{
EditLn = LE.Line;
IsEdit = false;
LE.Prompt = CmdPrompt;
LE.Init();
}
public void EditEnter(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit)
{
CW.N();
if (Row > Lines.Count)
{
Lines.Add(LE.Line);
}
else
{
Lines.Insert(Row - 1, LE.Line);
}
Row += 1;
LE.Init();
}
public void CmdEnter(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit)
{
CW.N();
string ln = LE.Line;
try
{
string[] args;
args = Regex.Split(ln.Trim(), @"\s+");
if (args.Length == 0) args = new string[] { "" };
Cmds.Execute(args, quit);
if (quit.Value == false) SetEditMode();
}
catch (Exception e)
{
if (e.InnerException != null) e = e.InnerException;
if (e is Error)
{
Error er_ = e as Error;
string s = FormatError(er_);
c.WN(s);
}
else
{
c.WN(e.ToString());
}
LE.Init();
LE.Ins(ln);
}
}
public static string FormatError(Error e)
{
//return string.Format("Path:{0}, Row:{1}, Col:{2}\n{3}:{4}", e.Path, e.Row, e.Col, e.GetType().Name, e.Message);
return string.Format("Path:{0}, Row:{1}, Col:{2}\n{3}:{4}", e.Path, e.Row, e.Col, e.GetType().Name,
e.ToString().Replace(@"C:\Documents and Settings\user1\My Documents\Visual Studio 2005\Projects\Nana\","")
);
}
public void OnRead(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit)
{
if (inf.Modifiers == ConsoleModifiers.Alt && OnReadsAlt.ContainsKey(inf.Key))
{
OnReadsAlt[inf.Key](c, inf, quit);
return;
}
if (OnReads.ContainsKey(inf.Key))
{
OnReads[inf.Key](c, inf, quit);
}
else
{
LE.Ins(inf.KeyChar.ToString());
}
}
public void SimCmd(string args)
{
if (string.IsNullOrEmpty(args)) return;
ConsoleKey key;
ConsoleKeyInfo inf;
Box<bool> quit = new Box<bool>(false);
key = ConsoleKey.Escape;
inf = new ConsoleKeyInfo((char)ConsoleKey.Escape, key, false, false, false);
OnRead(CW, inf, quit);
for (int i = 0; i < args.Length; i++)
{
key = (ConsoleKey)Enum.Parse(typeof(ConsoleKey), args[i].ToString().ToUpper());
inf = new ConsoleKeyInfo(args[i], key, false, false, false);
OnRead(CW, inf, quit);
}
key = ConsoleKey.Enter;
inf = new ConsoleKeyInfo((char)ConsoleKey.Enter, key, false, false, false);
OnRead(CW, inf, quit);
}
static public void List(LineEditMode lem)
{
for (int i = 1; i <= lem.Lines.Count; i++)
{
WriteLineFormat(i, lem);
}
}
static public void WriteLineFormat(int no, LineEditMode lem)
{
if (no <= 0 || lem.Lines.Count < no) return;
lem.CW.WN(string.Format("{0:D"
+ lem.Lines.Count.ToString().Length
+ "}: {1}", no, lem.Lines[no - 1]));
}
}
public interface ILineEdit
{
void Init();
string Line { get; set; }
int Pos { get; }
bool EOL { get; }
bool HOL { get; }
ILineEdit L();
ILineEdit R();
ILineEdit Ins(string value);
ILineEdit Bs();
ILineEdit Tab();
}
public class StringLineEdit : ILineEdit
{
public string TabSpace;
public string _Line;
public string Line { get { return _Line; } set { _Line = value; } }
public int _Pos;
public int Pos { get { return _Pos; } set { _Pos = value; } }
/// <summary>Head Of Line</summary>
public bool HOL { get { return Pos == 1; } }
/// <summary>End Of Line</summary>
public bool EOL { get { return Pos == (Line.Length + 1); } }
public StringLineEdit()
{
TabSpace = " ";
Init();
}
public virtual void Init()
{
Line = "";
Pos = 1;
}
/// <summary>Left</summary>
public virtual ILineEdit L()
{
if (HOL) return this;
Pos -= 1;
return this;
}
/// <summary>Right</summary>
public virtual ILineEdit R()
{
if (EOL) return this;
Pos += 1;
return this;
}
/// <summary>Insert</summary>
public virtual ILineEdit Ins(string value)
{
value = value ?? "";
if (EOL)
{
Line += value;
}
else
{
Line.Insert(Pos - 1, value);
}
Pos += value.Length;
return this;
}
/// <summary>Backspace</summary>
public virtual ILineEdit Bs()
{
if (HOL) return this;
Line = Line.Remove(Pos - 2);
Pos -= 1;
return this;
}
/// <summary>Tab</summary>
public virtual ILineEdit Tab()
{
string tab = GetTab();
Ins(tab);
return this;
}
public string GetTab()
{
int tabSize = TabSpace.Length;
int d = tabSize - ((Pos - 1) % tabSize);
string tab = TabSpace.Substring(0, d);
return tab;
}
}
public class ConsoleLineEdit : ILineEdit
{
StringLineEdit SLE;
public string Line { get { return SLE.Line; } set { SLE.Line = value; } }
public int Pos { get { return SLE.Pos; } }
public bool HOL { get { return SLE.HOL; } }
public bool EOL { get { return SLE.EOL; } }
public Func<string> Prompt = delegate() { return ""; };
public ConsoleLineEdit()
{
SLE = new StringLineEdit();
Init();
}
public void Init()
{
SLE.Init();
Console.Write(Prompt());
}
public virtual ILineEdit L()
{
if (SLE.HOL) return this;
Console.CursorLeft -= 1;
SLE.L();
return this;
}
public virtual ILineEdit R()
{
if (SLE.EOL) return this;
Console.CursorLeft += 1;
SLE.R();
return this;
}
public virtual ILineEdit Ins(string value)
{
Console.Write(value);
SLE.Ins(value);
return this;
}
/// <summary>Backspace</summary>
public virtual ILineEdit Bs()
{
if (SLE.HOL) return this;
Console.CursorLeft -= 1;
Console.Write(" ");
Console.CursorLeft -= 1;
SLE.Bs();
return this;
}
/// <summary>Tab</summary>
public virtual ILineEdit Tab()
{
Ins(SLE.GetTab());
return this;
}
}
public class ConsoleWrapper
{
public bool Suppress = true;
public Action<ConsoleWrapper, ConsoleKeyInfo, Box<bool>> OnRead
= delegate(ConsoleWrapper c, ConsoleKeyInfo inf, Box<bool> quit) { };
public void GoLoop()
{
int left, top;
ConsoleKeyInfo inf;
Box<bool> quit = new Box<bool>(false);
while (quit.Value == false)
{
left = Console.CursorLeft;
top = Console.CursorTop;
inf = Console.ReadKey(Suppress);
if (Console.CursorLeft != left) Console.CursorLeft = left;
if (Console.CursorTop != top) Console.CursorTop = top;
OnRead(this, inf, quit);
}
}
public ConsoleWrapper Home()
{
Console.CursorLeft = 0;
return this;
}
public ConsoleWrapper D()
{
Console.CursorTop = Console.CursorTop + 1;
return this;
}
public void Ins(string value)
{
Console.Write(value);
}
public ConsoleWrapper N()
{
Console.WriteLine();
return this;
}
public ConsoleWrapper W(char value)
{
Console.Write(value);
return this;
}
public ConsoleWrapper W(string value)
{
Console.Write(value);
return this;
}
public ConsoleWrapper WN(string value)
{
W(value); N();
return this;
}
public bool IsOnLeft(int offset)
{
return Console.CursorLeft <= (0 + offset);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
public partial class HttpClientHandler_ServerCertificates_Test : RemoteExecutorTestBase
{
// TODO: https://github.com/dotnet/corefx/issues/7812
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
private static bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
(BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
using (var handler = new HttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.True(handler.CheckCertificateRevocationList);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultValues_NotUapPlatform()
{
using (var handler = new HttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
if (ManagedHandlerTestHelpers.IsEnabled)
{
return; // TODO #21452: SSL proxy tunneling not yet implemented in ManagedHandler
}
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
var handler = new HttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
await TestHelper.WhenAllCompletedOrAnyFailed(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
X509ChainStatusFlags flags = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (cur, status) => cur | status.Status);
Assert.True(errors == SslPolicyErrors.None, $"Expected {SslPolicyErrors.None}, got {errors} with chain status {flags}");
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
// UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
// the getter always returns true. So, for this next Assert, it is better to get the property
// value back from the handler instead of using the parameter value of the test.
Assert.Equal(
handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[ActiveIssue(21904, ~TargetFrameworkMonikers.Uap)]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(BackendSupportsCustomCertificateHandling))]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsInnerException)}()");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
Assert.Same(e, ex.InnerException);
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (var client = new HttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(ClientSupportsDHECipherSuites))]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (!ShouldSuppressRevocationException)
throw;
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
return;
}
var handler = new HttpClientHandler() { CheckCertificateRevocationList = true };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, SslPolicyErrors expectedErrors)
{
if (BackendDoesNotSupportCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
return;
}
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
if (!ManagedHandlerTestHelpers.IsEnabled)
{
// TODO #21452: This test is failing with the managed handler on the exact value of the managed errors,
// e.g. reporting "RemoteCertificateNameMismatch, RemoteCertificateChainErrors" when we only expect
// "RemoteCertificateChainErrors"
Assert.Equal(expectedErrors, errors);
}
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
if (PlatformDetection.IsUap)
{
// UAP HTTP stack caches connections per-process. This causes interference when these tests run in
// the same process as the other tests. Each test needs to be isolated to its own process.
// See dicussion: https://github.com/dotnet/corefx/issues/21945
RemoteInvoke((remoteUrl, remoteExpectedErrors) =>
{
UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
remoteUrl,
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
return SuccessExitCode;
}, url, expectedErrors.ToString()).Dispose();
}
else
{
await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, expectedErrors);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
return;
}
using (var client = new HttpClient(new HttpClientHandler() { ServerCertificateCustomValidationCallback = delegate { return true; } }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for the managed handler
{
return;
}
using (var client = new HttpClient(new HttpClientHandler() { CheckCertificateRevocationList = true }))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (var client = new HttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
if (PlatformDetection.IsUap)
{
// UAP currently doesn't expose channel binding information.
Assert.Null(channelBinding);
}
else
{
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
public sealed class InteractiveConsole : ConsoleBase
{
#region FB.ActivateApp() example
private void CallFBActivateApp()
{
FB.ActivateApp();
Callback(new FBResult("Check Insights section for your app in the App Dashboard under \"Mobile App Installs\""));
}
#endregion
#region FB.AppRequest() Friend Selector
public string FriendSelectorTitle = "";
public string FriendSelectorMessage = "Derp";
public string FriendSelectorFilters = "[\"app_users\"]";
public string FriendSelectorData = "{}";
public string FriendSelectorExcludeIds = "";
public string FriendSelectorMax = "";
private void CallAppRequestAsFriendSelector()
{
// If there's a Max Recipients specified, include it
int? maxRecipients = null;
if (FriendSelectorMax != "")
{
try
{
maxRecipients = Int32.Parse(FriendSelectorMax);
}
catch (Exception e)
{
status = e.Message;
}
}
// include the exclude ids
string[] excludeIds = (FriendSelectorExcludeIds == "") ? null : FriendSelectorExcludeIds.Split(',');
List<object> FriendSelectorFiltersArr = null;
if (!String.IsNullOrEmpty(FriendSelectorFilters))
{
try
{
FriendSelectorFiltersArr = Facebook.MiniJSON.Json.Deserialize(FriendSelectorFilters) as List<object>;
}
catch
{
throw new Exception("JSON Parse error");
}
}
FB.AppRequest(
FriendSelectorMessage,
null,
FriendSelectorFiltersArr,
excludeIds,
maxRecipients,
FriendSelectorData,
FriendSelectorTitle,
Callback
);
}
#endregion
#region FB.AppRequest() Direct Request
public string DirectRequestTitle = "";
public string DirectRequestMessage = "Herp";
private string DirectRequestTo = "";
private void CallAppRequestAsDirectRequest()
{
if (DirectRequestTo == "")
{
throw new ArgumentException("\"To Comma Ids\" must be specificed", "to");
}
FB.AppRequest(
DirectRequestMessage,
DirectRequestTo.Split(','),
null,
null,
null,
"",
DirectRequestTitle,
Callback
);
}
#endregion
#region FB.Feed() example
public string FeedToId = "";
public string FeedLink = "";
public string FeedLinkName = "";
public string FeedLinkCaption = "";
public string FeedLinkDescription = "";
public string FeedPicture = "";
public string FeedMediaSource = "";
public string FeedActionName = "";
public string FeedActionLink = "";
public string FeedReference = "";
public bool IncludeFeedProperties = false;
private Dictionary<string, string[]> FeedProperties = new Dictionary<string, string[]>();
private void CallFBFeed()
{
Dictionary<string, string[]> feedProperties = null;
if (IncludeFeedProperties)
{
feedProperties = FeedProperties;
}
FB.Feed(
toId: FeedToId,
link: FeedLink,
linkName: FeedLinkName,
linkCaption: FeedLinkCaption,
linkDescription: FeedLinkDescription,
picture: FeedPicture,
mediaSource: FeedMediaSource,
actionName: FeedActionName,
actionLink: FeedActionLink,
reference: FeedReference,
properties: feedProperties,
callback: Callback
);
}
#endregion
#region FB.Canvas.Pay() example
public string PayProduct = "";
private void CallFBPay()
{
FB.Canvas.Pay(PayProduct);
}
#endregion
#region FB.API() example
public string ApiQuery = "";
private void CallFBAPI()
{
FB.API(ApiQuery, Facebook.HttpMethod.GET, Callback);
}
#endregion
#region FB.GetDeepLink() example
private void CallFBGetDeepLink()
{
FB.GetDeepLink(Callback);
}
#endregion
#region FB.AppEvent.LogEvent example
public float PlayerLevel = 1.0f;
public void CallAppEventLogEvent()
{
var parameters = new Dictionary<string, object>();
parameters[Facebook.FBAppEventParameterName.Level] = "Player Level";
FB.AppEvents.LogEvent(Facebook.FBAppEventName.AchievedLevel, PlayerLevel, parameters);
PlayerLevel++;
}
#endregion
#region FB.Canvas.SetResolution example
public string Width = "800";
public string Height = "600";
public bool CenterHorizontal = true;
public bool CenterVertical = false;
public string Top = "10";
public string Left = "10";
public void CallCanvasSetResolution()
{
int width;
if (!Int32.TryParse(Width, out width))
{
width = 800;
}
int height;
if (!Int32.TryParse(Height, out height))
{
height = 600;
}
float top;
if (!float.TryParse(Top, out top))
{
top = 0.0f;
}
float left;
if (!float.TryParse(Left, out left))
{
left = 0.0f;
}
if (CenterHorizontal && CenterVertical)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.CenterVertical(), FBScreen.CenterHorizontal());
}
else if (CenterHorizontal)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.Top(top), FBScreen.CenterHorizontal());
}
else if (CenterVertical)
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.CenterVertical(), FBScreen.Left(left));
}
else
{
FB.Canvas.SetResolution(width, height, false, 0, FBScreen.Top(top), FBScreen.Left(left));
}
}
#endregion
#region GUI
override protected void Awake()
{
base.Awake();
FeedProperties.Add("key1", new[] { "valueString1" });
FeedProperties.Add("key2", new[] { "valueString2", "http://www.facebook.com" });
}
void OnGUI()
{
AddCommonHeader ();
#if UNITY_IOS || UNITY_ANDROID
if (Button("Publish Install"))
{
CallFBActivateApp();
status = "Install Published";
}
#endif
GUI.enabled = FB.IsLoggedIn;
GUILayout.Space(10);
LabelAndTextField("Title (optional): ", ref FriendSelectorTitle);
LabelAndTextField("Message: ", ref FriendSelectorMessage);
LabelAndTextField("Exclude Ids (optional): ", ref FriendSelectorExcludeIds);
LabelAndTextField("Filters (optional): ", ref FriendSelectorFilters);
LabelAndTextField("Max Recipients (optional): ", ref FriendSelectorMax);
LabelAndTextField("Data (optional): ", ref FriendSelectorData);
if (Button("Open Friend Selector"))
{
try
{
CallAppRequestAsFriendSelector();
status = "Friend Selector called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
LabelAndTextField("Title (optional): ", ref DirectRequestTitle);
LabelAndTextField("Message: ", ref DirectRequestMessage);
LabelAndTextField("To Comma Ids: ", ref DirectRequestTo);
if (Button("Open Direct Request"))
{
try
{
CallAppRequestAsDirectRequest();
status = "Direct Request called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
LabelAndTextField("To Id (optional): ", ref FeedToId);
LabelAndTextField("Link (optional): ", ref FeedLink);
LabelAndTextField("Link Name (optional): ", ref FeedLinkName);
LabelAndTextField("Link Desc (optional): ", ref FeedLinkDescription);
LabelAndTextField("Link Caption (optional): ", ref FeedLinkCaption);
LabelAndTextField("Picture (optional): ", ref FeedPicture);
LabelAndTextField("Media Source (optional): ", ref FeedMediaSource);
LabelAndTextField("Action Name (optional): ", ref FeedActionName);
LabelAndTextField("Action Link (optional): ", ref FeedActionLink);
LabelAndTextField("Reference (optional): ", ref FeedReference);
GUILayout.BeginHorizontal();
GUILayout.Label("Properties (optional)", GUILayout.Width(150));
IncludeFeedProperties = GUILayout.Toggle(IncludeFeedProperties, "Include");
GUILayout.EndHorizontal();
if (Button("Open Feed Dialog"))
{
try
{
CallFBFeed();
status = "Feed dialog called";
}
catch (Exception e)
{
status = e.Message;
}
}
GUILayout.Space(10);
#if UNITY_WEBPLAYER
LabelAndTextField("Product: ", ref PayProduct);
if (Button("Call Pay"))
{
CallFBPay();
}
GUILayout.Space(10);
#endif
LabelAndTextField("API: ", ref ApiQuery);
if (Button("Call API"))
{
status = "API called";
CallFBAPI();
}
GUILayout.Space(10);
if (Button("Take & upload screenshot"))
{
status = "Take screenshot";
StartCoroutine(TakeScreenshot());
}
if (Button("Get Deep Link"))
{
CallFBGetDeepLink();
}
#if UNITY_IOS || UNITY_ANDROID
if (Button("Log FB App Event"))
{
status = "Logged FB.AppEvent";
CallAppEventLogEvent();
}
#endif
#if UNITY_WEBPLAYER
GUILayout.Space(10);
LabelAndTextField("Game Width: ", ref Width);
LabelAndTextField("Game Height: ", ref Height);
GUILayout.BeginHorizontal();
GUILayout.Label("Center Game:", GUILayout.Width(150));
CenterVertical = GUILayout.Toggle(CenterVertical, "Vertically");
CenterHorizontal = GUILayout.Toggle(CenterHorizontal, "Horizontally");
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
LabelAndTextField("or set Padding Top: ", ref Top);
LabelAndTextField("set Padding Left: ", ref Left);
GUILayout.EndHorizontal();
if (Button("Set Resolution"))
{
status = "Set to new Resolution";
CallCanvasSetResolution();
}
#endif
GUILayout.Space(10);
GUILayout.EndVertical();
GUILayout.EndScrollView();
if (IsHorizontalLayout())
{
GUILayout.EndVertical();
}
GUI.enabled = true;
AddCommonFooter();
if (IsHorizontalLayout())
{
GUILayout.EndHorizontal();
}
}
private IEnumerator TakeScreenshot()
{
yield return new WaitForEndOfFrame();
var width = Screen.width;
var height = Screen.height;
var tex = new Texture2D(width, height, TextureFormat.RGB24, false);
// Read screen contents into the texture
tex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
tex.Apply();
byte[] screenshot = tex.EncodeToPNG();
var wwwForm = new WWWForm();
wwwForm.AddBinaryData("image", screenshot, "InteractiveConsole.png");
wwwForm.AddField("message", "herp derp. I did a thing! Did I do this right?");
FB.API("me/photos", Facebook.HttpMethod.POST, Callback, wwwForm);
}
#endregion
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#pragma warning disable 0162
using System.Diagnostics;
namespace TrueSync.Physics2D
{
// Gear Joint:
// C0 = (coordinate1 + ratio * coordinate2)_initial
// C = (coordinate1 + ratio * coordinate2) - C0 = 0
// J = [J1 ratio * J2]
// K = J * invM * JT
// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T
//
// Revolute:
// coordinate = rotation
// Cdot = angularVelocity
// J = [0 0 1]
// K = J * invM * JT = invI
//
// Prismatic:
// coordinate = dot(p - pg, ug)
// Cdot = dot(v + cross(w, r), ug)
// J = [ug cross(r, ug)]
// K = J * invM * JT = invMass + invI * cross(r, ug)^2
/// <summary>
/// A gear joint is used to connect two joints together.
/// Either joint can be a revolute or prismatic joint.
/// You specify a gear ratio to bind the motions together:
/// <![CDATA[coordinate1 + ratio * coordinate2 = ant]]>
/// The ratio can be negative or positive. If one joint is a revolute joint
/// and the other joint is a prismatic joint, then the ratio will have units
/// of length or units of 1/length.
///
/// Warning: You have to manually destroy the gear joint if jointA or jointB is destroyed.
/// </summary>
public class GearJoint : Joint2D
{
private JointType _typeA;
private JointType _typeB;
private Body _bodyA;
private Body _bodyB;
private Body _bodyC;
private Body _bodyD;
// Solver shared
private TSVector2 _localAnchorA;
private TSVector2 _localAnchorB;
private TSVector2 _localAnchorC;
private TSVector2 _localAnchorD;
private TSVector2 _localAxisC;
private TSVector2 _localAxisD;
private FP _referenceAngleA;
private FP _referenceAngleB;
private FP _constant;
private FP _ratio;
private FP _impulse;
// Solver temp
private int _indexA, _indexB, _indexC, _indexD;
private TSVector2 _lcA, _lcB, _lcC, _lcD;
private FP _mA, _mB, _mC, _mD;
private FP _iA, _iB, _iC, _iD;
private TSVector2 _JvAC, _JvBD;
private FP _JwA, _JwB, _JwC, _JwD;
private FP _mass;
/// <summary>
/// Requires two existing revolute or prismatic joints (any combination will work).
/// The provided joints must attach a dynamic body to a static body.
/// </summary>
/// <param name="jointA">The first joint.</param>
/// <param name="jointB">The second joint.</param>
/// <param name="ratio">The ratio.</param>
/// <param name="bodyA">The first body</param>
/// <param name="bodyB">The second body</param>
// TS - public GearJoint(Body bodyA, Body bodyB, Joint jointA, Joint jointB, FP ratio = 1f)
public GearJoint(Body bodyA, Body bodyB, Joint2D jointA, Joint2D jointB, FP ratio)
{
JointType = JointType.Gear;
BodyA = bodyA;
BodyB = bodyB;
JointA = jointA;
JointB = jointB;
Ratio = ratio;
_typeA = jointA.JointType;
_typeB = jointB.JointType;
Debug.Assert(_typeA == JointType.Revolute || _typeA == JointType.Prismatic || _typeA == JointType.FixedRevolute || _typeA == JointType.FixedPrismatic);
Debug.Assert(_typeB == JointType.Revolute || _typeB == JointType.Prismatic || _typeB == JointType.FixedRevolute || _typeB == JointType.FixedPrismatic);
FP coordinateA, coordinateB;
// TODO_ERIN there might be some problem with the joint edges in b2Joint.
_bodyC = JointA.BodyA;
_bodyA = JointA.BodyB;
// Get geometry of joint1
Transform xfA = _bodyA._xf;
FP aA = _bodyA._sweep.A;
Transform xfC = _bodyC._xf;
FP aC = _bodyC._sweep.A;
if (_typeA == JointType.Revolute)
{
RevoluteJoint revolute = (RevoluteJoint)jointA;
_localAnchorC = revolute.LocalAnchorA;
_localAnchorA = revolute.LocalAnchorB;
_referenceAngleA = revolute.ReferenceAngle;
_localAxisC = TSVector2.zero;
coordinateA = aA - aC - _referenceAngleA;
}
else
{
PrismaticJoint prismatic = (PrismaticJoint)jointA;
_localAnchorC = prismatic.LocalAnchorA;
_localAnchorA = prismatic.LocalAnchorB;
_referenceAngleA = prismatic.ReferenceAngle;
_localAxisC = prismatic.LocalXAxis;
TSVector2 pC = _localAnchorC;
TSVector2 pA = MathUtils.MulT(xfC.q, MathUtils.Mul(xfA.q, _localAnchorA) + (xfA.p - xfC.p));
coordinateA = TSVector2.Dot(pA - pC, _localAxisC);
}
_bodyD = JointB.BodyA;
_bodyB = JointB.BodyB;
// Get geometry of joint2
Transform xfB = _bodyB._xf;
FP aB = _bodyB._sweep.A;
Transform xfD = _bodyD._xf;
FP aD = _bodyD._sweep.A;
if (_typeB == JointType.Revolute)
{
RevoluteJoint revolute = (RevoluteJoint)jointB;
_localAnchorD = revolute.LocalAnchorA;
_localAnchorB = revolute.LocalAnchorB;
_referenceAngleB = revolute.ReferenceAngle;
_localAxisD = TSVector2.zero;
coordinateB = aB - aD - _referenceAngleB;
}
else
{
PrismaticJoint prismatic = (PrismaticJoint)jointB;
_localAnchorD = prismatic.LocalAnchorA;
_localAnchorB = prismatic.LocalAnchorB;
_referenceAngleB = prismatic.ReferenceAngle;
_localAxisD = prismatic.LocalXAxis;
TSVector2 pD = _localAnchorD;
TSVector2 pB = MathUtils.MulT(xfD.q, MathUtils.Mul(xfB.q, _localAnchorB) + (xfB.p - xfD.p));
coordinateB = TSVector2.Dot(pB - pD, _localAxisD);
}
_ratio = ratio;
_constant = coordinateA + _ratio * coordinateB;
_impulse = 0.0f;
}
public override TSVector2 WorldAnchorA
{
get { return _bodyA.GetWorldPoint(_localAnchorA); }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
public override TSVector2 WorldAnchorB
{
get { return _bodyB.GetWorldPoint(_localAnchorB); }
set { Debug.Assert(false, "You can't set the world anchor on this joint type."); }
}
/// <summary>
/// The gear ratio.
/// </summary>
public FP Ratio
{
get { return _ratio; }
set
{
Debug.Assert(MathUtils.IsValid(value));
_ratio = value;
}
}
/// <summary>
/// The first revolute/prismatic joint attached to the gear joint.
/// </summary>
public Joint2D JointA { get; private set; }
/// <summary>
/// The second revolute/prismatic joint attached to the gear joint.
/// </summary>
public Joint2D JointB { get; private set; }
public override TSVector2 GetReactionForce(FP invDt)
{
TSVector2 P = _impulse * _JvAC;
return invDt * P;
}
public override FP GetReactionTorque(FP invDt)
{
FP L = _impulse * _JwA;
return invDt * L;
}
internal override void InitVelocityConstraints(ref SolverData data)
{
_indexA = _bodyA.IslandIndex;
_indexB = _bodyB.IslandIndex;
_indexC = _bodyC.IslandIndex;
_indexD = _bodyD.IslandIndex;
_lcA = _bodyA._sweep.LocalCenter;
_lcB = _bodyB._sweep.LocalCenter;
_lcC = _bodyC._sweep.LocalCenter;
_lcD = _bodyD._sweep.LocalCenter;
_mA = _bodyA._invMass;
_mB = _bodyB._invMass;
_mC = _bodyC._invMass;
_mD = _bodyD._invMass;
_iA = _bodyA._invI;
_iB = _bodyB._invI;
_iC = _bodyC._invI;
_iD = _bodyD._invI;
FP aA = data.positions[_indexA].a;
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
FP aB = data.positions[_indexB].a;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
FP aC = data.positions[_indexC].a;
TSVector2 vC = data.velocities[_indexC].v;
FP wC = data.velocities[_indexC].w;
FP aD = data.positions[_indexD].a;
TSVector2 vD = data.velocities[_indexD].v;
FP wD = data.velocities[_indexD].w;
Rot qA = new Rot(aA), qB = new Rot(aB), qC = new Rot(aC), qD = new Rot(aD);
_mass = 0.0f;
if (_typeA == JointType.Revolute)
{
_JvAC = TSVector2.zero;
_JwA = 1.0f;
_JwC = 1.0f;
_mass += _iA + _iC;
}
else
{
TSVector2 u = MathUtils.Mul(qC, _localAxisC);
TSVector2 rC = MathUtils.Mul(qC, _localAnchorC - _lcC);
TSVector2 rA = MathUtils.Mul(qA, _localAnchorA - _lcA);
_JvAC = u;
_JwC = MathUtils.Cross(rC, u);
_JwA = MathUtils.Cross(rA, u);
_mass += _mC + _mA + _iC * _JwC * _JwC + _iA * _JwA * _JwA;
}
if (_typeB == JointType.Revolute)
{
_JvBD = TSVector2.zero;
_JwB = _ratio;
_JwD = _ratio;
_mass += _ratio * _ratio * (_iB + _iD);
}
else
{
TSVector2 u = MathUtils.Mul(qD, _localAxisD);
TSVector2 rD = MathUtils.Mul(qD, _localAnchorD - _lcD);
TSVector2 rB = MathUtils.Mul(qB, _localAnchorB - _lcB);
_JvBD = _ratio * u;
_JwD = _ratio * MathUtils.Cross(rD, u);
_JwB = _ratio * MathUtils.Cross(rB, u);
_mass += _ratio * _ratio * (_mD + _mB) + _iD * _JwD * _JwD + _iB * _JwB * _JwB;
}
// Compute effective mass.
_mass = _mass > 0.0f ? 1.0f / _mass : 0.0f;
if (Settings.EnableWarmstarting)
{
vA += (_mA * _impulse) * _JvAC;
wA += _iA * _impulse * _JwA;
vB += (_mB * _impulse) * _JvBD;
wB += _iB * _impulse * _JwB;
vC -= (_mC * _impulse) * _JvAC;
wC -= _iC * _impulse * _JwC;
vD -= (_mD * _impulse) * _JvBD;
wD -= _iD * _impulse * _JwD;
}
else
{
_impulse = 0.0f;
}
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
data.velocities[_indexC].v = vC;
data.velocities[_indexC].w = wC;
data.velocities[_indexD].v = vD;
data.velocities[_indexD].w = wD;
}
internal override void SolveVelocityConstraints(ref SolverData data)
{
TSVector2 vA = data.velocities[_indexA].v;
FP wA = data.velocities[_indexA].w;
TSVector2 vB = data.velocities[_indexB].v;
FP wB = data.velocities[_indexB].w;
TSVector2 vC = data.velocities[_indexC].v;
FP wC = data.velocities[_indexC].w;
TSVector2 vD = data.velocities[_indexD].v;
FP wD = data.velocities[_indexD].w;
FP Cdot = TSVector2.Dot(_JvAC, vA - vC) + TSVector2.Dot(_JvBD, vB - vD);
Cdot += (_JwA * wA - _JwC * wC) + (_JwB * wB - _JwD * wD);
FP impulse = -_mass * Cdot;
_impulse += impulse;
vA += (_mA * impulse) * _JvAC;
wA += _iA * impulse * _JwA;
vB += (_mB * impulse) * _JvBD;
wB += _iB * impulse * _JwB;
vC -= (_mC * impulse) * _JvAC;
wC -= _iC * impulse * _JwC;
vD -= (_mD * impulse) * _JvBD;
wD -= _iD * impulse * _JwD;
data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
data.velocities[_indexC].v = vC;
data.velocities[_indexC].w = wC;
data.velocities[_indexD].v = vD;
data.velocities[_indexD].w = wD;
}
internal override bool SolvePositionConstraints(ref SolverData data)
{
TSVector2 cA = data.positions[_indexA].c;
FP aA = data.positions[_indexA].a;
TSVector2 cB = data.positions[_indexB].c;
FP aB = data.positions[_indexB].a;
TSVector2 cC = data.positions[_indexC].c;
FP aC = data.positions[_indexC].a;
TSVector2 cD = data.positions[_indexD].c;
FP aD = data.positions[_indexD].a;
Rot qA = new Rot(aA), qB = new Rot(aB), qC = new Rot(aC), qD = new Rot(aD);
FP linearError = 0.0f;
FP coordinateA, coordinateB;
TSVector2 JvAC, JvBD;
FP JwA, JwB, JwC, JwD;
FP mass = 0.0f;
if (_typeA == JointType.Revolute)
{
JvAC = TSVector2.zero;
JwA = 1.0f;
JwC = 1.0f;
mass += _iA + _iC;
coordinateA = aA - aC - _referenceAngleA;
}
else
{
TSVector2 u = MathUtils.Mul(qC, _localAxisC);
TSVector2 rC = MathUtils.Mul(qC, _localAnchorC - _lcC);
TSVector2 rA = MathUtils.Mul(qA, _localAnchorA - _lcA);
JvAC = u;
JwC = MathUtils.Cross(rC, u);
JwA = MathUtils.Cross(rA, u);
mass += _mC + _mA + _iC * JwC * JwC + _iA * JwA * JwA;
TSVector2 pC = _localAnchorC - _lcC;
TSVector2 pA = MathUtils.MulT(qC, rA + (cA - cC));
coordinateA = TSVector2.Dot(pA - pC, _localAxisC);
}
if (_typeB == JointType.Revolute)
{
JvBD = TSVector2.zero;
JwB = _ratio;
JwD = _ratio;
mass += _ratio * _ratio * (_iB + _iD);
coordinateB = aB - aD - _referenceAngleB;
}
else
{
TSVector2 u = MathUtils.Mul(qD, _localAxisD);
TSVector2 rD = MathUtils.Mul(qD, _localAnchorD - _lcD);
TSVector2 rB = MathUtils.Mul(qB, _localAnchorB - _lcB);
JvBD = _ratio * u;
JwD = _ratio * MathUtils.Cross(rD, u);
JwB = _ratio * MathUtils.Cross(rB, u);
mass += _ratio * _ratio * (_mD + _mB) + _iD * JwD * JwD + _iB * JwB * JwB;
TSVector2 pD = _localAnchorD - _lcD;
TSVector2 pB = MathUtils.MulT(qD, rB + (cB - cD));
coordinateB = TSVector2.Dot(pB - pD, _localAxisD);
}
FP C = (coordinateA + _ratio * coordinateB) - _constant;
FP impulse = 0.0f;
if (mass > 0.0f)
{
impulse = -C / mass;
}
cA += _mA * impulse * JvAC;
aA += _iA * impulse * JwA;
cB += _mB * impulse * JvBD;
aB += _iB * impulse * JwB;
cC -= _mC * impulse * JvAC;
aC -= _iC * impulse * JwC;
cD -= _mD * impulse * JvBD;
aD -= _iD * impulse * JwD;
data.positions[_indexA].c = cA;
data.positions[_indexA].a = aA;
data.positions[_indexB].c = cB;
data.positions[_indexB].a = aB;
data.positions[_indexC].c = cC;
data.positions[_indexC].a = aC;
data.positions[_indexD].c = cD;
data.positions[_indexD].a = aD;
// TODO_ERIN not implemented
return linearError < Settings.LinearSlop;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Orleans.SqlUtils;
using Tester.RelationalUtilities;
namespace UnitTests.General
{
public abstract class RelationalStorageForTesting
{
private static readonly Dictionary<string, Func<string, RelationalStorageForTesting>> instanceFactory =
new Dictionary<string, Func<string, RelationalStorageForTesting>>
{
{AdoNetInvariants.InvariantNameSqlServer, cs => new SqlServerStorageForTesting(cs)},
{AdoNetInvariants.InvariantNameMySql, cs => new MySqlStorageForTesting(cs)},
{AdoNetInvariants.InvariantNamePostgreSql, cs => new PostgreSqlStorageForTesting(cs)}
};
public IRelationalStorage Storage { get; private set; }
public string CurrentConnectionString
{
get { return Storage.ConnectionString; }
}
/// <summary>
/// Default connection string for testing
/// </summary>
public abstract string DefaultConnectionString { get; }
/// <summary>
/// A delayed query that is then cancelled in a test to see if cancellation works.
/// </summary>
public abstract string CancellationTestQuery { get; }
public abstract string CreateStreamTestTable { get; }
public virtual string DeleteStreamTestTable { get { return "DELETE StreamingTest;"; } }
public virtual string StreamTestSelect { get { return "SELECT Id, StreamData FROM StreamingTest WHERE Id = @streamId;"; } }
public virtual string StreamTestInsert { get { return "INSERT INTO StreamingTest(Id, StreamData) VALUES(@id, @streamData);"; } }
/// <summary>
/// The script that creates Orleans schema in the database, usually CreateOrleansTables_xxxx.sql
/// </summary>
protected abstract string SetupSqlScriptFileName { get; }
/// <summary>
/// A query template to create a database with a given name.
/// </summary>
protected abstract string CreateDatabaseTemplate { get; }
/// <summary>
/// A query template to drop a database with a given name.
/// </summary>
protected abstract string DropDatabaseTemplate { get; }
/// <summary>
/// A query template if a database with a given name exists.
/// </summary>
protected abstract string ExistsDatabaseTemplate { get; }
/// <summary>
/// Converts the given script into batches to execute sequentially
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="databaseName">the name of the database</param>
protected abstract IEnumerable<string> ConvertToExecutableBatches(string setupScript, string databaseName);
public static async Task<RelationalStorageForTesting> SetupInstance(string invariantName, string testDatabaseName, string connectionString = null)
{
if (string.IsNullOrWhiteSpace(invariantName))
{
throw new ArgumentException("The name of invariant must contain characters", "invariantName");
}
if (string.IsNullOrWhiteSpace(testDatabaseName))
{
throw new ArgumentException("database string must contain characters", "testDatabaseName");
}
Console.WriteLine("Initializing relational databases...");
RelationalStorageForTesting testStorage;
if(connectionString == null)
{
testStorage = CreateTestInstance(invariantName);
}
else
{
testStorage = CreateTestInstance(invariantName, connectionString);
}
Console.WriteLine("Dropping and recreating database '{0}' with connectionstring '{1}'", testDatabaseName, connectionString ?? testStorage.DefaultConnectionString);
if (await testStorage.ExistsDatabaseAsync(testDatabaseName))
{
await testStorage.DropDatabaseAsync(testDatabaseName);
}
await testStorage.CreateDatabaseAsync(testDatabaseName);
//The old storage instance has the previous connection string, time have a new handle with a new connection string...
testStorage = testStorage.CopyInstance(testDatabaseName);
Console.WriteLine("Creating database tables...");
var setupScript = File.ReadAllText(testStorage.SetupSqlScriptFileName);
await testStorage.ExecuteSetupScript(setupScript, testDatabaseName);
Console.WriteLine("Initializing relational databases done.");
return testStorage;
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName, string connectionString)
{
return instanceFactory[invariantName](connectionString);
}
private static RelationalStorageForTesting CreateTestInstance(string invariantName)
{
return CreateTestInstance(invariantName, CreateTestInstance(invariantName, "notempty").DefaultConnectionString);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="invariantName"></param>
/// <param name="connectionString"></param>
protected RelationalStorageForTesting(string invariantName, string connectionString)
{
Storage = RelationalStorage.CreateInstance(invariantName, connectionString);
}
/// <summary>
/// Executes the given script in a test context.
/// </summary>
/// <param name="setupScript">the script. usually CreateOrleansTables_xxxx.sql</param>
/// <param name="dataBaseName">the target database to be populated</param>
/// <returns></returns>
private async Task ExecuteSetupScript(string setupScript, string dataBaseName)
{
var splitScripts = ConvertToExecutableBatches(setupScript, dataBaseName);
foreach (var script in splitScripts)
{
var res1 = await Storage.ExecuteAsync(script);
}
}
/// <summary>
/// Checks the existence of a database using the given <see paramref="storage"/> storage object.
/// </summary>
/// <param name="databaseName">The name of the database existence of which to check.</param>
/// <returns><em>TRUE</em> if the given database exists. <em>FALSE</em> otherwise.</returns>
private async Task<bool> ExistsDatabaseAsync(string databaseName)
{
var ret = await Storage.ReadAsync(string.Format(ExistsDatabaseTemplate, databaseName), command =>
{ }, (selector, resultSetCount, cancellationToken) => { return Task.FromResult(selector.GetBoolean(0)); }).ConfigureAwait(continueOnCapturedContext: false);
return ret.First();
}
/// <summary>
/// Creates a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to create.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private async Task CreateDatabaseAsync(string databaseName)
{
await Storage.ExecuteAsync(string.Format(CreateDatabaseTemplate, databaseName), command => { }).ConfigureAwait(continueOnCapturedContext: false);
}
/// <summary>
/// Drops a database with a given name.
/// </summary>
/// <param name="databaseName">The name of the database to drop.</param>
/// <returns>The call will be successful if the DDL query is successful. Otherwise an exception will be thrown.</returns>
private Task DropDatabaseAsync(string databaseName)
{
return Storage.ExecuteAsync(string.Format(DropDatabaseTemplate, databaseName), command => { });
}
/// <summary>
/// Creates a new instance of the storage based on the old connection string by changing the database name.
/// </summary>
/// <param name="newDatabaseName">Connection string instance name of the database.</param>
/// <returns>A new <see cref="RelationalStorageForTesting"/> instance with having the same connection string but with with a new databaseName.</returns>
private RelationalStorageForTesting CopyInstance(string newDatabaseName)
{
var csb = new DbConnectionStringBuilder();
csb.ConnectionString = Storage.ConnectionString;
csb["Database"] = newDatabaseName;
return CreateTestInstance(Storage.InvariantName, csb.ConnectionString);
}
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass(typeof(global::android.view.Window_))]
public abstract partial class Window : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
protected Window(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.Window.Callback_))]
public partial interface Callback : global::MonoJavaBridge.IJavaObject
{
void onWindowAttributesChanged(android.view.WindowManager_LayoutParams arg0);
void onContentChanged();
void onWindowFocusChanged(bool arg0);
void onAttachedToWindow();
void onDetachedFromWindow();
bool dispatchKeyEvent(android.view.KeyEvent arg0);
bool dispatchTouchEvent(android.view.MotionEvent arg0);
bool dispatchTrackballEvent(android.view.MotionEvent arg0);
bool dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0);
global::android.view.View onCreatePanelView(int arg0);
bool onCreatePanelMenu(int arg0, android.view.Menu arg1);
bool onPreparePanel(int arg0, android.view.View arg1, android.view.Menu arg2);
bool onMenuOpened(int arg0, android.view.Menu arg1);
bool onMenuItemSelected(int arg0, android.view.MenuItem arg1);
void onPanelClosed(int arg0, android.view.Menu arg1);
bool onSearchRequested();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.Window.Callback))]
internal sealed partial class Callback_ : java.lang.Object, Callback
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Callback_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
void android.view.Window.Callback.onWindowAttributesChanged(android.view.WindowManager_LayoutParams arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onWindowAttributesChanged", "(Landroid/view/WindowManager$LayoutParams;)V", ref global::android.view.Window.Callback_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
void android.view.Window.Callback.onContentChanged()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onContentChanged", "()V", ref global::android.view.Window.Callback_._m1);
}
private static global::MonoJavaBridge.MethodId _m2;
void android.view.Window.Callback.onWindowFocusChanged(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onWindowFocusChanged", "(Z)V", ref global::android.view.Window.Callback_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
void android.view.Window.Callback.onAttachedToWindow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onAttachedToWindow", "()V", ref global::android.view.Window.Callback_._m3);
}
private static global::MonoJavaBridge.MethodId _m4;
void android.view.Window.Callback.onDetachedFromWindow()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onDetachedFromWindow", "()V", ref global::android.view.Window.Callback_._m4);
}
private static global::MonoJavaBridge.MethodId _m5;
bool android.view.Window.Callback.dispatchKeyEvent(android.view.KeyEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.view.Window.Callback_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
bool android.view.Window.Callback.dispatchTouchEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "dispatchTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.Window.Callback_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
bool android.view.Window.Callback.dispatchTrackballEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "dispatchTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.Window.Callback_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m8;
bool android.view.Window.Callback.dispatchPopulateAccessibilityEvent(android.view.accessibility.AccessibilityEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "dispatchPopulateAccessibilityEvent", "(Landroid/view/accessibility/AccessibilityEvent;)Z", ref global::android.view.Window.Callback_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m9;
global::android.view.View android.view.Window.Callback.onCreatePanelView(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.Callback_.staticClass, "onCreatePanelView", "(I)Landroid/view/View;", ref global::android.view.Window.Callback_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m10;
bool android.view.Window.Callback.onCreatePanelMenu(int arg0, android.view.Menu arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "onCreatePanelMenu", "(ILandroid/view/Menu;)Z", ref global::android.view.Window.Callback_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m11;
bool android.view.Window.Callback.onPreparePanel(int arg0, android.view.View arg1, android.view.Menu arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "onPreparePanel", "(ILandroid/view/View;Landroid/view/Menu;)Z", ref global::android.view.Window.Callback_._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m12;
bool android.view.Window.Callback.onMenuOpened(int arg0, android.view.Menu arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "onMenuOpened", "(ILandroid/view/Menu;)Z", ref global::android.view.Window.Callback_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m13;
bool android.view.Window.Callback.onMenuItemSelected(int arg0, android.view.MenuItem arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "onMenuItemSelected", "(ILandroid/view/MenuItem;)Z", ref global::android.view.Window.Callback_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m14;
void android.view.Window.Callback.onPanelClosed(int arg0, android.view.Menu arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.Callback_.staticClass, "onPanelClosed", "(ILandroid/view/Menu;)V", ref global::android.view.Window.Callback_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
bool android.view.Window.Callback.onSearchRequested()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.Callback_.staticClass, "onSearchRequested", "()Z", ref global::android.view.Window.Callback_._m15);
}
static Callback_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.Window.Callback_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/Window$Callback"));
}
}
private static global::MonoJavaBridge.MethodId _m0;
public virtual global::android.content.Context getContext()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.staticClass, "getContext", "()Landroid/content/Context;", ref global::android.view.Window._m0) as android.content.Context;
}
private static global::MonoJavaBridge.MethodId _m1;
public virtual global::android.view.WindowManager_LayoutParams getAttributes()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.staticClass, "getAttributes", "()Landroid/view/WindowManager$LayoutParams;", ref global::android.view.Window._m1) as android.view.WindowManager_LayoutParams;
}
private static global::MonoJavaBridge.MethodId _m2;
public abstract void onConfigurationChanged(android.content.res.Configuration arg0);
private static global::MonoJavaBridge.MethodId _m3;
public virtual void setType(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setType", "(I)V", ref global::android.view.Window._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m4;
public virtual void setFlags(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setFlags", "(II)V", ref global::android.view.Window._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m5;
public virtual void addFlags(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "addFlags", "(I)V", ref global::android.view.Window._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m6;
public virtual void setCallback(android.view.Window.Callback arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setCallback", "(Landroid/view/Window$Callback;)V", ref global::android.view.Window._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public virtual global::android.view.WindowManager getWindowManager()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.WindowManager>(this, global::android.view.Window.staticClass, "getWindowManager", "()Landroid/view/WindowManager;", ref global::android.view.Window._m7) as android.view.WindowManager;
}
private static global::MonoJavaBridge.MethodId _m8;
public abstract global::android.view.View getCurrentFocus();
private static global::MonoJavaBridge.MethodId _m9;
public virtual global::android.view.View findViewById(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.staticClass, "findViewById", "(I)Landroid/view/View;", ref global::android.view.Window._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m10;
public abstract void setContentView(int arg0);
private static global::MonoJavaBridge.MethodId _m11;
public abstract void setContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1);
private static global::MonoJavaBridge.MethodId _m12;
public abstract void setContentView(android.view.View arg0);
private static global::MonoJavaBridge.MethodId _m13;
public abstract void addContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1);
private static global::MonoJavaBridge.MethodId _m14;
public abstract void takeKeyEvents(bool arg0);
private static global::MonoJavaBridge.MethodId _m15;
public abstract void setFeatureDrawableResource(int arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m16;
public abstract void setFeatureDrawableUri(int arg0, android.net.Uri arg1);
private static global::MonoJavaBridge.MethodId _m17;
public abstract void setFeatureDrawable(int arg0, android.graphics.drawable.Drawable arg1);
private static global::MonoJavaBridge.MethodId _m18;
public abstract void setFeatureDrawableAlpha(int arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m19;
public abstract global::android.view.LayoutInflater getLayoutInflater();
private static global::MonoJavaBridge.MethodId _m20;
public abstract void setTitle(java.lang.CharSequence arg0);
private static global::MonoJavaBridge.MethodId _m21;
public abstract void setTitleColor(int arg0);
private static global::MonoJavaBridge.MethodId _m22;
public abstract void setVolumeControlStream(int arg0);
private static global::MonoJavaBridge.MethodId _m23;
public abstract int getVolumeControlStream();
private static global::MonoJavaBridge.MethodId _m24;
public virtual global::android.content.res.TypedArray getWindowStyle()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.staticClass, "getWindowStyle", "()Landroid/content/res/TypedArray;", ref global::android.view.Window._m24) as android.content.res.TypedArray;
}
private static global::MonoJavaBridge.MethodId _m25;
public virtual void setContainer(android.view.Window arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setContainer", "(Landroid/view/Window;)V", ref global::android.view.Window._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public virtual global::android.view.Window getContainer()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window.staticClass, "getContainer", "()Landroid/view/Window;", ref global::android.view.Window._m26) as android.view.Window;
}
private static global::MonoJavaBridge.MethodId _m27;
public virtual bool hasChildren()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.staticClass, "hasChildren", "()Z", ref global::android.view.Window._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
public virtual void setWindowManager(android.view.WindowManager arg0, android.os.IBinder arg1, java.lang.String arg2)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setWindowManager", "(Landroid/view/WindowManager;Landroid/os/IBinder;Ljava/lang/String;)V", ref global::android.view.Window._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m29;
public virtual global::android.view.Window.Callback getCallback()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.view.Window.Callback>(this, global::android.view.Window.staticClass, "getCallback", "()Landroid/view/Window$Callback;", ref global::android.view.Window._m29) as android.view.Window.Callback;
}
private static global::MonoJavaBridge.MethodId _m30;
public abstract bool isFloating();
private static global::MonoJavaBridge.MethodId _m31;
public virtual void setLayout(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setLayout", "(II)V", ref global::android.view.Window._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m32;
public virtual void setGravity(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setGravity", "(I)V", ref global::android.view.Window._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
public virtual void setFormat(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setFormat", "(I)V", ref global::android.view.Window._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public virtual void setWindowAnimations(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setWindowAnimations", "(I)V", ref global::android.view.Window._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m35;
public virtual void setSoftInputMode(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setSoftInputMode", "(I)V", ref global::android.view.Window._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m36;
public virtual void clearFlags(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "clearFlags", "(I)V", ref global::android.view.Window._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m37;
public virtual void setAttributes(android.view.WindowManager_LayoutParams arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setAttributes", "(Landroid/view/WindowManager$LayoutParams;)V", ref global::android.view.Window._m37, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m38;
protected virtual int getForcedWindowFlags()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.Window.staticClass, "getForcedWindowFlags", "()I", ref global::android.view.Window._m38);
}
private static global::MonoJavaBridge.MethodId _m39;
protected virtual bool hasSoftInputMode()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.staticClass, "hasSoftInputMode", "()Z", ref global::android.view.Window._m39);
}
private static global::MonoJavaBridge.MethodId _m40;
public virtual bool requestFeature(int arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.staticClass, "requestFeature", "(I)Z", ref global::android.view.Window._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m41;
public virtual void makeActive()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "makeActive", "()V", ref global::android.view.Window._m41);
}
private static global::MonoJavaBridge.MethodId _m42;
public virtual bool isActive()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window.staticClass, "isActive", "()Z", ref global::android.view.Window._m42);
}
private static global::MonoJavaBridge.MethodId _m43;
public abstract void openPanel(int arg0, android.view.KeyEvent arg1);
private static global::MonoJavaBridge.MethodId _m44;
public abstract void closePanel(int arg0);
private static global::MonoJavaBridge.MethodId _m45;
public abstract void togglePanel(int arg0, android.view.KeyEvent arg1);
private static global::MonoJavaBridge.MethodId _m46;
public abstract bool performPanelShortcut(int arg0, int arg1, android.view.KeyEvent arg2, int arg3);
private static global::MonoJavaBridge.MethodId _m47;
public abstract bool performPanelIdentifierAction(int arg0, int arg1, int arg2);
private static global::MonoJavaBridge.MethodId _m48;
public abstract void closeAllPanels();
private static global::MonoJavaBridge.MethodId _m49;
public abstract bool performContextMenuIdentifierAction(int arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m50;
public virtual void setBackgroundDrawableResource(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setBackgroundDrawableResource", "(I)V", ref global::android.view.Window._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m51;
public abstract void setBackgroundDrawable(android.graphics.drawable.Drawable arg0);
private static global::MonoJavaBridge.MethodId _m52;
public abstract void setFeatureInt(int arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m53;
public abstract bool superDispatchKeyEvent(android.view.KeyEvent arg0);
private static global::MonoJavaBridge.MethodId _m54;
public abstract bool superDispatchTouchEvent(android.view.MotionEvent arg0);
private static global::MonoJavaBridge.MethodId _m55;
public abstract bool superDispatchTrackballEvent(android.view.MotionEvent arg0);
private static global::MonoJavaBridge.MethodId _m56;
public abstract global::android.view.View getDecorView();
private static global::MonoJavaBridge.MethodId _m57;
public abstract global::android.view.View peekDecorView();
private static global::MonoJavaBridge.MethodId _m58;
public abstract global::android.os.Bundle saveHierarchyState();
private static global::MonoJavaBridge.MethodId _m59;
public abstract void restoreHierarchyState(android.os.Bundle arg0);
private static global::MonoJavaBridge.MethodId _m60;
protected abstract void onActive();
private static global::MonoJavaBridge.MethodId _m61;
protected virtual int getFeatures()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.Window.staticClass, "getFeatures", "()I", ref global::android.view.Window._m61);
}
private static global::MonoJavaBridge.MethodId _m62;
protected virtual int getLocalFeatures()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.Window.staticClass, "getLocalFeatures", "()I", ref global::android.view.Window._m62);
}
private static global::MonoJavaBridge.MethodId _m63;
protected virtual void setDefaultWindowFormat(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window.staticClass, "setDefaultWindowFormat", "(I)V", ref global::android.view.Window._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m64;
public abstract void setChildDrawable(int arg0, android.graphics.drawable.Drawable arg1);
private static global::MonoJavaBridge.MethodId _m65;
public abstract void setChildInt(int arg0, int arg1);
private static global::MonoJavaBridge.MethodId _m66;
public abstract bool isShortcutKey(int arg0, android.view.KeyEvent arg1);
private static global::MonoJavaBridge.MethodId _m67;
public Window(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.view.Window._m67.native == global::System.IntPtr.Zero)
global::android.view.Window._m67 = @__env.GetMethodIDNoThrow(global::android.view.Window.staticClass, "<init>", "(Landroid/content/Context;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.view.Window.staticClass, global::android.view.Window._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
public static int FEATURE_OPTIONS_PANEL
{
get
{
return 0;
}
}
public static int FEATURE_NO_TITLE
{
get
{
return 1;
}
}
public static int FEATURE_PROGRESS
{
get
{
return 2;
}
}
public static int FEATURE_LEFT_ICON
{
get
{
return 3;
}
}
public static int FEATURE_RIGHT_ICON
{
get
{
return 4;
}
}
public static int FEATURE_INDETERMINATE_PROGRESS
{
get
{
return 5;
}
}
public static int FEATURE_CONTEXT_MENU
{
get
{
return 6;
}
}
public static int FEATURE_CUSTOM_TITLE
{
get
{
return 7;
}
}
public static int PROGRESS_VISIBILITY_ON
{
get
{
return -1;
}
}
public static int PROGRESS_VISIBILITY_OFF
{
get
{
return -2;
}
}
public static int PROGRESS_INDETERMINATE_ON
{
get
{
return -3;
}
}
public static int PROGRESS_INDETERMINATE_OFF
{
get
{
return -4;
}
}
public static int PROGRESS_START
{
get
{
return 0;
}
}
public static int PROGRESS_END
{
get
{
return 10000;
}
}
public static int PROGRESS_SECONDARY_START
{
get
{
return 20000;
}
}
public static int PROGRESS_SECONDARY_END
{
get
{
return 30000;
}
}
public static int ID_ANDROID_CONTENT
{
get
{
return 16908290;
}
}
static Window()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.Window.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/Window"));
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.Window))]
internal sealed partial class Window_ : android.view.Window
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Window_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public override void onConfigurationChanged(android.content.res.Configuration arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "onConfigurationChanged", "(Landroid/content/res/Configuration;)V", ref global::android.view.Window_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m1;
public override global::android.view.View getCurrentFocus()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window_.staticClass, "getCurrentFocus", "()Landroid/view/View;", ref global::android.view.Window_._m1) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m2;
public override void setContentView(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setContentView", "(I)V", ref global::android.view.Window_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m3;
public override void setContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.view.Window_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public override void setContentView(android.view.View arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setContentView", "(Landroid/view/View;)V", ref global::android.view.Window_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public override void addContentView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "addContentView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V", ref global::android.view.Window_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m6;
public override void takeKeyEvents(bool arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "takeKeyEvents", "(Z)V", ref global::android.view.Window_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public override void setFeatureDrawableResource(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setFeatureDrawableResource", "(II)V", ref global::android.view.Window_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m8;
public override void setFeatureDrawableUri(int arg0, android.net.Uri arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setFeatureDrawableUri", "(ILandroid/net/Uri;)V", ref global::android.view.Window_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public override void setFeatureDrawable(int arg0, android.graphics.drawable.Drawable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setFeatureDrawable", "(ILandroid/graphics/drawable/Drawable;)V", ref global::android.view.Window_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m10;
public override void setFeatureDrawableAlpha(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setFeatureDrawableAlpha", "(II)V", ref global::android.view.Window_._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m11;
public override global::android.view.LayoutInflater getLayoutInflater()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window_.staticClass, "getLayoutInflater", "()Landroid/view/LayoutInflater;", ref global::android.view.Window_._m11) as android.view.LayoutInflater;
}
private static global::MonoJavaBridge.MethodId _m12;
public override void setTitle(java.lang.CharSequence arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setTitle", "(Ljava/lang/CharSequence;)V", ref global::android.view.Window_._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
public void setTitle(string arg0)
{
setTitle((global::java.lang.CharSequence)(global::java.lang.String)arg0);
}
private static global::MonoJavaBridge.MethodId _m13;
public override void setTitleColor(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setTitleColor", "(I)V", ref global::android.view.Window_._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m14;
public override void setVolumeControlStream(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setVolumeControlStream", "(I)V", ref global::android.view.Window_._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m15;
public override int getVolumeControlStream()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.view.Window_.staticClass, "getVolumeControlStream", "()I", ref global::android.view.Window_._m15);
}
private static global::MonoJavaBridge.MethodId _m16;
public override bool isFloating()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "isFloating", "()Z", ref global::android.view.Window_._m16);
}
private static global::MonoJavaBridge.MethodId _m17;
public override void openPanel(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "openPanel", "(ILandroid/view/KeyEvent;)V", ref global::android.view.Window_._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m18;
public override void closePanel(int arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "closePanel", "(I)V", ref global::android.view.Window_._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public override void togglePanel(int arg0, android.view.KeyEvent arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "togglePanel", "(ILandroid/view/KeyEvent;)V", ref global::android.view.Window_._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m20;
public override bool performPanelShortcut(int arg0, int arg1, android.view.KeyEvent arg2, int arg3)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "performPanelShortcut", "(IILandroid/view/KeyEvent;I)Z", ref global::android.view.Window_._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
private static global::MonoJavaBridge.MethodId _m21;
public override bool performPanelIdentifierAction(int arg0, int arg1, int arg2)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "performPanelIdentifierAction", "(III)Z", ref global::android.view.Window_._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
private static global::MonoJavaBridge.MethodId _m22;
public override void closeAllPanels()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "closeAllPanels", "()V", ref global::android.view.Window_._m22);
}
private static global::MonoJavaBridge.MethodId _m23;
public override bool performContextMenuIdentifierAction(int arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "performContextMenuIdentifierAction", "(II)Z", ref global::android.view.Window_._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m24;
public override void setBackgroundDrawable(android.graphics.drawable.Drawable arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setBackgroundDrawable", "(Landroid/graphics/drawable/Drawable;)V", ref global::android.view.Window_._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m25;
public override void setFeatureInt(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setFeatureInt", "(II)V", ref global::android.view.Window_._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m26;
public override bool superDispatchKeyEvent(android.view.KeyEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "superDispatchKeyEvent", "(Landroid/view/KeyEvent;)Z", ref global::android.view.Window_._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m27;
public override bool superDispatchTouchEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "superDispatchTouchEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.Window_._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m28;
public override bool superDispatchTrackballEvent(android.view.MotionEvent arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "superDispatchTrackballEvent", "(Landroid/view/MotionEvent;)Z", ref global::android.view.Window_._m28, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m29;
public override global::android.view.View getDecorView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window_.staticClass, "getDecorView", "()Landroid/view/View;", ref global::android.view.Window_._m29) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m30;
public override global::android.view.View peekDecorView()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.view.Window_.staticClass, "peekDecorView", "()Landroid/view/View;", ref global::android.view.Window_._m30) as android.view.View;
}
private static global::MonoJavaBridge.MethodId _m31;
public override global::android.os.Bundle saveHierarchyState()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.view.Window_.staticClass, "saveHierarchyState", "()Landroid/os/Bundle;", ref global::android.view.Window_._m31) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m32;
public override void restoreHierarchyState(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "restoreHierarchyState", "(Landroid/os/Bundle;)V", ref global::android.view.Window_._m32, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m33;
protected override void onActive()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "onActive", "()V", ref global::android.view.Window_._m33);
}
private static global::MonoJavaBridge.MethodId _m34;
public override void setChildDrawable(int arg0, android.graphics.drawable.Drawable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setChildDrawable", "(ILandroid/graphics/drawable/Drawable;)V", ref global::android.view.Window_._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m35;
public override void setChildInt(int arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.view.Window_.staticClass, "setChildInt", "(II)V", ref global::android.view.Window_._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m36;
public override bool isShortcutKey(int arg0, android.view.KeyEvent arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.view.Window_.staticClass, "isShortcutKey", "(ILandroid/view/KeyEvent;)Z", ref global::android.view.Window_._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
static Window_()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.Window_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/Window"));
}
}
}
| |
/*! Achordeon - MIT License
Copyright (c) 2017 tiamatix / Wolf Robben
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.Globalization;
using System.IO;
using System.Text;
using Achordeon.Common.Extensions;
using Achordeon.Common.Helpers;
using Achordeon.Lib.Chords;
using Achordeon.Lib.DataModel;
using Achordeon.Lib.Helpers;
using Achordeon.Lib.Properties;
using DryIoc;
namespace Achordeon.Lib.Parser
{
public class ChordProParser : IDisposable
{
private Container IoC { get; }
private TextReader m_Reader;
private const char EOF = '\uffff';
private const char EOL = '\n';
private int m_CurrentLineNo ;
private int m_CurrentLinePos;
private char Current { get; set; }
private char Peek => (char) (m_Reader?.Peek() ?? EOF);
private readonly SongBook m_CurrentBook;
private Song m_CurrentSong;
private readonly Stack<LineRange> m_RangeStack = new Stack<LineRange>();
private LineRange CurrentRange => m_RangeStack.Peek();
private Line CurrentLine => CurrentRange.LastLine;
public SongBook SongBook => m_CurrentBook;
public Encoding Encoding { get; }
private void BeginSong()
{
m_CurrentBook.ThrowIfNullEx(nameof(m_CurrentBook));
m_CurrentBook.AddSong(m_CurrentSong = new Song(IoC, m_CurrentLineNo, m_CurrentLinePos));
m_RangeStack.Push(m_CurrentSong);
BeginRange(new LineRange(IoC, m_CurrentLineNo, m_CurrentLinePos), false);
}
private void BeginRange(LineRange ANewLineRange, bool AInsertBeforeCurrentLine)
{
m_CurrentSong.ThrowIfNullEx(nameof(m_CurrentSong));
if (AInsertBeforeCurrentLine && CurrentLine != null)
CurrentRange.InsertBefore(CurrentLine, ANewLineRange);
else
CurrentRange.AddLineRange(ANewLineRange);
m_RangeStack.Push(ANewLineRange);
BeginLine();
}
private void EndRange()
{
m_RangeStack.Pop();
}
private void BeginLine()
{
CurrentRange.ThrowIfNullEx(nameof(CurrentRange));
CurrentRange.AddLine(new Line(IoC, m_CurrentLineNo, m_CurrentLinePos));
}
private void ReadNextChar()
{
Current = Peek;
m_Reader?.Read();
if (Current == EOL)
{
m_CurrentLineNo++;
m_CurrentLinePos = 0;
}
m_CurrentLinePos++;
}
public ChordProParser(Container AIoC, Stream AInputStream) : this(AIoC, AInputStream, TextEncodingDetector.Detect(AInputStream) ?? Encoding.Default)
{
}
public ChordProParser(Container AIoC, Stream AInputStream, Encoding AEncoding)
{
IoC = AIoC;
m_Reader = new StreamReader(AInputStream, AEncoding);
m_CurrentBook = new SongBook(IoC);
Encoding = AEncoding;
}
public void Dispose()
{
try
{
m_Reader?.Dispose();
}
finally
{
m_Reader = null;
}
}
private void SkipWhitespace()
{
while (Current != '\r' && Current != '\n' && char.IsWhiteSpace(Current))
ReadNextChar();
}
private string ReadString()
{
var res = new StringBuilder();
while (char.IsLetter(Current) || Current == '_')
{
res.Append(Current);
ReadNextChar();
}
return res.ToString();
}
private void Expect(char AChar)
{
if (Current != AChar)
throw new ParseException(string.Format(Resources.ChordProParser_Expect___0___expected__but___1___found_, AChar, Current), m_CurrentLineNo);
}
private string ReadUntil(params char[] AStopChars)
{
var res = new StringBuilder();
while (Current != EOF && Array.IndexOf(AStopChars, Current) < 0)
{
res.Append(Current);
ReadNextChar();
}
return res.ToString();
}
private void ReadWhile(params char[] AStopChars)
{
while (Current != EOF && Array.IndexOf(AStopChars, Current) >= 0)
ReadNextChar();
}
private void ExpecteEndOfDirective()
{
SkipWhitespace();
Expect('}');
ReadNextChar();
}
private void SkipSingleLineBreak()
{
SkipWhitespace();
if (Current == '\r' && Peek == '\n')
{
ReadNextChar();
ReadNextChar();
}
else if (Current == '\n')
ReadNextChar();
}
private void ReadDirective()
{
Expect('{');
ReadNextChar();
SkipWhitespace();
var FirstString = ReadString();
switch (FirstString.ToLower())
{
case "new_page":
case "np":
CurrentRange.InsertBefore(CurrentLine, new LogicalPageBreak(IoC, m_CurrentLineNo, m_CurrentLinePos));
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginLine();
return;
case "new_physical_page":
case "npp":
CurrentRange.InsertBefore(CurrentLine, new PhysicalPageBreak(IoC, m_CurrentLineNo, m_CurrentLinePos));
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginLine();
return;
case "column_break":
case "colb":
CurrentRange.InsertBefore(CurrentLine, new ColumnBreak(IoC, m_CurrentLineNo, m_CurrentLinePos));
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginLine();
return;
case "no_grid":
case "ng":
ExpecteEndOfDirective();
SkipSingleLineBreak();
m_CurrentSong.NoGrid = true;
return;
case "grid":
case "g":
ExpecteEndOfDirective();
SkipSingleLineBreak();
m_CurrentSong.NoGrid = false;
return;
case "new_song":
case "ns":
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginSong();
return;
case "start_of_chorus":
case "soc":
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginRange(new Chorus(IoC, m_CurrentLineNo, m_CurrentLinePos), true);
return;
case "end_of_chorus":
case "eoc":
ExpecteEndOfDirective();
SkipSingleLineBreak();
CurrentRange.RemoveLastEmptyLine();
EndRange();
//BeginLine();
if (CurrentRange == null)
throw new Exception(string.Format(Resources.ChordProParser_ReadDirective_Unexpected___0_____not_within_a_chorus_, FirstString));
return;
case "start_of_tab":
case "sot":
ExpecteEndOfDirective();
SkipSingleLineBreak();
BeginRange(new Tab(IoC, m_CurrentLineNo, m_CurrentLinePos), true);
return;
case "end_of_tab":
case "eot":
ExpecteEndOfDirective();
SkipSingleLineBreak();
CurrentRange.RemoveLastEmptyLine();
EndRange();
if (CurrentRange == null)
throw new ParseException(string.Format(Resources.ChordProParser_ReadDirective_Unexpected___0_____not_within_a_tab_, FirstString), m_CurrentLineNo);
return;
case "define":
SkipWhitespace();
if (Current != ':') //Check if its the old format!
{
var RestOfLine = ReadUntil('}', EOL);
ExpecteEndOfDirective();
SkipSingleLineBreak();
m_CurrentSong.DefineChord(RestOfLine.Trim());
return;
}
break;
}
SkipWhitespace();
if (Current == ':')
{
ReadNextChar();
SkipWhitespace();
var RestOfLine = ReadUntil('}', EOL);
ExpecteEndOfDirective();
SkipSingleLineBreak();
switch (FirstString.ToLower())
{
case "define":
m_CurrentSong.DefineChord(RestOfLine.Trim(), ChordDefinitionFormat.Obsolete);
return;
case "textfont":
case "tf":
m_CurrentSong.TextFont = RestOfLine;
return;
case "textsize":
case "ts":
m_CurrentSong.TextSize = double.Parse(RestOfLine, NumberStyles.Float, CultureInfo.InvariantCulture);
return;
case "chordfont":
case "cf":
m_CurrentSong.ChordFont = RestOfLine;
return;
case "chordsize":
case "cs":
m_CurrentSong.ChordSize = double.Parse(RestOfLine, NumberStyles.Float, CultureInfo.InvariantCulture);
return;
case "columns":
case "col":
m_CurrentSong.Columns = int.Parse(RestOfLine, NumberStyles.Integer, CultureInfo.InvariantCulture);
return;
case "chordcolour":
m_CurrentSong.ChordColor = RestOfLine;
return;
case "pagetype":
m_CurrentSong.PageType = RestOfLine;
return;
case "title":
case "t":
m_CurrentSong.Title = RestOfLine;
return;
case "subtitle":
case "st":
m_CurrentSong.AddSubtitle(RestOfLine);
return;
case "comment":
case "c":
case "comment_italic":
case "ci":
case "comment_box":
case "cb":
CommentStyle Style;
switch (FirstString.ToLower())
{
case "comment":
case "c":
Style = CommentStyle.Comment;
break;
case "comment_italic":
case "ci":
Style = CommentStyle.CommentItalic;
break;
case "comment_box":
case "cb":
Style = CommentStyle.ComentBox;
break;
default:
throw new ParseException(string.Format(Resources.ChordProParser_ReadDirective_Comment_style__0__unsupported, FirstString), m_CurrentLineNo);
}
CurrentRange.InsertBefore(CurrentLine, new Comment(IoC, Style, RestOfLine, m_CurrentLineNo, m_CurrentLinePos));
return;
default:
throw new ParseException(string.Format(Resources.ChordProParser_ReadDirective_Directive___0___unsupported, FirstString), m_CurrentLineNo);
}
}
throw new ParseException(string.Format(Resources.ChordProParser_ReadDirective_Directive___0___unsupported, FirstString), m_CurrentLineNo);
}
private void ReadChord()
{
Expect('[');
ReadNextChar();
SkipWhitespace();
var Chord = ReadUntil(']', EOL);
CurrentLine.AddChord(new LineChord(IoC, Chord, m_CurrentLineNo, m_CurrentLinePos));
Expect(']');
ReadNextChar();
}
private void ReadLineBreak(int AMaxAmoutOfConsecutiveLineBreaks, bool ABeginLine)
{
int Count = 1;
while (Current != EOF && Current == '\r' || (Current == EOL) && Count <= AMaxAmoutOfConsecutiveLineBreaks)
{
if (Current == EOL)
Count++;
ReadNextChar();
}
ReadWhile(EOL, '\r');
if (ABeginLine)
{
for (int i = 0; i < Count - 1; i++)
BeginLine();
}
}
private void ReadPlainText()
{
var Text = string.Empty;
switch (Current)
{
case '[':
case '{':
case '\r':
case EOL:
Text += Current;
ReadNextChar();
break;
}
Text += ReadUntil('[', '{', EOL, '\r');
CurrentLine.AddText(new LineText(IoC, Text, m_CurrentLineNo, m_CurrentLinePos));
}
public void ReadFile()
{
BeginSong();
try
{
ReadNextChar();
while (true)
{
switch (Current)
{
case EOF:
return;
case '[':
if (CurrentRange.AcceptNonPlaintext)
ReadChord();
else
ReadPlainText();
break;
case '{':
ReadDirective();
break;
case '\r':
case EOL:
ReadLineBreak(Int32.MaxValue, true);
break;
default:
ReadPlainText();
break;
}
}
}
finally
{
SongBook.RebuildBuildChordList();
}
}
}
}
| |
// Copyright (c) Pomelo Foundation. All rights reserved.
// Licensed under the MIT. See LICENSE in the project root for license information.
using System;
using System.Linq;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal;
using Pomelo.EntityFrameworkCore.MySql.Storage.Internal;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Microsoft.EntityFrameworkCore.Diagnostics;
using MySqlConnector;
namespace Pomelo.EntityFrameworkCore.MySql.Internal
{
public class MySqlOptions : IMySqlOptions
{
private static readonly MySqlSchemaNameTranslator _ignoreSchemaNameTranslator = (_, objectName) => objectName;
public MySqlOptions()
{
ConnectionSettings = new MySqlConnectionSettings();
ServerVersion = null;
// We explicitly use `utf8mb4` in all instances, where charset based calculations need to be done, but accessing annotations
// isn't possible (e.g. in `MySqlTypeMappingSource`).
// This is also being used as the universal fallback character set, if no character set was explicitly defined for the model,
// which will result in similar behavior as in previous versions and ensure that databases use a decent/the recommended charset
// by default, if none was explicitly set.
DefaultCharSet = CharSet.Utf8Mb4;
// NCHAR and NVARCHAR are prefdefined by MySQL.
NationalCharSet = CharSet.Utf8Mb3;
// Optimize space and performance for GUID columns.
DefaultGuidCollation = "ascii_general_ci";
ReplaceLineBreaksWithCharFunction = true;
DefaultDataTypeMappings = new MySqlDefaultDataTypeMappings();
// Throw by default if a schema is being used with any type.
SchemaNameTranslator = null;
// TODO: Change to `true` for EF Core 5.
IndexOptimizedBooleanColumns = false;
LimitKeyedOrIndexedStringColumnLength = true;
StringComparisonTranslations = false;
}
public virtual void Initialize(IDbContextOptions options)
{
var mySqlOptions = options.FindExtension<MySqlOptionsExtension>() ?? new MySqlOptionsExtension();
var mySqlJsonOptions = (MySqlJsonOptionsExtension)options.Extensions.LastOrDefault(e => e is MySqlJsonOptionsExtension);
ConnectionSettings = GetConnectionSettings(mySqlOptions);
ServerVersion = mySqlOptions.ServerVersion ?? throw new InvalidOperationException($"The {nameof(ServerVersion)} has not been set.");
NoBackslashEscapes = mySqlOptions.NoBackslashEscapes;
ReplaceLineBreaksWithCharFunction = mySqlOptions.ReplaceLineBreaksWithCharFunction;
DefaultDataTypeMappings = ApplyDefaultDataTypeMappings(mySqlOptions.DefaultDataTypeMappings, ConnectionSettings);
SchemaNameTranslator = mySqlOptions.SchemaNameTranslator ?? (mySqlOptions.SchemaBehavior == MySqlSchemaBehavior.Ignore
? _ignoreSchemaNameTranslator
: null);
IndexOptimizedBooleanColumns = mySqlOptions.IndexOptimizedBooleanColumns;
JsonChangeTrackingOptions = mySqlJsonOptions?.JsonChangeTrackingOptions ?? default;
LimitKeyedOrIndexedStringColumnLength = mySqlOptions.LimitKeyedOrIndexedStringColumnLength;
StringComparisonTranslations = mySqlOptions.StringComparisonTranslations;
}
public virtual void Validate(IDbContextOptions options)
{
var mySqlOptions = options.FindExtension<MySqlOptionsExtension>() ?? new MySqlOptionsExtension();
var mySqlJsonOptions = (MySqlJsonOptionsExtension)options.Extensions.LastOrDefault(e => e is MySqlJsonOptionsExtension);
var connectionSettings = GetConnectionSettings(mySqlOptions);
if (!Equals(ServerVersion, mySqlOptions.ServerVersion))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlOptionsExtension.ServerVersion),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(ConnectionSettings.TreatTinyAsBoolean, connectionSettings.TreatTinyAsBoolean))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlConnectionStringBuilder.TreatTinyAsBoolean),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(ConnectionSettings.GuidFormat, connectionSettings.GuidFormat))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlConnectionStringBuilder.GuidFormat),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(NoBackslashEscapes, mySqlOptions.NoBackslashEscapes))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.DisableBackslashEscaping),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(ReplaceLineBreaksWithCharFunction, mySqlOptions.ReplaceLineBreaksWithCharFunction))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.DisableLineBreakToCharSubstition),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(DefaultDataTypeMappings, ApplyDefaultDataTypeMappings(mySqlOptions.DefaultDataTypeMappings ?? new MySqlDefaultDataTypeMappings(), connectionSettings)))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.DefaultDataTypeMappings),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(
SchemaNameTranslator,
mySqlOptions.SchemaBehavior == MySqlSchemaBehavior.Ignore
? _ignoreSchemaNameTranslator
: SchemaNameTranslator))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.SchemaBehavior),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(IndexOptimizedBooleanColumns, mySqlOptions.IndexOptimizedBooleanColumns))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.EnableIndexOptimizedBooleanColumns),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(JsonChangeTrackingOptions, mySqlJsonOptions?.JsonChangeTrackingOptions ?? default))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlJsonOptionsExtension.JsonChangeTrackingOptions),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(LimitKeyedOrIndexedStringColumnLength, mySqlOptions.LimitKeyedOrIndexedStringColumnLength))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.LimitKeyedOrIndexedStringColumnLength),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
if (!Equals(StringComparisonTranslations, mySqlOptions.StringComparisonTranslations))
{
throw new InvalidOperationException(
CoreStrings.SingletonOptionChanged(
nameof(MySqlDbContextOptionsBuilder.EnableStringComparisonTranslations),
nameof(DbContextOptionsBuilder.UseInternalServiceProvider)));
}
}
protected virtual MySqlDefaultDataTypeMappings ApplyDefaultDataTypeMappings(MySqlDefaultDataTypeMappings defaultDataTypeMappings, MySqlConnectionSettings connectionSettings)
{
defaultDataTypeMappings ??= DefaultDataTypeMappings;
// Explicitly set MySqlDefaultDataTypeMappings values take precedence over connection string options.
if (connectionSettings.TreatTinyAsBoolean.HasValue &&
defaultDataTypeMappings.ClrBoolean == MySqlBooleanType.Default)
{
defaultDataTypeMappings = defaultDataTypeMappings.WithClrBoolean(
connectionSettings.TreatTinyAsBoolean.Value
? MySqlBooleanType.TinyInt1
: MySqlBooleanType.Bit1);
}
if (defaultDataTypeMappings.ClrDateTime == MySqlDateTimeType.Default)
{
defaultDataTypeMappings = defaultDataTypeMappings.WithClrDateTime(
ServerVersion.Supports.DateTime6
? MySqlDateTimeType.DateTime6
: MySqlDateTimeType.DateTime);
}
if (defaultDataTypeMappings.ClrDateTimeOffset == MySqlDateTimeType.Default)
{
defaultDataTypeMappings = defaultDataTypeMappings.WithClrDateTimeOffset(
ServerVersion.Supports.DateTime6
? MySqlDateTimeType.DateTime6
: MySqlDateTimeType.DateTime);
}
if (defaultDataTypeMappings.ClrTimeSpan == MySqlTimeSpanType.Default)
{
defaultDataTypeMappings = defaultDataTypeMappings.WithClrTimeSpan(
ServerVersion.Supports.DateTime6
? MySqlTimeSpanType.Time6
: MySqlTimeSpanType.Time);
}
if (defaultDataTypeMappings.ClrTimeOnlyPrecision < 0)
{
defaultDataTypeMappings = defaultDataTypeMappings.WithClrTimeOnly(
ServerVersion.Supports.DateTime6
? 6
: 0);
}
return defaultDataTypeMappings;
}
private static MySqlConnectionSettings GetConnectionSettings(MySqlOptionsExtension relationalOptions)
=> relationalOptions.Connection != null
? new MySqlConnectionSettings(relationalOptions.Connection)
: new MySqlConnectionSettings(relationalOptions.ConnectionString);
protected virtual bool Equals(MySqlOptions other)
{
return Equals(ConnectionSettings, other.ConnectionSettings) &&
Equals(ServerVersion, other.ServerVersion) &&
Equals(DefaultCharSet, other.DefaultCharSet) &&
Equals(NationalCharSet, other.NationalCharSet) &&
Equals(DefaultGuidCollation, other.DefaultGuidCollation) &&
NoBackslashEscapes == other.NoBackslashEscapes &&
ReplaceLineBreaksWithCharFunction == other.ReplaceLineBreaksWithCharFunction &&
Equals(DefaultDataTypeMappings, other.DefaultDataTypeMappings) &&
Equals(SchemaNameTranslator, other.SchemaNameTranslator) &&
IndexOptimizedBooleanColumns == other.IndexOptimizedBooleanColumns &&
JsonChangeTrackingOptions == other.JsonChangeTrackingOptions &&
LimitKeyedOrIndexedStringColumnLength == other.LimitKeyedOrIndexedStringColumnLength &&
StringComparisonTranslations == other.StringComparisonTranslations;
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != this.GetType())
{
return false;
}
return Equals((MySqlOptions)obj);
}
public override int GetHashCode()
{
var hashCode = new HashCode();
hashCode.Add(ConnectionSettings);
hashCode.Add(ServerVersion);
hashCode.Add(DefaultCharSet);
hashCode.Add(NationalCharSet);
hashCode.Add(DefaultGuidCollation);
hashCode.Add(NoBackslashEscapes);
hashCode.Add(ReplaceLineBreaksWithCharFunction);
hashCode.Add(DefaultDataTypeMappings);
hashCode.Add(SchemaNameTranslator);
hashCode.Add(IndexOptimizedBooleanColumns);
hashCode.Add(JsonChangeTrackingOptions);
hashCode.Add(LimitKeyedOrIndexedStringColumnLength);
hashCode.Add(StringComparisonTranslations);
return hashCode.ToHashCode();
}
public virtual MySqlConnectionSettings ConnectionSettings { get; private set; }
public virtual ServerVersion ServerVersion { get; private set; }
public virtual CharSet DefaultCharSet { get; private set; }
public virtual CharSet NationalCharSet { get; }
public virtual string DefaultGuidCollation { get; private set; }
public virtual bool NoBackslashEscapes { get; private set; }
public virtual bool ReplaceLineBreaksWithCharFunction { get; private set; }
public virtual MySqlDefaultDataTypeMappings DefaultDataTypeMappings { get; private set; }
public virtual MySqlSchemaNameTranslator SchemaNameTranslator { get; private set; }
public virtual bool IndexOptimizedBooleanColumns { get; private set; }
public virtual MySqlJsonChangeTrackingOptions JsonChangeTrackingOptions { get; private set; }
public virtual bool LimitKeyedOrIndexedStringColumnLength { get; private set; }
public virtual bool StringComparisonTranslations { get; private set; }
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Reflection.Metadata.Tests;
using Xunit;
namespace System.Reflection.Metadata.Ecma335.Tests
{
public class MetadataBuilderTests
{
[Fact]
public void Ctor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataBuilder(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataBuilder(0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataBuilder(0, 0, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataBuilder(0, 0, 0, -1));
AssertExtensions.Throws<ArgumentException>("guidHeapStartOffset", () => new MetadataBuilder(0, 0, 0, 1));
new MetadataBuilder(userStringHeapStartOffset: 0x00fffffe);
Assert.Throws<ImageFormatLimitationException>(() => new MetadataBuilder(userStringHeapStartOffset: 0x00ffffff));
}
[Fact]
public void Add()
{
var builder = new MetadataBuilder();
builder.AddModule(default(int), default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.Module));
builder.AddAssembly(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), default(AssemblyFlags), default(AssemblyHashAlgorithm));
Assert.Equal(1, builder.GetRowCount(TableIndex.Assembly));
var assemblyReference = builder.AddAssemblyReference(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), default(AssemblyFlags), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.AssemblyRef));
Assert.Equal(1, MetadataTokens.GetRowNumber(assemblyReference));
var typeDefinition = builder.AddTypeDefinition(default(TypeAttributes), default(StringHandle), default(StringHandle), default(EntityHandle), default(FieldDefinitionHandle), default(MethodDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.TypeDef));
Assert.Equal(1, MetadataTokens.GetRowNumber(typeDefinition));
builder.AddTypeLayout(default(TypeDefinitionHandle), default(ushort), default(uint));
Assert.Equal(1, builder.GetRowCount(TableIndex.ClassLayout));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Equal(1, builder.GetRowCount(TableIndex.InterfaceImpl));
builder.AddNestedType(default(TypeDefinitionHandle), default(TypeDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.NestedClass));
var typeReference = builder.AddTypeReference(EntityHandle.ModuleDefinition, default(StringHandle), default(StringHandle));
Assert.Equal(1, MetadataTokens.GetRowNumber(typeReference));
Assert.Equal(1, builder.GetRowCount(TableIndex.TypeRef));
builder.AddTypeSpecification(default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.TypeSpec));
builder.AddStandaloneSignature(default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.StandAloneSig));
builder.AddProperty(default(PropertyAttributes), default(StringHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.Property));
builder.AddPropertyMap(default(TypeDefinitionHandle), default(PropertyDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.PropertyMap));
builder.AddEvent(default(EventAttributes), default(StringHandle), MetadataTokens.TypeDefinitionHandle(1));
Assert.Equal(1, builder.GetRowCount(TableIndex.Event));
builder.AddEventMap(default(TypeDefinitionHandle), default(EventDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.EventMap));
builder.AddConstant(MetadataTokens.FieldDefinitionHandle(1), default(object));
Assert.Equal(1, builder.GetRowCount(TableIndex.Constant));
builder.AddMethodSemantics(MetadataTokens.EventDefinitionHandle(1), default(ushort), default(MethodDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.MethodSemantics));
builder.AddCustomAttribute(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.MethodDefinitionHandle(1), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.CustomAttribute));
builder.AddMethodSpecification(MetadataTokens.MethodDefinitionHandle(1), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.MethodSpec));
builder.AddModuleReference(default(StringHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.ModuleRef));
builder.AddParameter(default(ParameterAttributes), default(StringHandle), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.Param));
var genericParameter = builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.GenericParam));
Assert.Equal(1, MetadataTokens.GetRowNumber(genericParameter));
builder.AddGenericParameterConstraint(default(GenericParameterHandle), MetadataTokens.TypeDefinitionHandle(1));
Assert.Equal(1, builder.GetRowCount(TableIndex.GenericParamConstraint));
builder.AddFieldDefinition(default(FieldAttributes), default(StringHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.Field));
builder.AddFieldLayout(default(FieldDefinitionHandle), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.FieldLayout));
builder.AddMarshallingDescriptor(MetadataTokens.FieldDefinitionHandle(1), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.FieldMarshal));
builder.AddFieldRelativeVirtualAddress(default(FieldDefinitionHandle), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.FieldRva));
var methodDefinition = builder.AddMethodDefinition(default(MethodAttributes), default(MethodImplAttributes), default(StringHandle), default(BlobHandle), default(int), default(ParameterHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.MethodDef));
Assert.Equal(1, MetadataTokens.GetRowNumber(methodDefinition));
builder.AddMethodImport(MetadataTokens.MethodDefinitionHandle(1), default(MethodImportAttributes), default(StringHandle), default(ModuleReferenceHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.ImplMap));
builder.AddMethodImplementation(default(TypeDefinitionHandle), MetadataTokens.MethodDefinitionHandle(1), MetadataTokens.MethodDefinitionHandle(1));
Assert.Equal(1, builder.GetRowCount(TableIndex.MethodImpl));
var memberReference = builder.AddMemberReference(MetadataTokens.TypeDefinitionHandle(1), default(StringHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.MemberRef));
Assert.Equal(1, MetadataTokens.GetRowNumber(memberReference));
builder.AddManifestResource(default(ManifestResourceAttributes), default(StringHandle), MetadataTokens.AssemblyFileHandle(1), default(uint));
Assert.Equal(1, builder.GetRowCount(TableIndex.ManifestResource));
builder.AddAssemblyFile(default(StringHandle), default(BlobHandle), default(Boolean));
Assert.Equal(1, builder.GetRowCount(TableIndex.File));
builder.AddExportedType(default(TypeAttributes), default(StringHandle), default(StringHandle), MetadataTokens.AssemblyFileHandle(1), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.ExportedType));
builder.AddDeclarativeSecurityAttribute(MetadataTokens.TypeDefinitionHandle(1), default(DeclarativeSecurityAction), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.DeclSecurity));
builder.AddEncLogEntry(MetadataTokens.TypeDefinitionHandle(1), default(EditAndContinueOperation));
Assert.Equal(1, builder.GetRowCount(TableIndex.EncLog));
builder.AddEncMapEntry(MetadataTokens.TypeDefinitionHandle(1));
Assert.Equal(1, builder.GetRowCount(TableIndex.EncMap));
var document = builder.AddDocument(default(BlobHandle), default(GuidHandle), default(BlobHandle), default(GuidHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.Document));
Assert.Equal(1, MetadataTokens.GetRowNumber(document));
builder.AddMethodDebugInformation(default(DocumentHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.MethodDebugInformation));
var localScope = builder.AddLocalScope(default(MethodDefinitionHandle), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), default(int), default(int));
Assert.Equal(1, builder.GetRowCount(TableIndex.LocalScope));
Assert.Equal(1, MetadataTokens.GetRowNumber(localScope));
var localVariable = builder.AddLocalVariable(default(LocalVariableAttributes), default(int), default(StringHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.LocalVariable));
Assert.Equal(1, MetadataTokens.GetRowNumber(localVariable));
var localConstant = builder.AddLocalConstant(default(StringHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.LocalConstant));
Assert.Equal(1, MetadataTokens.GetRowNumber(localConstant));
var importScope = builder.AddImportScope(default(ImportScopeHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.ImportScope));
Assert.Equal(1, MetadataTokens.GetRowNumber(importScope));
builder.AddStateMachineMethod(default(MethodDefinitionHandle), default(MethodDefinitionHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.StateMachineMethod));
builder.AddCustomDebugInformation(default(EntityHandle), default(GuidHandle), default(BlobHandle));
Assert.Equal(1, builder.GetRowCount(TableIndex.CustomDebugInformation));
Assert.Equal(0, builder.GetRowCount(TableIndex.AssemblyOS));
Assert.Equal(0, builder.GetRowCount(TableIndex.AssemblyProcessor));
Assert.Equal(0, builder.GetRowCount(TableIndex.AssemblyRefOS));
Assert.Equal(0, builder.GetRowCount(TableIndex.AssemblyRefProcessor));
Assert.Equal(0, builder.GetRowCount(TableIndex.EventPtr));
Assert.Equal(0, builder.GetRowCount(TableIndex.FieldPtr));
Assert.Equal(0, builder.GetRowCount(TableIndex.MethodPtr));
Assert.Equal(0, builder.GetRowCount(TableIndex.ParamPtr));
Assert.Equal(0, builder.GetRowCount(TableIndex.PropertyPtr));
var rowCounts = builder.GetRowCounts();
Assert.Equal(MetadataTokens.TableCount, rowCounts.Length);
foreach (TableIndex tableIndex in Enum.GetValues(typeof(TableIndex)))
{
Assert.Equal(builder.GetRowCount(tableIndex), rowCounts[(int)tableIndex]);
}
}
[Fact]
public void GetRowCount_Errors()
{
var builder = new MetadataBuilder();
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)0x2D));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)0x2E));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)0x2F));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)0x38));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)0x39));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.GetRowCount((TableIndex)255));
}
/// <summary>
/// Add methods do minimal validation to avoid overhead.
/// </summary>
[Fact]
public void Add_ArgumentErrors()
{
var builder = new MetadataBuilder();
var badHandleKind = CustomAttributeHandle.FromRowId(1);
Assert.Throws<ArgumentNullException>(() => builder.AddAssembly(default(StringHandle), null, default(StringHandle), default(BlobHandle), 0, 0));
Assert.Throws<ArgumentNullException>(() => builder.AddAssemblyReference(default(StringHandle), null, default(StringHandle), default(BlobHandle), 0, default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddTypeDefinition(0, default(StringHandle), default(StringHandle), badHandleKind, default(FieldDefinitionHandle), default(MethodDefinitionHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddInterfaceImplementation(default(TypeDefinitionHandle), badHandleKind));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddTypeReference(badHandleKind, default(StringHandle), default(StringHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddEvent(0, default(StringHandle), badHandleKind));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddConstant(badHandleKind, 0));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMethodSemantics(badHandleKind, 0, default(MethodDefinitionHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddCustomAttribute(badHandleKind, default(MethodDefinitionHandle), default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddCustomAttribute(default(TypeDefinitionHandle), badHandleKind, default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMethodSpecification(badHandleKind, default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddGenericParameter(badHandleKind, 0, default(StringHandle), 0));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddGenericParameterConstraint(default(GenericParameterHandle), badHandleKind));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMarshallingDescriptor(badHandleKind, default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMethodImplementation(default(TypeDefinitionHandle), badHandleKind, default(MethodDefinitionHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMethodImplementation(default(TypeDefinitionHandle), default(MethodDefinitionHandle), badHandleKind));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddMemberReference(badHandleKind, default(StringHandle), default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddManifestResource(0, default(StringHandle), badHandleKind, 0));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddExportedType(0, default(StringHandle), default(StringHandle), badHandleKind, 0));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddDeclarativeSecurityAttribute(badHandleKind, 0, default(BlobHandle)));
AssertExtensions.Throws<ArgumentException>(null, () => builder.AddCustomDebugInformation(badHandleKind, default(GuidHandle), default(BlobHandle)));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddModule(-1, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddModule(ushort.MaxValue + 1, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddParameter(0, default(StringHandle), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddGenericParameter(default(TypeDefinitionHandle), 0, default(StringHandle), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddFieldRelativeVirtualAddress(default(FieldDefinitionHandle), -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddMethodDefinition(0, 0, default(StringHandle), default(BlobHandle), -2, default(ParameterHandle)));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.AddLocalVariable(0, -1, default(StringHandle)));
}
[Fact]
public void MultipleModuleAssemblyEntries()
{
var builder = new MetadataBuilder();
builder.AddAssembly(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), 0, 0);
builder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle));
Assert.Throws<InvalidOperationException>(() => builder.AddAssembly(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), 0, 0));
Assert.Throws<InvalidOperationException>(() => builder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle)));
}
[Fact]
public void Add_BadValues()
{
var builder = new MetadataBuilder();
builder.AddAssembly(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), (AssemblyFlags)(-1), (AssemblyHashAlgorithm)(-1));
builder.AddAssemblyReference(default(StringHandle), new Version(0, 0, 0, 0), default(StringHandle), default(BlobHandle), (AssemblyFlags)(-1), default(BlobHandle));
builder.AddTypeDefinition((TypeAttributes)(-1), default(StringHandle), default(StringHandle), default(TypeDefinitionHandle), default(FieldDefinitionHandle), default(MethodDefinitionHandle));
builder.AddProperty((PropertyAttributes)(-1), default(StringHandle), default(BlobHandle));
builder.AddEvent((EventAttributes)(-1), default(StringHandle), default(TypeDefinitionHandle));
builder.AddMethodSemantics(default(EventDefinitionHandle), (MethodSemanticsAttributes)(-1), default(MethodDefinitionHandle));
builder.AddParameter((ParameterAttributes)(-1), default(StringHandle), 0);
builder.AddGenericParameter(default(TypeDefinitionHandle), (GenericParameterAttributes)(-1), default(StringHandle), 0);
builder.AddFieldDefinition((FieldAttributes)(-1), default(StringHandle), default(BlobHandle));
builder.AddMethodDefinition((MethodAttributes)(-1), (MethodImplAttributes)(-1), default(StringHandle), default(BlobHandle), -1, default(ParameterHandle));
builder.AddMethodImport(default(MethodDefinitionHandle), (MethodImportAttributes)(-1), default(StringHandle), default(ModuleReferenceHandle));
builder.AddManifestResource((ManifestResourceAttributes)(-1), default(StringHandle), default(AssemblyFileHandle), 0);
builder.AddExportedType((TypeAttributes)(-1), default(StringHandle), default(StringHandle), default(AssemblyFileHandle), 0);
builder.AddDeclarativeSecurityAttribute(default(TypeDefinitionHandle), (DeclarativeSecurityAction)(-1), default(BlobHandle));
builder.AddEncLogEntry(default(TypeDefinitionHandle), (EditAndContinueOperation)(-1));
builder.AddLocalVariable((LocalVariableAttributes)(-1), 0, default(StringHandle));
}
[Fact]
public void GetOrAddErrors()
{
var mdBuilder = new MetadataBuilder();
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddBlob((BlobBuilder)null));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddBlob((byte[])null));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddBlob(default(ImmutableArray<byte>)));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddBlobUTF8(null));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddBlobUTF16(null));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddDocumentName(null));
AssertExtensions.Throws<ArgumentNullException>("value", () => mdBuilder.GetOrAddString(null));
}
[Fact]
public void Heaps_Empty()
{
var mdBuilder = new MetadataBuilder();
var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false);
var builder = new BlobBuilder();
mdBuilder.WriteHeapsTo(builder, serialized.StringHeap);
AssertEx.Equal(new byte[]
{
0x00, 0x00, 0x00, 0x00, // #String
0x00, 0x00, 0x00, 0x00, // #US
// #Guid
0x00, 0x00, 0x00, 0x00 // #Blob
}, builder.ToArray());
}
[Fact]
public void Heaps()
{
var mdBuilder = new MetadataBuilder();
var g0 = mdBuilder.GetOrAddGuid(default(Guid));
Assert.True(g0.IsNil);
Assert.Equal(0, g0.Index);
var g1 = mdBuilder.GetOrAddGuid(new Guid("D39F3559-476A-4D1E-B6D2-88E66395230B"));
Assert.Equal(1, g1.Index);
var s0 = mdBuilder.GetOrAddString("");
Assert.False(s0.IsVirtual);
Assert.Equal(0, s0.GetWriterVirtualIndex());
var s1 = mdBuilder.GetOrAddString("foo");
Assert.True(s1.IsVirtual);
Assert.Equal(1, s1.GetWriterVirtualIndex());
var us0 = mdBuilder.GetOrAddUserString("");
Assert.Equal(1, us0.GetHeapOffset());
var us1 = mdBuilder.GetOrAddUserString("bar");
Assert.Equal(3, us1.GetHeapOffset());
var b0 = mdBuilder.GetOrAddBlob(new byte[0]);
Assert.Equal(0, b0.GetHeapOffset());
var b1 = mdBuilder.GetOrAddBlob(new byte[] { 1, 2 });
Assert.Equal(1, b1.GetHeapOffset());
var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false);
Assert.Equal(0, mdBuilder.SerializeHandle(g0));
Assert.Equal(1, mdBuilder.SerializeHandle(g1));
Assert.Equal(0, mdBuilder.SerializeHandle(serialized.StringMap, s0));
Assert.Equal(1, mdBuilder.SerializeHandle(serialized.StringMap, s1));
Assert.Equal(1, mdBuilder.SerializeHandle(us0));
Assert.Equal(3, mdBuilder.SerializeHandle(us1));
Assert.Equal(0, mdBuilder.SerializeHandle(b0));
Assert.Equal(1, mdBuilder.SerializeHandle(b1));
var heaps = new BlobBuilder();
mdBuilder.WriteHeapsTo(heaps, serialized.StringHeap);
AssertEx.Equal(new byte[]
{
// #String
0x00,
0x66, 0x6F, 0x6F, 0x00,
0x00, 0x00, 0x00,
// #US
0x00,
0x01, 0x00,
0x07, 0x62, 0x00, 0x61, 0x00, 0x72, 0x00, 0x00,
0x00,
// #Guid
0x59, 0x35, 0x9F, 0xD3, 0x6A, 0x47, 0x1E, 0x4D, 0xB6, 0xD2, 0x88, 0xE6, 0x63, 0x95, 0x23, 0x0B,
// #Blob
0x00, 0x02, 0x01, 0x02
}, heaps.ToArray());
}
[Fact]
public void GetOrAddDocumentName1()
{
var mdBuilder = new MetadataBuilder();
mdBuilder.GetOrAddDocumentName("");
mdBuilder.GetOrAddDocumentName("/a/b/c");
mdBuilder.GetOrAddDocumentName(@"\a\b\cc");
mdBuilder.GetOrAddDocumentName(@"/a/b\c");
mdBuilder.GetOrAddDocumentName(@"/\a/\b\\//c");
mdBuilder.GetOrAddDocumentName(@"a/");
mdBuilder.GetOrAddDocumentName(@"/");
mdBuilder.GetOrAddDocumentName(@"\\");
mdBuilder.GetOrAddDocumentName("\ud800"); // unpaired surrogate
mdBuilder.GetOrAddDocumentName("\0");
var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false);
var heaps = new BlobBuilder();
mdBuilder.WriteHeapsTo(heaps, serialized.StringHeap);
AssertEx.Equal(new byte[]
{
// #String
0x00, 0x00, 0x00, 0x00,
// #US
0x00, 0x00, 0x00, 0x00,
0x00, // 0x00
// ""
0x02, (byte)'/', 0x00,
0x01, (byte)'a', // 0x04
0x01, (byte)'b', // 0x06
0x01, (byte)'c', // 0x08
// "/a/b/c"
0x05, (byte)'/', 0x00, 0x04, 0x06, 0x08,
// 0x10
0x02, (byte)'c', (byte)'c',
// @"\a\b\cc"
0x05, (byte)'\\', 0x00, 0x04, 0x06, 0x10,
// 0x19
0x03, (byte)'b', (byte)'\\', (byte)'c',
// @"/a/b\c"
0x04, (byte)'/', 0x00, 0x04, 0x19,
// 0x22
0x02, (byte)'\\', (byte)'a',
// 0x25
0x04, (byte)'\\', (byte)'b', (byte)'\\', (byte)'\\',
// @"/\a/\b\\//c"
0x06, (byte)'/', 0x00, 0x22, 0x25, 0x00, 0x08,
// @"a/"
0x03, (byte)'/', 0x04, 0x00,
// @"/"
0x03, (byte)'/', 0x00, 0x00,
// @"\\"
0x04, (byte)'\\', 0x00, 0x00, 0x00,
// 0x3E
0x03, 0xED, 0xA0, 0x80,
// "\ud800"
0x02, (byte)'/', 0x3E,
// 0x45
0x01, 0x00,
// "\0"
0x02, (byte)'/', 0x45,
// heap padding
0x00, 0x00
}, heaps.ToArray());
}
[Fact]
public void GetOrAddDocumentName2()
{
var mdBuilder = new MetadataBuilder();
mdBuilder.AddModule(0, default(StringHandle), default(GuidHandle), default(GuidHandle), default(GuidHandle));
var n1 = mdBuilder.GetOrAddDocumentName("");
var n2 = mdBuilder.GetOrAddDocumentName("/a/b/c");
var n3 = mdBuilder.GetOrAddDocumentName(@"\a\b\cc");
var n4 = mdBuilder.GetOrAddDocumentName(@"/a/b\c");
var n5 = mdBuilder.GetOrAddDocumentName(@"/\a/\b\\//c");
var n6 = mdBuilder.GetOrAddDocumentName(@"a/");
var n7 = mdBuilder.GetOrAddDocumentName(@"/");
var n8 = mdBuilder.GetOrAddDocumentName(@"\\");
var n9 = mdBuilder.GetOrAddDocumentName("\ud800"); // unpaired surrogate
var n10 = mdBuilder.GetOrAddDocumentName("\0");
var root = new MetadataRootBuilder(mdBuilder);
var rootBuilder = new BlobBuilder();
root.Serialize(rootBuilder, 0, 0);
var mdImage = rootBuilder.ToImmutableArray();
using (var provider = MetadataReaderProvider.FromMetadataImage(mdImage))
{
var mdReader = provider.GetMetadataReader();
Assert.Equal("", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n1))));
Assert.Equal("/a/b/c", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n2))));
Assert.Equal(@"\a\b\cc", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n3))));
Assert.Equal(@"/a/b\c", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n4))));
Assert.Equal(@"/\a/\b\\//c", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n5))));
Assert.Equal(@"a/", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n6))));
Assert.Equal(@"/", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n7))));
Assert.Equal(@"\\", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n8))));
Assert.Equal("\uFFFd\uFFFd", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n9))));
Assert.Equal("\0", mdReader.GetString(MetadataTokens.DocumentNameBlobHandle(MetadataTokens.GetHeapOffset(n10))));
}
}
[Fact]
public void Heaps_StartOffsets()
{
var mdBuilder = new MetadataBuilder(
userStringHeapStartOffset: 0x10,
stringHeapStartOffset: 0x20,
blobHeapStartOffset: 0x30,
guidHeapStartOffset: 0x40);
var g = mdBuilder.GetOrAddGuid(new Guid("D39F3559-476A-4D1E-B6D2-88E66395230B"));
Assert.Equal(5, g.Index);
var s0 = mdBuilder.GetOrAddString("");
Assert.False(s0.IsVirtual);
Assert.Equal(0, s0.GetWriterVirtualIndex());
var s1 = mdBuilder.GetOrAddString("foo");
Assert.True(s1.IsVirtual);
Assert.Equal(1, s1.GetWriterVirtualIndex());
var us0 = mdBuilder.GetOrAddUserString("");
Assert.Equal(0x11, us0.GetHeapOffset());
var us1 = mdBuilder.GetOrAddUserString("bar");
Assert.Equal(0x13, us1.GetHeapOffset());
var b0 = mdBuilder.GetOrAddBlob(new byte[0]);
Assert.Equal(0, b0.GetHeapOffset());
var b1 = mdBuilder.GetOrAddBlob(new byte[] { 1, 2 });
Assert.Equal(0x31, b1.GetHeapOffset());
var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false);
Assert.Equal(5, mdBuilder.SerializeHandle(g));
Assert.Equal(0, mdBuilder.SerializeHandle(serialized.StringMap, s0));
Assert.Equal(0x21, mdBuilder.SerializeHandle(serialized.StringMap, s1));
Assert.Equal(0x11, mdBuilder.SerializeHandle(us0));
Assert.Equal(0x13, mdBuilder.SerializeHandle(us1));
Assert.Equal(0, mdBuilder.SerializeHandle(b0));
Assert.Equal(0x31, mdBuilder.SerializeHandle(b1));
var heaps = new BlobBuilder();
mdBuilder.WriteHeapsTo(heaps, serialized.StringHeap);
AssertEx.Equal(new byte[]
{
// #String
0x00,
0x66, 0x6F, 0x6F, 0x00,
0x00, 0x00, 0x00,
// #US
0x00,
0x01, 0x00,
0x07, 0x62, 0x00, 0x61, 0x00, 0x72, 0x00, 0x00,
0x00,
// #Guid
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x59, 0x35, 0x9F, 0xD3, 0x6A, 0x47, 0x1E, 0x4D, 0xB6, 0xD2, 0x88, 0xE6, 0x63, 0x95, 0x23, 0x0B,
// #Blob
0x00, 0x02, 0x01, 0x02
}, heaps.ToArray());
Assert.Throws<ArgumentNullException>(() => mdBuilder.GetOrAddString(null));
}
[Fact]
public void Heaps_Reserve()
{
var mdBuilder = new MetadataBuilder();
var guid = mdBuilder.ReserveGuid();
var us = mdBuilder.ReserveUserString(3);
Assert.Equal(MetadataTokens.GuidHandle(1), guid.Handle);
Assert.Equal(MetadataTokens.UserStringHandle(1), us.Handle);
var serialized = mdBuilder.GetSerializedMetadata(MetadataRootBuilder.EmptyRowCounts, 12, isStandaloneDebugMetadata: false);
var builder = new BlobBuilder();
mdBuilder.WriteHeapsTo(builder, serialized.StringHeap);
AssertEx.Equal(new byte[]
{
// #String
0x00, 0x00, 0x00, 0x00,
// #US
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// #Guid
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
// #Blob
0x00, 0x00, 0x00, 0x00
}, builder.ToArray());
guid.CreateWriter().WriteGuid(new Guid("D39F3559-476A-4D1E-B6D2-88E66395230B"));
us.CreateWriter().WriteUserString("bar");
AssertEx.Equal(new byte[]
{
// #String
0x00, 0x00, 0x00, 0x00,
// #US
0x00, 0x07, 0x62, 0x00, 0x61, 0x00, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00,
// #Guid
0x59, 0x35, 0x9F, 0xD3, 0x6A, 0x47, 0x1E, 0x4D, 0xB6, 0xD2, 0x88, 0xE6, 0x63, 0x95, 0x23, 0x0B,
// #Blob
0x00, 0x00, 0x00, 0x00
}, builder.ToArray());
}
[Fact, ActiveIssue("https://github.com/dotnet/roslyn/issues/9852")]
public void HeapOverflow_UserString()
{
string veryLargeString = new string('x', 0x00fffff0 / 2);
var builder1 = new MetadataBuilder();
Assert.Equal(0x70000001, MetadataTokens.GetToken(builder1.GetOrAddUserString(veryLargeString)));
// TODO: https://github.com/dotnet/roslyn/issues/9852
// Should throw: Assert.Throws<ImageFormatLimitationException>(() => builder1.GetOrAddUserString("123"));
// Assert.Equal(0x70fffff6, MetadataTokens.GetToken(builder1.GetOrAddUserString("12")));
// Assert.Equal(0x70fffff6, MetadataTokens.GetToken(builder1.GetOrAddUserString("12")));
Assert.Equal(0x70fffff6, MetadataTokens.GetToken(builder1.GetOrAddUserString(veryLargeString + "z")));
Assert.Throws<ImageFormatLimitationException>(() => builder1.GetOrAddUserString("12"));
var builder2 = new MetadataBuilder();
Assert.Equal(0x70000001, MetadataTokens.GetToken(builder2.GetOrAddUserString("123")));
Assert.Equal(0x70000009, MetadataTokens.GetToken(builder2.GetOrAddUserString(veryLargeString)));
Assert.Equal(0x70fffffe, MetadataTokens.GetToken(builder2.GetOrAddUserString("4"))); // TODO: should throw https://github.com/dotnet/roslyn/issues/9852
var builder3 = new MetadataBuilder(userStringHeapStartOffset: 0x00fffffe);
Assert.Equal(0x70ffffff, MetadataTokens.GetToken(builder3.GetOrAddUserString("1"))); // TODO: should throw https://github.com/dotnet/roslyn/issues/9852
var builder4 = new MetadataBuilder(userStringHeapStartOffset: 0x00fffff7);
Assert.Equal(0x70fffff8, MetadataTokens.GetToken(builder4.GetOrAddUserString("1"))); // 4B
Assert.Equal(0x70fffffc, MetadataTokens.GetToken(builder4.GetOrAddUserString("2"))); // 4B
Assert.Throws<ImageFormatLimitationException>(() => builder4.GetOrAddUserString("3")); // hits the limit exactly
var builder5 = new MetadataBuilder(userStringHeapStartOffset: 0x00fffff8);
Assert.Equal(0x70fffff9, MetadataTokens.GetToken(builder5.GetOrAddUserString("1"))); // 4B
Assert.Equal(0x70fffffd, MetadataTokens.GetToken(builder5.GetOrAddUserString("2"))); // 4B // TODO: should throw https://github.com/dotnet/roslyn/issues/9852
}
// TODO: test overflow of other heaps, tables
[Fact]
public void SetCapacity()
{
var builder = new MetadataBuilder();
builder.GetOrAddString("11111");
builder.GetOrAddGuid(Guid.NewGuid());
builder.GetOrAddBlobUTF8("2222");
builder.GetOrAddUserString("3333");
builder.AddMethodDefinition(0, 0, default(StringHandle), default(BlobHandle), 0, default(ParameterHandle));
builder.AddMethodDefinition(0, 0, default(StringHandle), default(BlobHandle), 0, default(ParameterHandle));
builder.AddMethodDefinition(0, 0, default(StringHandle), default(BlobHandle), 0, default(ParameterHandle));
builder.SetCapacity(TableIndex.MethodDef, 0);
builder.SetCapacity(TableIndex.MethodDef, 1);
builder.SetCapacity(TableIndex.MethodDef, 1000);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.SetCapacity(TableIndex.MethodDef, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.SetCapacity((TableIndex)0xff, 10));
builder.SetCapacity(HeapIndex.String, 3);
builder.SetCapacity(HeapIndex.String, 1000);
builder.SetCapacity(HeapIndex.Blob, 3);
builder.SetCapacity(HeapIndex.Blob, 1000);
builder.SetCapacity(HeapIndex.Guid, 3);
builder.SetCapacity(HeapIndex.Guid, 1000);
builder.SetCapacity(HeapIndex.UserString, 3);
builder.SetCapacity(HeapIndex.UserString, 1000);
builder.SetCapacity(HeapIndex.String, 0);
Assert.Throws<ArgumentOutOfRangeException>(() => builder.SetCapacity(HeapIndex.String, -1));
Assert.Throws<ArgumentOutOfRangeException>(() => builder.SetCapacity((HeapIndex)0xff, 10));
}
[Fact]
public void ValidateClassLayoutTable()
{
var builder = new MetadataBuilder();
builder.AddTypeLayout(MetadataTokens.TypeDefinitionHandle(2), 1, 1);
builder.AddTypeLayout(MetadataTokens.TypeDefinitionHandle(1), 1, 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddTypeLayout(MetadataTokens.TypeDefinitionHandle(1), 1, 1);
builder.AddTypeLayout(MetadataTokens.TypeDefinitionHandle(1), 1, 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateFieldLayoutTable()
{
var builder = new MetadataBuilder();
builder.AddFieldLayout(MetadataTokens.FieldDefinitionHandle(2), 1);
builder.AddFieldLayout(MetadataTokens.FieldDefinitionHandle(1), 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddFieldLayout(MetadataTokens.FieldDefinitionHandle(1), 1);
builder.AddFieldLayout(MetadataTokens.FieldDefinitionHandle(1), 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateFieldRvaTable()
{
var builder = new MetadataBuilder();
builder.AddFieldRelativeVirtualAddress(MetadataTokens.FieldDefinitionHandle(2), 1);
builder.AddFieldRelativeVirtualAddress(MetadataTokens.FieldDefinitionHandle(1), 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddFieldRelativeVirtualAddress(MetadataTokens.FieldDefinitionHandle(1), 1);
builder.AddFieldRelativeVirtualAddress(MetadataTokens.FieldDefinitionHandle(1), 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateGenericParamTable()
{
var builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(2), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(2), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(2), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(2), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 1);
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameter(MetadataTokens.MethodDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
builder.AddGenericParameter(MetadataTokens.TypeDefinitionHandle(1), default(GenericParameterAttributes), default(StringHandle), index: 0);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateGenericParamConstaintTable()
{
var builder = new MetadataBuilder();
builder.AddGenericParameterConstraint(MetadataTokens.GenericParameterHandle(2), default(TypeDefinitionHandle));
builder.AddGenericParameterConstraint(MetadataTokens.GenericParameterHandle(1), default(TypeDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddGenericParameterConstraint(MetadataTokens.GenericParameterHandle(1), default(TypeDefinitionHandle));
builder.AddGenericParameterConstraint(MetadataTokens.GenericParameterHandle(1), default(TypeDefinitionHandle));
builder.ValidateOrder(); // ok
}
[Fact]
public void ValidateImplMapTable()
{
var builder = new MetadataBuilder();
builder.AddMethodImport(MetadataTokens.MethodDefinitionHandle(2), default(MethodImportAttributes), default(StringHandle), default(ModuleReferenceHandle));
builder.AddMethodImport(MetadataTokens.MethodDefinitionHandle(1), default(MethodImportAttributes), default(StringHandle), default(ModuleReferenceHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddMethodImport(MetadataTokens.MethodDefinitionHandle(1), default(MethodImportAttributes), default(StringHandle), default(ModuleReferenceHandle));
builder.AddMethodImport(MetadataTokens.MethodDefinitionHandle(1), default(MethodImportAttributes), default(StringHandle), default(ModuleReferenceHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateInterfaceImplTable()
{
var builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(2), MetadataTokens.TypeDefinitionHandle(1));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(2));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeReferenceHandle(2));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeReferenceHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeSpecificationHandle(2));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeSpecificationHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeReferenceHandle(1));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeSpecificationHandle(1));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeReferenceHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeSpecificationHandle(1));
builder.AddInterfaceImplementation(MetadataTokens.TypeDefinitionHandle(1), MetadataTokens.TypeDefinitionHandle(1));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateMethodImplTable()
{
var builder = new MetadataBuilder();
builder.AddMethodImplementation(MetadataTokens.TypeDefinitionHandle(2), default(MethodDefinitionHandle), default(MethodDefinitionHandle));
builder.AddMethodImplementation(MetadataTokens.TypeDefinitionHandle(1), default(MethodDefinitionHandle), default(MethodDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddMethodImplementation(MetadataTokens.TypeDefinitionHandle(1), default(MethodDefinitionHandle), default(MethodDefinitionHandle));
builder.AddMethodImplementation(MetadataTokens.TypeDefinitionHandle(1), default(MethodDefinitionHandle), default(MethodDefinitionHandle));
builder.ValidateOrder(); // ok
}
[Fact]
public void ValidateNestedClassTable()
{
var builder = new MetadataBuilder();
builder.AddNestedType(MetadataTokens.TypeDefinitionHandle(2), default(TypeDefinitionHandle));
builder.AddNestedType(MetadataTokens.TypeDefinitionHandle(1), default(TypeDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddNestedType(MetadataTokens.TypeDefinitionHandle(1), default(TypeDefinitionHandle));
builder.AddNestedType(MetadataTokens.TypeDefinitionHandle(1), default(TypeDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
[Fact]
public void ValidateLocalScopeTable()
{
var builder = new MetadataBuilder();
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(2), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 1, length: 1);
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 2);
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
builder.AddLocalScope(MetadataTokens.MethodDefinitionHandle(1), default(ImportScopeHandle), default(LocalVariableHandle), default(LocalConstantHandle), startOffset: 0, length: 1);
builder.ValidateOrder(); // ok
}
[Fact]
public void ValidateStateMachineMethodTable()
{
var builder = new MetadataBuilder();
builder.AddStateMachineMethod(MetadataTokens.MethodDefinitionHandle(2), default(MethodDefinitionHandle));
builder.AddStateMachineMethod(MetadataTokens.MethodDefinitionHandle(1), default(MethodDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
builder = new MetadataBuilder();
builder.AddStateMachineMethod(MetadataTokens.MethodDefinitionHandle(1), default(MethodDefinitionHandle));
builder.AddStateMachineMethod(MetadataTokens.MethodDefinitionHandle(1), default(MethodDefinitionHandle));
Assert.Throws<InvalidOperationException>(() => builder.ValidateOrder());
}
}
}
| |
// <copyright file="LinearAlgebraProviderTests.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
//
// Copyright (c) 2009-2016 Math.NET
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using System;
using System.Collections.Generic;
using MathNet.Numerics.Distributions;
using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Complex;
using MathNet.Numerics.LinearAlgebra.Factorization;
using MathNet.Numerics.Providers.LinearAlgebra;
using NUnit.Framework;
namespace MathNet.Numerics.UnitTests.Providers.LinearAlgebra.Complex
{
#if NOSYSNUMERICS
using Complex = Numerics.Complex;
#else
using Complex = System.Numerics.Complex;
#endif
/// <summary>
/// Base class for linear algebra provider tests.
/// </summary>
[TestFixture, Category("LAProvider")]
public class LinearAlgebraProviderTests
{
/// <summary>
/// The Y Complex test vector.
/// </summary>
readonly Complex[] _y = {new Complex(1.1, 0), 2.2, 3.3, 4.4, 5.5};
/// <summary>
/// The X Complex test vector.
/// </summary>
readonly Complex[] _x = {new Complex(6.6, 0), 7.7, 8.8, 9.9, 10.1};
static readonly IContinuousDistribution Dist = new Normal();
/// <summary>
/// Test matrix to use.
/// </summary>
readonly IDictionary<string, DenseMatrix> _matrices = new Dictionary<string, DenseMatrix>
{
{"Singular3x3", DenseMatrix.OfArray(new[,] {{new Complex(1.0, 0), 1.0, 2.0}, {1.0, 1.0, 2.0}, {1.0, 1.0, 2.0}})},
{"Square3x3", DenseMatrix.OfArray(new[,] {{new Complex(-1.1, 0), -2.2, -3.3}, {0.0, 1.1, 2.2}, {-4.4, 5.5, 6.6}})},
{"Square4x4", DenseMatrix.OfArray(new[,] {{new Complex(-1.1, 0), -2.2, -3.3, -4.4}, {0.0, 1.1, 2.2, 3.3}, {1.0, 2.1, 6.2, 4.3}, {-4.4, 5.5, 6.6, -7.7}})},
{"Singular4x4", DenseMatrix.OfArray(new[,] {{new Complex(-1.1, 0), -2.2, -3.3, -4.4}, {-1.1, -2.2, -3.3, -4.4}, {-1.1, -2.2, -3.3, -4.4}, {-1.1, -2.2, -3.3, -4.4}})},
{"Tall3x2", DenseMatrix.OfArray(new[,] {{new Complex(-1.1, 0), -2.2}, {0.0, 1.1}, {-4.4, 5.5}})},
{"Wide2x3", DenseMatrix.OfArray(new[,] {{new Complex(-1.1, 0), -2.2, -3.3}, {0.0, 1.1, 2.2}})},
{"Tall50000x10", DenseMatrix.CreateRandom(50000, 10, Dist)},
{"Wide10x50000", DenseMatrix.CreateRandom(10, 50000, Dist)},
{"Square1000x1000", DenseMatrix.CreateRandom(1000, 1000, Dist)}
};
/// <summary>
/// Can add a vector to scaled vector
/// </summary>
[Test]
public void CanAddVectorToScaledVectorComplex()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.AddVectorToScaledVector(_y, 0, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.AddVectorToScaledVector(result, 1, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i] + _x[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.AddVectorToScaledVector(result, Math.PI, _x, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i] + (Math.PI*_x[i]), result[i]);
}
}
/// <summary>
/// Can scale an array.
/// </summary>
[Test]
public void CanScaleArray()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.ScaleArray(1, _y, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i], result[i]);
}
Array.Copy(_y, result, _y.Length);
Control.LinearAlgebraProvider.ScaleArray(Math.PI, result, result);
for (var i = 0; i < _y.Length; i++)
{
Assert.AreEqual(_y[i]*Math.PI, result[i]);
}
}
/// <summary>
/// Can compute the dot product.
/// </summary>
[Test]
public void CanComputeDotProduct()
{
var result = Control.LinearAlgebraProvider.DotProduct(_x, _y);
AssertHelpers.AlmostEqualRelative(152.35, result, 15);
}
/// <summary>
/// Can add two arrays.
/// </summary>
[Test]
public void CanAddArrays()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.AddArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i] + _y[i], result[i]);
}
}
/// <summary>
/// Can subtract two arrays.
/// </summary>
[Test]
public void CanSubtractArrays()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.SubtractArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i] - _y[i], result[i]);
}
}
/// <summary>
/// Can pointwise multiply two arrays.
/// </summary>
[Test]
public void CanPointWiseMultiplyArrays()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.PointWiseMultiplyArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i]*_y[i], result[i]);
}
}
/// <summary>
/// Can pointwise divide two arrays.
/// </summary>
[Test]
public void CanPointWiseDivideArrays()
{
var result = new Complex[_y.Length];
Control.LinearAlgebraProvider.PointWiseDivideArrays(_x, _y, result);
for (var i = 0; i < result.Length; i++)
{
Assert.AreEqual(_x[i]/_y[i], result[i]);
}
}
/// <summary>
/// Can compute L1 norm.
/// </summary>
[Test]
public void CanComputeMatrixL1Norm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.OneNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
AssertHelpers.AlmostEqualRelative(12.1, norm, 6);
}
/// <summary>
/// Can compute Frobenius norm.
/// </summary>
[Test]
public void CanComputeMatrixFrobeniusNorm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.FrobeniusNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
AssertHelpers.AlmostEqualRelative(10.777754868246, norm, 8);
}
/// <summary>
/// Can compute Infinity norm.
/// </summary>
[Test]
public void CanComputeMatrixInfinityNorm()
{
var matrix = _matrices["Square3x3"];
var norm = Control.LinearAlgebraProvider.MatrixNorm(Norm.InfinityNorm, matrix.RowCount, matrix.ColumnCount, matrix.Values);
Assert.AreEqual(16.5, norm);
}
/// <summary>
/// Can multiply two square matrices.
/// </summary>
[Test]
public void CanMultiplySquareMatrices()
{
var x = _matrices["Singular3x3"];
var y = _matrices["Square3x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a wide and tall matrix.
/// </summary>
[Test]
public void CanMultiplyWideAndTallMatrices()
{
var x = _matrices["Wide2x3"];
var y = _matrices["Tall3x2"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a tall and wide matrix.
/// </summary>
[Test]
public void CanMultiplyTallAndWideMatrices()
{
var x = _matrices["Tall3x2"];
var y = _matrices["Wide2x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiply(x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply two square matrices.
/// </summary>
[Test]
public void CanMultiplySquareMatricesWithUpdate()
{
var x = _matrices["Singular3x3"];
var y = _matrices["Square3x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a wide and tall matrix.
/// </summary>
[Test]
public void CanMultiplyWideAndTallMatricesWithUpdate()
{
var x = _matrices["Wide2x3"];
var y = _matrices["Tall3x2"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can multiply a tall and wide matrix.
/// </summary>
[Test]
public void CanMultiplyTallAndWideMatricesWithUpdate()
{
var x = _matrices["Tall3x2"];
var y = _matrices["Wide2x3"];
var c = new DenseMatrix(x.RowCount, y.ColumnCount);
Control.LinearAlgebraProvider.MatrixMultiplyWithUpdate(Transpose.DontTranspose, Transpose.DontTranspose, 2.2, x.Values, x.RowCount, x.ColumnCount, y.Values, y.RowCount, y.ColumnCount, 1.0, c.Values);
for (var i = 0; i < c.RowCount; i++)
{
for (var j = 0; j < c.ColumnCount; j++)
{
AssertHelpers.AlmostEqualRelative(2.2*x.Row(i)*y.Column(j), c[i, j], 14);
}
}
}
/// <summary>
/// Can compute the LU factor of a matrix.
/// </summary>
[Test]
public void CanComputeLuFactor()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
AssertHelpers.AlmostEqualRelative(a[0], -4.4, 15);
AssertHelpers.AlmostEqualRelative(a[1], 0.25, 15);
AssertHelpers.AlmostEqualRelative(a[2], 0, 15);
AssertHelpers.AlmostEqualRelative(a[3], 5.5, 15);
AssertHelpers.AlmostEqualRelative(a[4], -3.575, 15);
AssertHelpers.AlmostEqualRelative(a[5], -0.307692307692308, 14);
AssertHelpers.AlmostEqualRelative(a[6], 6.6, 15);
AssertHelpers.AlmostEqualRelative(a[7], -4.95, 14);
AssertHelpers.AlmostEqualRelative(a[8], 0.676923076923077, 14);
Assert.AreEqual(ipiv[0], 2);
Assert.AreEqual(ipiv[1], 2);
Assert.AreEqual(ipiv[2], 2);
}
/// <summary>
/// Can compute the inverse of a matrix using LU factorization.
/// </summary>
[Test]
public void CanComputeLuInverse()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
Control.LinearAlgebraProvider.LUInverse(a, matrix.RowCount);
AssertHelpers.AlmostEqualRelative(a[0], -0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[1], -0.909090909090908, 13);
AssertHelpers.AlmostEqualRelative(a[2], 0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[3], -0.340909090909090, 13);
AssertHelpers.AlmostEqualRelative(a[4], -2.045454545454543, 13);
AssertHelpers.AlmostEqualRelative(a[5], 1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(a[6], -0.113636363636364, 13);
AssertHelpers.AlmostEqualRelative(a[7], 0.227272727272727, 13);
AssertHelpers.AlmostEqualRelative(a[8], -0.113636363636364, 13);
}
/// <summary>
/// Can compute the inverse of a matrix using LU factorization
/// using a previously factored matrix.
/// </summary>
[Test]
public void CanComputeLuInverseOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
Control.LinearAlgebraProvider.LUInverseFactored(a, matrix.RowCount, ipiv);
AssertHelpers.AlmostEqualRelative(a[0], -0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[1], -0.909090909090908, 13);
AssertHelpers.AlmostEqualRelative(a[2], 0.454545454545454, 13);
AssertHelpers.AlmostEqualRelative(a[3], -0.340909090909090, 13);
AssertHelpers.AlmostEqualRelative(a[4], -2.045454545454543, 13);
AssertHelpers.AlmostEqualRelative(a[5], 1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(a[6], -0.113636363636364, 13);
AssertHelpers.AlmostEqualRelative(a[7], 0.227272727272727, 13);
AssertHelpers.AlmostEqualRelative(a[8], -0.113636363636364, 13);
}
/// <summary>
/// Can solve Ax=b using LU factorization.
/// </summary>
[Test]
public void CanSolveUsingLU()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.LUSolve(2, a, matrix.RowCount, b);
AssertHelpers.AlmostEqualRelative(b[0], -1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(b[1], -4.318181818181815, 13);
AssertHelpers.AlmostEqualRelative(b[2], 3.068181818181816, 13);
AssertHelpers.AlmostEqualRelative(b[3], -4.204545454545451, 13);
AssertHelpers.AlmostEqualRelative(b[4], -12.499999999999989, 13);
AssertHelpers.AlmostEqualRelative(b[5], 8.522727272727266, 13);
NotModified(matrix.RowCount, matrix.ColumnCount, a, matrix);
}
/// <summary>
/// Can solve Ax=b using LU factorization using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingLUOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.RowCount];
Array.Copy(matrix.Values, a, a.Length);
var ipiv = new int[matrix.RowCount];
Control.LinearAlgebraProvider.LUFactor(a, matrix.RowCount, ipiv);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.LUSolveFactored(2, a, matrix.RowCount, ipiv, b);
AssertHelpers.AlmostEqualRelative(b[0], -1.477272727272726, 13);
AssertHelpers.AlmostEqualRelative(b[1], -4.318181818181815, 13);
AssertHelpers.AlmostEqualRelative(b[2], 3.068181818181816, 13);
AssertHelpers.AlmostEqualRelative(b[3], -4.204545454545451, 13);
AssertHelpers.AlmostEqualRelative(b[4], -12.499999999999989, 13);
AssertHelpers.AlmostEqualRelative(b[5], 8.522727272727266, 13);
}
/// <summary>
/// Can compute the <c>Cholesky</c> factorization.
/// </summary>
[Test]
public void CanComputeCholeskyFactor()
{
var matrix = new Complex[] {1, 1, 1, 1, 1, 5, 5, 5, 1, 5, 14, 14, 1, 5, 14, 15};
Control.LinearAlgebraProvider.CholeskyFactor(matrix, 4);
Assert.AreEqual(matrix[0].Real, 1);
Assert.AreEqual(matrix[1].Real, 1);
Assert.AreEqual(matrix[2].Real, 1);
Assert.AreEqual(matrix[3].Real, 1);
Assert.AreEqual(matrix[4].Real, 0);
Assert.AreEqual(matrix[5].Real, 2);
Assert.AreEqual(matrix[6].Real, 2);
Assert.AreEqual(matrix[7].Real, 2);
Assert.AreEqual(matrix[8].Real, 0);
Assert.AreEqual(matrix[9].Real, 0);
Assert.AreEqual(matrix[10].Real, 3);
Assert.AreEqual(matrix[11].Real, 3);
Assert.AreEqual(matrix[12].Real, 0);
Assert.AreEqual(matrix[13].Real, 0);
Assert.AreEqual(matrix[14].Real, 0);
Assert.AreEqual(matrix[15].Real, 1);
}
/// <summary>
/// Can solve Ax=b using Cholesky factorization.
/// </summary>
[Test]
public void CanSolveUsingCholesky()
{
var matrix = new DenseMatrix(3, 3, new Complex[] {1, 1, 1, 1, 2, 3, 1, 3, 6});
var a = new Complex[] {1, 1, 1, 1, 2, 3, 1, 3, 6};
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.CholeskySolve(a, 3, b, 2);
AssertHelpers.AlmostEqualRelative(b[0], 0, 14);
AssertHelpers.AlmostEqualRelative(b[1], 1, 14);
AssertHelpers.AlmostEqualRelative(b[2], 0, 14);
AssertHelpers.AlmostEqualRelative(b[3], 3, 14);
AssertHelpers.AlmostEqualRelative(b[4], 1, 14);
AssertHelpers.AlmostEqualRelative(b[5], 0, 14);
NotModified(3, 3, a, matrix);
}
/// <summary>
/// Can solve Ax=b using LU factorization using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingCholeskyOnFactoredMatrix()
{
var a = new Complex[] {1, 1, 1, 1, 2, 3, 1, 3, 6};
Control.LinearAlgebraProvider.CholeskyFactor(a, 3);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
Control.LinearAlgebraProvider.CholeskySolveFactored(a, 3, b, 2);
AssertHelpers.AlmostEqualRelative(b[0], 0, 14);
AssertHelpers.AlmostEqualRelative(b[1], 1, 14);
AssertHelpers.AlmostEqualRelative(b[2], 0, 14);
AssertHelpers.AlmostEqualRelative(b[3], 3, 14);
AssertHelpers.AlmostEqualRelative(b[4], 1, 14);
AssertHelpers.AlmostEqualRelative(b[5], 0, 14);
}
/// <summary>
/// Can compute QR factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeQRFactorSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var r = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new Complex[3];
var q = new Complex[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mq = new DenseMatrix(matrix.RowCount, matrix.RowCount, q);
var mr = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute QR factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeQRFactorTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var r = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new Complex[3];
var q = new Complex[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mr = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var mq = new DenseMatrix(matrix.RowCount, matrix.RowCount, q);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute QR factorization of a wide matrix.
/// </summary>
[Test]
public void CanComputeQRFactorWideMatrix()
{
var matrix = _matrices["Wide2x3"];
var r = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, r, r.Length);
var tau = new Complex[3];
var q = new Complex[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(r, matrix.RowCount, matrix.ColumnCount, q, tau);
var mr = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, r).UpperTriangle();
var mq = new DenseMatrix(matrix.RowCount, matrix.RowCount, q);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute thin QR factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeThinQRFactorSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var r = new Complex[matrix.ColumnCount*matrix.ColumnCount];
var tau = new Complex[3];
var q = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, q, q.Length);
Control.LinearAlgebraProvider.ThinQRFactor(q, matrix.RowCount, matrix.ColumnCount, r, tau);
var mq = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, q);
var mr = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, r);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can compute thin QR factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeThinQRFactorTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var r = new Complex[matrix.ColumnCount*matrix.ColumnCount];
var tau = new Complex[3];
var q = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, q, q.Length);
Control.LinearAlgebraProvider.ThinQRFactor(q, matrix.RowCount, matrix.ColumnCount, r, tau);
var mq = new DenseMatrix(matrix.RowCount, matrix.ColumnCount, q);
var mr = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, r);
var a = mq*mr;
for (var row = 0; row < matrix.RowCount; row++)
{
for (var col = 0; col < matrix.ColumnCount; col++)
{
AssertHelpers.AlmostEqualRelative(matrix[row, col], a[row, col], 14);
}
}
}
/// <summary>
/// Can solve Ax=b using QR factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 3, a, matrix);
var mx = new DenseMatrix(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using QR factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 2, a, matrix);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using QR factorization with a tall A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingQRTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new Complex[matrix.ColumnCount];
var q = new Complex[matrix.RowCount*matrix.RowCount];
Control.LinearAlgebraProvider.QRFactor(a, matrix.RowCount, matrix.ColumnCount, q, tau);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(q, a, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, QRMethod.Thin);
NotModified(3, 3, a, matrix);
var mx = new DenseMatrix(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x, QRMethod.Thin);
NotModified(3, 2, a, matrix);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a square A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRSquareMatrixOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new Complex[matrix.ColumnCount];
var r = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.ThinQRFactor(a, matrix.RowCount, matrix.ColumnCount, r, tau);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(a, r, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x, QRMethod.Thin);
var mx = new DenseMatrix(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqualRelative(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqualRelative(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqualRelative(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqualRelative(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using thin QR factorization with a tall A matrix
/// using a factored A matrix.
/// </summary>
[Test]
public void CanSolveUsingThinQRTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var tau = new Complex[matrix.ColumnCount];
var r = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.ThinQRFactor(a, matrix.RowCount, matrix.ColumnCount, r, tau);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.QRSolveFactored(a, r, matrix.RowCount, matrix.ColumnCount, tau, b, 2, x, QRMethod.Thin);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqualRelative(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqualRelative(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqualRelative(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqualRelative(test[1, 1], x[3], 13);
}
/// <summary>
/// Can compute the SVD factorization of a square matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new Complex[matrix.RowCount];
var u = new Complex[matrix.RowCount*matrix.RowCount];
var vt = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = new DenseMatrix(matrix.RowCount, matrix.RowCount, u);
var mV = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 13);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 13);
AssertHelpers.AlmostEqualRelative(matrix[2, 0], result[2, 0], 13);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 13);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 13);
AssertHelpers.AlmostEqualRelative(matrix[2, 1], result[2, 1], 13);
AssertHelpers.AlmostEqualRelative(matrix[0, 2], result[0, 2], 13);
AssertHelpers.AlmostEqualRelative(matrix[1, 2], result[1, 2], 13);
AssertHelpers.AlmostEqualRelative(matrix[2, 2], result[2, 2], 13);
}
/// <summary>
/// Can compute the SVD factorization of a tall matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new Complex[matrix.ColumnCount];
var u = new Complex[matrix.RowCount*matrix.RowCount];
var vt = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = new DenseMatrix(matrix.RowCount, matrix.RowCount, u);
var mV = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 0], result[2, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[2, 1], result[2, 1], 14);
}
/// <summary>
/// Can compute the SVD factorization of a wide matrix.
/// </summary>
[Test]
public void CanComputeSVDFactorizationOfWideMatrix()
{
var matrix = _matrices["Wide2x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new Complex[matrix.RowCount];
var u = new Complex[matrix.RowCount*matrix.RowCount];
var vt = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var w = new DenseMatrix(matrix.RowCount, matrix.ColumnCount);
for (var index = 0; index < s.Length; index++)
{
w[index, index] = s[index];
}
var mU = new DenseMatrix(matrix.RowCount, matrix.RowCount, u);
var mV = new DenseMatrix(matrix.ColumnCount, matrix.ColumnCount, vt);
var result = mU*w*mV;
AssertHelpers.AlmostEqualRelative(matrix[0, 0], result[0, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 0], result[1, 0], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 1], result[0, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 1], result[1, 1], 14);
AssertHelpers.AlmostEqualRelative(matrix[0, 2], result[0, 2], 14);
AssertHelpers.AlmostEqualRelative(matrix[1, 2], result[1, 2], 14);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a square A matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDSquareMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 3, a, matrix);
var mx = new DenseMatrix(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqual(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqual(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqual(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqual(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqual(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqual(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a tall A matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDTallMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolve(a, matrix.RowCount, matrix.ColumnCount, b, 2, x);
NotModified(3, 2, a, matrix);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqual(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqual(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqual(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqual(test[1, 1], x[3], 13);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a square A matrix
/// using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDSquareMatrixOnFactoredMatrix()
{
var matrix = _matrices["Square3x3"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new Complex[matrix.RowCount];
var u = new Complex[matrix.RowCount*matrix.RowCount];
var vt = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolveFactored(matrix.RowCount, matrix.ColumnCount, s, u, vt, b, 2, x);
var mx = new DenseMatrix(matrix.ColumnCount, 2, x);
var mb = matrix*mx;
AssertHelpers.AlmostEqual(mb[0, 0], b[0], 13);
AssertHelpers.AlmostEqual(mb[1, 0], b[1], 13);
AssertHelpers.AlmostEqual(mb[2, 0], b[2], 13);
AssertHelpers.AlmostEqual(mb[0, 1], b[3], 13);
AssertHelpers.AlmostEqual(mb[1, 1], b[4], 13);
AssertHelpers.AlmostEqual(mb[2, 1], b[5], 13);
}
/// <summary>
/// Can solve Ax=b using SVD factorization with a tall A matrix
/// using a factored matrix.
/// </summary>
[Test]
public void CanSolveUsingSVDTallMatrixOnFactoredMatrix()
{
var matrix = _matrices["Tall3x2"];
var a = new Complex[matrix.RowCount*matrix.ColumnCount];
Array.Copy(matrix.Values, a, a.Length);
var s = new Complex[matrix.ColumnCount];
var u = new Complex[matrix.RowCount*matrix.RowCount];
var vt = new Complex[matrix.ColumnCount*matrix.ColumnCount];
Control.LinearAlgebraProvider.SingularValueDecomposition(true, a, matrix.RowCount, matrix.ColumnCount, s, u, vt);
var b = new[] {new Complex(1.0, 0), 2.0, 3.0, 4.0, 5.0, 6.0};
var x = new Complex[matrix.ColumnCount*2];
Control.LinearAlgebraProvider.SvdSolveFactored(matrix.RowCount, matrix.ColumnCount, s, u, vt, b, 2, x);
var mb = new DenseMatrix(matrix.RowCount, 2, b);
var test = (matrix.Transpose()*matrix).Inverse()*matrix.Transpose()*mb;
AssertHelpers.AlmostEqual(test[0, 0], x[0], 13);
AssertHelpers.AlmostEqual(test[1, 0], x[1], 13);
AssertHelpers.AlmostEqual(test[0, 1], x[2], 13);
AssertHelpers.AlmostEqual(test[1, 1], x[3], 13);
}
[TestCase("Wide10x50000", "Tall50000x10")]
[TestCase("Square1000x1000", "Square1000x1000")]
[Explicit, Timeout(1000*10)]
public void IsMatrixMultiplicationPerformant(string leftMatrixKey, string rightMatrixKey)
{
var leftMatrix = _matrices[leftMatrixKey];
var rightMatrix = _matrices[rightMatrixKey];
var result = leftMatrix*rightMatrix;
Assert.That(result, Is.Not.Null);
}
/// <summary>
/// Checks to see if a matrix and array contain the same values.
/// </summary>
/// <param name="rows">number of rows.</param>
/// <param name="columns">number of columns.</param>
/// <param name="array">array to check.</param>
/// <param name="matrix">matrix to check against.</param>
static void NotModified(int rows, int columns, IList<Complex> array, Matrix<Complex> matrix)
{
var index = 0;
for (var col = 0; col < columns; col++)
{
for (var row = 0; row < rows; row++)
{
Assert.AreEqual(array[index++], matrix[row, col]);
}
}
}
}
}
| |
// 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.Backup
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Azure.Management.RecoveryServices;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackupOperationResultsOperations operations.
/// </summary>
internal partial class BackupOperationResultsOperations : IServiceOperations<RecoveryServicesBackupClient>, IBackupOperationResultsOperations
{
/// <summary>
/// Initializes a new instance of the BackupOperationResultsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal BackupOperationResultsOperations(RecoveryServicesBackupClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the RecoveryServicesBackupClient
/// </summary>
public RecoveryServicesBackupClient Client { get; private set; }
/// <summary>
/// Provides the status of the delete operations such as deleting backed up
/// item. Once the operation has started, the status code in the response would
/// be Accepted. It will continue to be in this state till it reaches
/// completion. On successful completion, the status code will be OK. This
/// method expects OperationID as an argument. OperationID is part of the
/// Location header of the operation response.
/// </summary>
/// <param name='vaultName'>
/// The name of the recovery services vault.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group where the recovery services vault is
/// present.
/// </param>
/// <param name='operationId'>
/// OperationID which represents the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string operationId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (vaultName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "vaultName");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (operationId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "operationId");
}
string apiVersion = "2016-12-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("vaultName", vaultName);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("operationId", operationId);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "Subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.RecoveryServices/vaults/{vaultName}/backupOperationResults/{operationId}").ToString();
_url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName));
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
_url = _url.Replace("{operationId}", System.Uri.EscapeDataString(operationId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202 && (int)_statusCode != 204)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Numerics.Tests
{
public class operation_ComparisonHashCodeTest
{
private static void VerifyComplexComparison(Complex c1, Complex c2, bool expectedResult, bool expectedResultEqual)
{
Assert.True(expectedResult == (c1 == c2), string.Format("c1:{0} == c2{1} is not '{2}' as expected", c1, c2, expectedResult));
Assert.True(expectedResult == (c2 == c1), string.Format("c2:{0} == c1{1} is not '{2}' as expected", c2, c1, expectedResult));
Assert.True(expectedResult != (c1 != c2), string.Format("c1:{0} != c2{1} is not '{2}' as expected", c1, c2, !expectedResult));
Assert.True(expectedResult != (c2 != c1), string.Format("c2:{0} != c1{1} is not '{2}' as expected", c2, c1, !expectedResult));
bool result = c1.Equals(c2);
Assert.True(expectedResultEqual == result, string.Format("c1:{0}.Equals(c2{1}) is not '{2}' as expected", c1, c2, expectedResultEqual));
if (result) // then verify Hash Code equality
{
Assert.True(c1.GetHashCode() == c2.GetHashCode(), string.Format("c1:{0}.GetHashCode() == c2:{1}.GetHashCode() is 'true' as expected", c1, c2));
}
result = c2.Equals(c1);
Assert.True(expectedResultEqual == result, string.Format("c2:{0}.Equals(c1{1}) is not '{2}' as expected", c2, c1, expectedResultEqual));
if (result) // then verify Hash Code equality
{
Assert.True(c2.GetHashCode() == c1.GetHashCode(), string.Format("Obj c2:{0}.GetHashCode() == c1:{1}.GetHashCode() is 'true' as expected", c2, c1));
}
Assert.True(expectedResult == c2.Equals((Object)c1), string.Format("c2:{0}.Equals((object) c1{1}) is not '{2}' as expected", c2, c1, expectedResult));
Assert.True(expectedResult == c1.Equals((Object)c2), string.Format("c1:{0}.Equals((object) c2{1}) is not '{2}' as expected", c1, c2, expectedResult));
}
private static void VerifyComplexComparison(Complex c1, Complex c2, bool expectedResult)
{
VerifyComplexComparison(c1, c2, expectedResult, expectedResult);
}
[Fact]
public static void RunTests_ZeroOneImaginaryOne()
{
double real = Support.GetRandomDoubleValue(false);
double imaginary = Support.GetRandomDoubleValue(false);
Complex randomComplex = new Complex(real, imaginary);
real = Support.GetRandomDoubleValue(true);
imaginary = Support.GetRandomDoubleValue(true);
Complex randomComplexNeg = new Complex(real, imaginary);
real = Support.GetSmallRandomDoubleValue(false);
imaginary = Support.GetSmallRandomDoubleValue(false);
Complex randomSmallComplex = new Complex(real, imaginary);
real = Support.GetSmallRandomDoubleValue(true);
imaginary = Support.GetSmallRandomDoubleValue(true);
Complex randomSmallComplexNeg = new Complex(real, imaginary);
VerifyComplexComparison(Complex.Zero, Complex.Zero, true);
VerifyComplexComparison(Complex.Zero, Complex.One, false);
VerifyComplexComparison(Complex.Zero, -Complex.One, false);
VerifyComplexComparison(Complex.Zero, Complex.ImaginaryOne, false);
VerifyComplexComparison(Complex.Zero, -Complex.ImaginaryOne, false);
VerifyComplexComparison(Complex.Zero, -Complex.ImaginaryOne, false);
bool expectedResult = (randomComplex.Real == 0.0 && randomComplex.Imaginary == 0.0);
VerifyComplexComparison(Complex.Zero, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == 0.0 && randomComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(Complex.Zero, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == 0.0 && randomSmallComplex.Imaginary == 0.0);
VerifyComplexComparison(Complex.Zero, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == 0.0 && randomSmallComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(Complex.Zero, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(Complex.One, Complex.One, true);
VerifyComplexComparison(Complex.One, -Complex.One, false);
VerifyComplexComparison(Complex.One, Complex.ImaginaryOne, false);
VerifyComplexComparison(Complex.One, -Complex.ImaginaryOne, false);
expectedResult = (randomComplex.Real == 1.0 && randomComplex.Imaginary == 0.0);
VerifyComplexComparison(Complex.One, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == 1.0 && randomComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(Complex.One, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == 1.0 && randomSmallComplex.Imaginary == 0.0);
VerifyComplexComparison(Complex.One, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == 1.0 && randomSmallComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(Complex.One, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(-Complex.One, -Complex.One, true);
VerifyComplexComparison(-Complex.One, Complex.ImaginaryOne, false);
VerifyComplexComparison(-Complex.One, -Complex.ImaginaryOne, false);
expectedResult = (randomComplex.Real == -1.0 && randomComplex.Imaginary == 0.0);
VerifyComplexComparison(-Complex.One, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == -1.0 && randomComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(-Complex.One, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == -1.0 && randomSmallComplex.Imaginary == 0.0);
VerifyComplexComparison(-Complex.One, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == -1.0 && randomSmallComplexNeg.Imaginary == 0.0);
VerifyComplexComparison(-Complex.One, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(Complex.ImaginaryOne, Complex.ImaginaryOne, true);
VerifyComplexComparison(Complex.ImaginaryOne, -Complex.ImaginaryOne, false);
expectedResult = (randomComplex.Real == 0.0 && randomComplex.Imaginary == 1.0);
VerifyComplexComparison(Complex.ImaginaryOne, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == 0.0 && randomComplexNeg.Imaginary == 1.0);
VerifyComplexComparison(Complex.ImaginaryOne, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == 0.0 && randomSmallComplex.Imaginary == 1.0);
VerifyComplexComparison(Complex.ImaginaryOne, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == 0.0 && randomSmallComplexNeg.Imaginary == 1.0);
VerifyComplexComparison(Complex.ImaginaryOne, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(-Complex.ImaginaryOne, -Complex.ImaginaryOne, true);
expectedResult = (randomComplex.Real == 0.0 && randomComplex.Imaginary == -1.0);
VerifyComplexComparison(-Complex.ImaginaryOne, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == 0.0 && randomComplexNeg.Imaginary == -1.0);
VerifyComplexComparison(-Complex.ImaginaryOne, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == 0.0 && randomSmallComplex.Imaginary == -1.0);
VerifyComplexComparison(-Complex.ImaginaryOne, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == 0.0 && randomSmallComplexNeg.Imaginary == -1.0);
VerifyComplexComparison(-Complex.ImaginaryOne, randomSmallComplexNeg, expectedResult);
}
[Fact]
public static void RunTests_MaxMinValues()
{
double real = Support.GetRandomDoubleValue(false);
double imaginary = Support.GetRandomDoubleValue(false);
Complex randomComplex = new Complex(real, imaginary);
real = Support.GetRandomDoubleValue(true);
imaginary = Support.GetRandomDoubleValue(true);
Complex randomComplexNeg = new Complex(real, imaginary);
real = Support.GetSmallRandomDoubleValue(false);
imaginary = Support.GetSmallRandomDoubleValue(false);
Complex randomSmallComplex = new Complex(real, imaginary);
real = Support.GetSmallRandomDoubleValue(true);
imaginary = Support.GetSmallRandomDoubleValue(true);
Complex randomSmallComplexNeg = new Complex(real, imaginary);
Complex maxComplex = new Complex(double.MaxValue, double.MaxValue);
Complex minComplex = new Complex(double.MinValue, double.MinValue);
Complex maxReal = new Complex(double.MaxValue, 0.0);
Complex minReal = new Complex(double.MinValue, 0.0);
Complex maxImaginary = new Complex(0.0, double.MaxValue);
Complex minImaginary = new Complex(0.0, double.MinValue);
VerifyComplexComparison(maxComplex, maxComplex, true);
VerifyComplexComparison(maxComplex, minComplex, false);
VerifyComplexComparison(maxComplex, maxReal, false);
VerifyComplexComparison(maxComplex, minReal, false);
VerifyComplexComparison(maxComplex, maxImaginary, false);
VerifyComplexComparison(maxComplex, minImaginary, false);
bool expectedResult = (randomComplex.Real == maxComplex.Real && randomComplex.Imaginary == maxComplex.Imaginary);
VerifyComplexComparison(maxComplex, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == maxComplex.Real && randomComplexNeg.Imaginary == maxComplex.Imaginary);
VerifyComplexComparison(maxComplex, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == maxComplex.Real && randomSmallComplex.Imaginary == maxComplex.Imaginary);
VerifyComplexComparison(maxComplex, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == maxComplex.Real && randomSmallComplexNeg.Imaginary == maxComplex.Imaginary);
VerifyComplexComparison(maxComplex, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(minComplex, minComplex, true);
VerifyComplexComparison(minComplex, maxReal, false);
VerifyComplexComparison(minComplex, maxImaginary, false);
VerifyComplexComparison(minComplex, minImaginary, false);
expectedResult = (randomComplex.Real == minComplex.Real && randomComplex.Imaginary == minComplex.Imaginary);
VerifyComplexComparison(minComplex, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == minComplex.Real && randomComplexNeg.Imaginary == minComplex.Imaginary);
VerifyComplexComparison(minComplex, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == minComplex.Real && randomSmallComplex.Imaginary == minComplex.Imaginary);
VerifyComplexComparison(minComplex, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == minComplex.Real && randomSmallComplexNeg.Imaginary == minComplex.Imaginary);
VerifyComplexComparison(minComplex, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(maxReal, maxReal, true);
VerifyComplexComparison(maxReal, minReal, false);
VerifyComplexComparison(maxReal, maxImaginary, false);
VerifyComplexComparison(maxReal, minImaginary, false);
expectedResult = (randomComplex.Real == maxReal.Real && randomComplex.Imaginary == maxReal.Imaginary);
VerifyComplexComparison(maxReal, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == maxReal.Real && randomComplexNeg.Imaginary == maxReal.Imaginary);
VerifyComplexComparison(maxReal, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == maxReal.Real && randomSmallComplex.Imaginary == maxReal.Imaginary);
VerifyComplexComparison(maxReal, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == maxReal.Real && randomSmallComplexNeg.Imaginary == maxReal.Imaginary);
VerifyComplexComparison(maxReal, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(minReal, minReal, true);
VerifyComplexComparison(minReal, maxImaginary, false);
VerifyComplexComparison(minReal, minImaginary, false);
expectedResult = (randomComplex.Real == minReal.Real && randomComplex.Imaginary == minReal.Imaginary);
VerifyComplexComparison(minReal, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == minReal.Real && randomComplexNeg.Imaginary == minReal.Imaginary);
VerifyComplexComparison(minReal, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == minReal.Real && randomSmallComplex.Imaginary == minReal.Imaginary);
VerifyComplexComparison(minReal, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == minReal.Real && randomSmallComplexNeg.Imaginary == minReal.Imaginary);
VerifyComplexComparison(minReal, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(maxImaginary, maxImaginary, true);
VerifyComplexComparison(maxImaginary, minImaginary, false);
expectedResult = (randomComplex.Real == maxImaginary.Real && randomComplex.Imaginary == maxImaginary.Imaginary);
VerifyComplexComparison(maxImaginary, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == maxImaginary.Real && randomComplexNeg.Imaginary == maxImaginary.Imaginary);
VerifyComplexComparison(maxImaginary, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == maxImaginary.Real && randomSmallComplex.Imaginary == maxImaginary.Imaginary);
VerifyComplexComparison(maxImaginary, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == maxImaginary.Real && randomSmallComplexNeg.Imaginary == maxImaginary.Imaginary);
VerifyComplexComparison(maxImaginary, randomSmallComplexNeg, expectedResult);
VerifyComplexComparison(minImaginary, minImaginary, true);
expectedResult = (randomComplex.Real == minImaginary.Real && randomComplex.Imaginary == minImaginary.Imaginary);
VerifyComplexComparison(minImaginary, randomComplex, expectedResult);
expectedResult = (randomComplexNeg.Real == minImaginary.Real && randomComplexNeg.Imaginary == minImaginary.Imaginary);
VerifyComplexComparison(minImaginary, randomComplexNeg, expectedResult);
expectedResult = (randomSmallComplex.Real == minImaginary.Real && randomSmallComplex.Imaginary == minImaginary.Imaginary);
VerifyComplexComparison(minImaginary, randomSmallComplex, expectedResult);
expectedResult = (randomSmallComplexNeg.Real == minImaginary.Real && randomSmallComplexNeg.Imaginary == minImaginary.Imaginary);
VerifyComplexComparison(minImaginary, randomSmallComplexNeg, expectedResult);
}
[Fact]
public static void RunTests_InvalidValues()
{
double real = Support.GetRandomDoubleValue(false);
double imaginary = Support.GetRandomDoubleValue(false);
Complex randomComplex = new Complex(real, imaginary);
foreach (double imaginaryInvalid in Support.doubleInvalidValues)
{
real = Support.GetRandomDoubleValue(false);
Complex randomInvalidComplex = new Complex(real, imaginaryInvalid);
VerifyComplexComparison(randomInvalidComplex, randomComplex, false);
VerifyComplexComparison(randomInvalidComplex, randomInvalidComplex, !double.IsNaN(imaginaryInvalid), true);
}
foreach (double realInvalid in Support.doubleInvalidValues)
{
imaginary = Support.GetRandomDoubleValue(false);
Complex randomInvalidComplex = new Complex(realInvalid, imaginary);
VerifyComplexComparison(randomInvalidComplex, randomComplex, false);
VerifyComplexComparison(randomInvalidComplex, randomInvalidComplex, !double.IsNaN(realInvalid), true);
}
foreach (double realInvalid in Support.doubleInvalidValues)
{
foreach (double imaginaryInvalid in Support.doubleInvalidValues)
{
Complex randomInvalidComplex = new Complex(realInvalid, imaginaryInvalid);
VerifyComplexComparison(randomInvalidComplex, randomComplex, false);
VerifyComplexComparison(randomInvalidComplex, randomInvalidComplex, !(double.IsNaN(realInvalid) || double.IsNaN(imaginaryInvalid)), true);
}
}
}
[Fact]
public static void RunTests_WithNonComplexObject()
{
// local variables
double real = Support.GetSmallRandomDoubleValue(false);
Complex randomComplex = new Complex(real, 0.0);
// verify with same double value
Assert.False(randomComplex.Equals((Object)real), string.Format("Obj randomComplex:{0}.Equals((object) real) is not 'false' as expected", randomComplex, real));
// verify with null
Assert.False(randomComplex.Equals((Object)null), string.Format("Obj randomComplex:{0}.Equals((object) null) is not 'false' as expected", randomComplex));
// verify with 0
Assert.False(randomComplex.Equals((Object)0), string.Format("Obj randomComplex:{0}.Equals((object) 0) is not 'false' as expected", randomComplex));
// verify with string
Assert.False(randomComplex.Equals((Object)"0"), string.Format("Obj randomComplex:{0}.Equals((object) \"0\") is not 'false' as expected", randomComplex));
}
}
}
| |
/*
* 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.Drawing;
using System.Reflection;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Imaging;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
namespace OpenSim.Region.CoreModules.World.WorldMap
{
public enum DrawRoutine
{
Rectangle,
Polygon,
Ellipse
}
public struct face
{
public Point[] pts;
}
public struct DrawStruct
{
public DrawRoutine dr;
public Rectangle rect;
public SolidBrush brush;
public face[] trns;
}
public class MapImageModule : IMapImageGenerator, IRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Scene m_scene;
private IConfigSource m_config;
private IMapTileTerrainRenderer terrainRenderer;
#region IMapImageGenerator Members
public byte[] WriteJpeg2000Image(string gradientmap)
{
byte[] imageData = null;
bool drawPrimVolume = true;
bool textureTerrain = false;
try
{
IConfig startupConfig = m_config.Configs["Startup"];
drawPrimVolume = startupConfig.GetBoolean("DrawPrimOnMapTile", drawPrimVolume);
textureTerrain = startupConfig.GetBoolean("TextureOnMapTile", textureTerrain);
}
catch
{
m_log.Warn("[MAPTILE]: Failed to load StartupConfig");
}
if (textureTerrain)
{
terrainRenderer = new TexturedMapTileRenderer();
}
else
{
terrainRenderer = new ShadedMapTileRenderer();
}
terrainRenderer.Initialise(m_scene, m_config);
using (Bitmap mapbmp = new Bitmap((int)Constants.RegionSize, (int)Constants.RegionSize))
{
//long t = System.Environment.TickCount;
//for (int i = 0; i < 10; ++i) {
terrainRenderer.TerrainToBitmap(mapbmp);
//}
//t = System.Environment.TickCount - t;
//m_log.InfoFormat("[MAPTILE] generation of 10 maptiles needed {0} ms", t);
if (drawPrimVolume)
{
DrawObjectVolume(m_scene, mapbmp);
}
try
{
imageData = OpenJPEG.EncodeFromImage(mapbmp, true);
}
catch (Exception e) // LEGIT: Catching problems caused by OpenJPEG p/invoke
{
m_log.Error("Failed generating terrain map: " + e);
}
}
return imageData;
}
#endregion
#region IRegionModule Members
public void Initialise(Scene scene, IConfigSource source)
{
m_scene = scene;
m_config = source;
IConfig startupConfig = m_config.Configs["Startup"];
if (startupConfig.GetString("MapImageModule", "MapImageModule") !=
"MapImageModule")
return;
m_scene.RegisterModuleInterface<IMapImageGenerator>(this);
}
public void PostInitialise()
{
}
public void Close()
{
}
public string Name
{
get { return "MapImageModule"; }
}
public bool IsSharedModule
{
get { return false; }
}
#endregion
// TODO: unused:
// private void ShadeBuildings(Bitmap map)
// {
// lock (map)
// {
// lock (m_scene.Entities)
// {
// foreach (EntityBase entity in m_scene.Entities.Values)
// {
// if (entity is SceneObjectGroup)
// {
// SceneObjectGroup sog = (SceneObjectGroup) entity;
//
// foreach (SceneObjectPart primitive in sog.Children.Values)
// {
// int x = (int) (primitive.AbsolutePosition.X - (primitive.Scale.X / 2));
// int y = (int) (primitive.AbsolutePosition.Y - (primitive.Scale.Y / 2));
// int w = (int) primitive.Scale.X;
// int h = (int) primitive.Scale.Y;
//
// int dx;
// for (dx = x; dx < x + w; dx++)
// {
// int dy;
// for (dy = y; dy < y + h; dy++)
// {
// if (x < 0 || y < 0)
// continue;
// if (x >= map.Width || y >= map.Height)
// continue;
//
// map.SetPixel(dx, dy, Color.DarkGray);
// }
// }
// }
// }
// }
// }
// }
// }
private Bitmap DrawObjectVolume(Scene whichScene, Bitmap mapbmp)
{
int tc = 0;
double[,] hm = whichScene.Heightmap.GetDoubles();
tc = Environment.TickCount;
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Object Volume Profile");
List<EntityBase> objs = whichScene.GetEntities();
Dictionary<uint, DrawStruct> z_sort = new Dictionary<uint, DrawStruct>();
//SortedList<float, RectangleDrawStruct> z_sort = new SortedList<float, RectangleDrawStruct>();
List<float> z_sortheights = new List<float>();
List<uint> z_localIDs = new List<uint>();
lock (objs)
{
foreach (EntityBase obj in objs)
{
// Only draw the contents of SceneObjectGroup
if (obj is SceneObjectGroup)
{
SceneObjectGroup mapdot = (SceneObjectGroup)obj;
Color mapdotspot = Color.Gray; // Default color when prim color is white
// Loop over prim in group
foreach (SceneObjectPart part in mapdot.Children.Values)
{
if (part == null)
continue;
// Draw if the object is at least 1 meter wide in any direction
if (part.Scale.X > 1f || part.Scale.Y > 1f || part.Scale.Z > 1f)
{
// Try to get the RGBA of the default texture entry..
//
try
{
// get the null checks out of the way
// skip the ones that break
if (part == null)
continue;
if (part.Shape == null)
continue;
if (part.Shape.PCode == (byte)PCode.Tree || part.Shape.PCode == (byte)PCode.NewTree || part.Shape.PCode == (byte)PCode.Grass)
continue; // eliminates trees from this since we don't really have a good tree representation
// if you want tree blocks on the map comment the above line and uncomment the below line
//mapdotspot = Color.PaleGreen;
if (part.Shape.Textures == null)
continue;
if (part.Shape.Textures.DefaultTexture == null)
continue;
Color4 texcolor = part.Shape.Textures.DefaultTexture.RGBA;
// Not sure why some of these are null, oh well.
int colorr = 255 - (int)(texcolor.R * 255f);
int colorg = 255 - (int)(texcolor.G * 255f);
int colorb = 255 - (int)(texcolor.B * 255f);
if (!(colorr == 255 && colorg == 255 && colorb == 255))
{
//Try to set the map spot color
try
{
// If the color gets goofy somehow, skip it *shakes fist at Color4
mapdotspot = Color.FromArgb(colorr, colorg, colorb);
}
catch (ArgumentException)
{
}
}
}
catch (IndexOutOfRangeException)
{
// Windows Array
}
catch (ArgumentOutOfRangeException)
{
// Mono Array
}
Vector3 pos = part.GetWorldPosition();
// skip prim outside of retion
if (pos.X < 0f || pos.X > 256f || pos.Y < 0f || pos.Y > 256f)
continue;
// skip prim in non-finite position
if (Single.IsNaN(pos.X) || Single.IsNaN(pos.Y) ||
Single.IsInfinity(pos.X) || Single.IsInfinity(pos.Y))
continue;
// Figure out if object is under 256m above the height of the terrain
bool isBelow256AboveTerrain = false;
try
{
isBelow256AboveTerrain = (pos.Z < ((float)hm[(int)pos.X, (int)pos.Y] + 256f));
}
catch (Exception)
{
}
if (isBelow256AboveTerrain)
{
// Translate scale by rotation so scale is represented properly when object is rotated
Vector3 lscale = new Vector3(part.Shape.Scale.X, part.Shape.Scale.Y, part.Shape.Scale.Z);
Vector3 scale = new Vector3();
Vector3 tScale = new Vector3();
Vector3 axPos = new Vector3(pos.X,pos.Y,pos.Z);
Quaternion llrot = part.GetWorldRotation();
Quaternion rot = new Quaternion(llrot.W, llrot.X, llrot.Y, llrot.Z);
scale = lscale * rot;
// negative scales don't work in this situation
scale.X = Math.Abs(scale.X);
scale.Y = Math.Abs(scale.Y);
scale.Z = Math.Abs(scale.Z);
// This scaling isn't very accurate and doesn't take into account the face rotation :P
int mapdrawstartX = (int)(pos.X - scale.X);
int mapdrawstartY = (int)(pos.Y - scale.Y);
int mapdrawendX = (int)(pos.X + scale.X);
int mapdrawendY = (int)(pos.Y + scale.Y);
// If object is beyond the edge of the map, don't draw it to avoid errors
if (mapdrawstartX < 0 || mapdrawstartX > ((int)Constants.RegionSize - 1) || mapdrawendX < 0 || mapdrawendX > ((int)Constants.RegionSize - 1)
|| mapdrawstartY < 0 || mapdrawstartY > ((int)Constants.RegionSize - 1) || mapdrawendY < 0
|| mapdrawendY > ((int)Constants.RegionSize - 1))
continue;
#region obb face reconstruction part duex
Vector3[] vertexes = new Vector3[8];
// float[] distance = new float[6];
Vector3[] FaceA = new Vector3[6]; // vertex A for Facei
Vector3[] FaceB = new Vector3[6]; // vertex B for Facei
Vector3[] FaceC = new Vector3[6]; // vertex C for Facei
Vector3[] FaceD = new Vector3[6]; // vertex D for Facei
tScale = new Vector3(lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[0] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[0].x = pos.X + vertexes[0].x;
//vertexes[0].y = pos.Y + vertexes[0].y;
//vertexes[0].z = pos.Z + vertexes[0].z;
FaceA[0] = vertexes[0];
FaceB[3] = vertexes[0];
FaceA[4] = vertexes[0];
tScale = lscale;
scale = ((tScale * rot));
vertexes[1] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[1].x = pos.X + vertexes[1].x;
// vertexes[1].y = pos.Y + vertexes[1].y;
//vertexes[1].z = pos.Z + vertexes[1].z;
FaceB[0] = vertexes[1];
FaceA[1] = vertexes[1];
FaceC[4] = vertexes[1];
tScale = new Vector3(lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[2] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[2].x = pos.X + vertexes[2].x;
//vertexes[2].y = pos.Y + vertexes[2].y;
//vertexes[2].z = pos.Z + vertexes[2].z;
FaceC[0] = vertexes[2];
FaceD[3] = vertexes[2];
FaceC[5] = vertexes[2];
tScale = new Vector3(lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[3] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
//vertexes[3].x = pos.X + vertexes[3].x;
// vertexes[3].y = pos.Y + vertexes[3].y;
// vertexes[3].z = pos.Z + vertexes[3].z;
FaceD[0] = vertexes[3];
FaceC[1] = vertexes[3];
FaceA[5] = vertexes[3];
tScale = new Vector3(-lscale.X, lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[4] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[4].x = pos.X + vertexes[4].x;
// vertexes[4].y = pos.Y + vertexes[4].y;
// vertexes[4].z = pos.Z + vertexes[4].z;
FaceB[1] = vertexes[4];
FaceA[2] = vertexes[4];
FaceD[4] = vertexes[4];
tScale = new Vector3(-lscale.X, lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[5] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[5].x = pos.X + vertexes[5].x;
// vertexes[5].y = pos.Y + vertexes[5].y;
// vertexes[5].z = pos.Z + vertexes[5].z;
FaceD[1] = vertexes[5];
FaceC[2] = vertexes[5];
FaceB[5] = vertexes[5];
tScale = new Vector3(-lscale.X, -lscale.Y, lscale.Z);
scale = ((tScale * rot));
vertexes[6] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[6].x = pos.X + vertexes[6].x;
// vertexes[6].y = pos.Y + vertexes[6].y;
// vertexes[6].z = pos.Z + vertexes[6].z;
FaceB[2] = vertexes[6];
FaceA[3] = vertexes[6];
FaceB[4] = vertexes[6];
tScale = new Vector3(-lscale.X, -lscale.Y, -lscale.Z);
scale = ((tScale * rot));
vertexes[7] = (new Vector3((pos.X + scale.X), (pos.Y + scale.Y), (pos.Z + scale.Z)));
// vertexes[7].x = pos.X + vertexes[7].x;
// vertexes[7].y = pos.Y + vertexes[7].y;
// vertexes[7].z = pos.Z + vertexes[7].z;
FaceD[2] = vertexes[7];
FaceC[3] = vertexes[7];
FaceD[5] = vertexes[7];
#endregion
//int wy = 0;
//bool breakYN = false; // If we run into an error drawing, break out of the
// loop so we don't lag to death on error handling
DrawStruct ds = new DrawStruct();
ds.brush = new SolidBrush(mapdotspot);
//ds.rect = new Rectangle(mapdrawstartX, (255 - mapdrawstartY), mapdrawendX - mapdrawstartX, mapdrawendY - mapdrawstartY);
ds.trns = new face[FaceA.Length];
for (int i = 0; i < FaceA.Length; i++)
{
Point[] working = new Point[5];
working[0] = project(FaceA[i], axPos);
working[1] = project(FaceB[i], axPos);
working[2] = project(FaceD[i], axPos);
working[3] = project(FaceC[i], axPos);
working[4] = project(FaceA[i], axPos);
face workingface = new face();
workingface.pts = working;
ds.trns[i] = workingface;
}
z_sort.Add(part.LocalId, ds);
z_localIDs.Add(part.LocalId);
z_sortheights.Add(pos.Z);
//for (int wx = mapdrawstartX; wx < mapdrawendX; wx++)
//{
//for (wy = mapdrawstartY; wy < mapdrawendY; wy++)
//{
//m_log.InfoFormat("[MAPDEBUG]: {0},{1}({2})", wx, (255 - wy),wy);
//try
//{
// Remember, flip the y!
// mapbmp.SetPixel(wx, (255 - wy), mapdotspot);
//}
//catch (ArgumentException)
//{
// breakYN = true;
//}
//if (breakYN)
// break;
//}
//if (breakYN)
// break;
//}
} // Object is within 256m Z of terrain
} // object is at least a meter wide
} // loop over group children
} // entitybase is sceneobject group
} // foreach loop over entities
float[] sortedZHeights = z_sortheights.ToArray();
uint[] sortedlocalIds = z_localIDs.ToArray();
// Sort prim by Z position
Array.Sort(sortedZHeights, sortedlocalIds);
Graphics g = Graphics.FromImage(mapbmp);
for (int s = 0; s < sortedZHeights.Length; s++)
{
if (z_sort.ContainsKey(sortedlocalIds[s]))
{
DrawStruct rectDrawStruct = z_sort[sortedlocalIds[s]];
for (int r = 0; r < rectDrawStruct.trns.Length; r++)
{
g.FillPolygon(rectDrawStruct.brush,rectDrawStruct.trns[r].pts);
}
//g.FillRectangle(rectDrawStruct.brush , rectDrawStruct.rect);
}
}
g.Dispose();
} // lock entities objs
m_log.Info("[MAPTILE]: Generating Maptile Step 2: Done in " + (Environment.TickCount - tc) + " ms");
return mapbmp;
}
private Point project(Vector3 point3d, Vector3 originpos)
{
Point returnpt = new Point();
//originpos = point3d;
//int d = (int)(256f / 1.5f);
//Vector3 topos = new Vector3(0, 0, 0);
// float z = -point3d.z - topos.z;
returnpt.X = (int)point3d.X;//(int)((topos.x - point3d.x) / z * d);
returnpt.Y = (int)(((int)Constants.RegionSize - 1) - point3d.Y);//(int)(255 - (((topos.y - point3d.y) / z * d)));
return returnpt;
}
// TODO: unused:
// #region Deprecated Maptile Generation. Adam may update this
// private Bitmap TerrainToBitmap(string gradientmap)
// {
// Bitmap gradientmapLd = new Bitmap(gradientmap);
//
// int pallete = gradientmapLd.Height;
//
// Bitmap bmp = new Bitmap(m_scene.Heightmap.Width, m_scene.Heightmap.Height);
// Color[] colours = new Color[pallete];
//
// for (int i = 0; i < pallete; i++)
// {
// colours[i] = gradientmapLd.GetPixel(0, i);
// }
//
// lock (m_scene.Heightmap)
// {
// ITerrainChannel copy = m_scene.Heightmap;
// for (int y = 0; y < copy.Height; y++)
// {
// for (int x = 0; x < copy.Width; x++)
// {
// // 512 is the largest possible height before colours clamp
// int colorindex = (int) (Math.Max(Math.Min(1.0, copy[x, y] / 512.0), 0.0) * (pallete - 1));
//
// // Handle error conditions
// if (colorindex > pallete - 1 || colorindex < 0)
// bmp.SetPixel(x, copy.Height - y - 1, Color.Red);
// else
// bmp.SetPixel(x, copy.Height - y - 1, colours[colorindex]);
// }
// }
// ShadeBuildings(bmp);
// return bmp;
// }
// }
// #endregion
}
}
| |
/*-
* Copyright (c) 2009, 2020 Oracle and/or its affiliates. All rights reserved.
*
* See the file LICENSE for license information.
*
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;
using NUnit.Framework;
using BerkeleyDB;
namespace CsharpAPITest
{
[TestFixture]
public class RecnoCursorTest : CSharpTestFixture
{
[TestFixtureSetUp]
public void SetUpTestFixture()
{
testFixtureName = "RecnoCursorTest";
base.SetUpTestfixture();
}
[Test]
public void TestCursor()
{
testName = "TestCursor";
SetUpTest(true);
GetCursorWithImplicitTxn(testHome,
testName + ".db", false);
}
[Test]
public void TestCursorWithConfig()
{
testName = "TestCursorWithConfig";
SetUpTest(true);
GetCursorWithImplicitTxn(testHome,
testName + ".db", true);
}
public void GetCursorWithImplicitTxn(string home,
string dbFile, bool ifConfig)
{
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
envConfig.Create = true;
envConfig.UseCDB = true;
envConfig.UseMPool = true;
DatabaseEnvironment env = DatabaseEnvironment.Open(
home, envConfig);
RecnoDatabaseConfig dbConfig =
new RecnoDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.Env = env;
RecnoDatabase db = RecnoDatabase.Open(dbFile,
dbConfig);
RecnoCursor cursor;
if (ifConfig == false)
cursor = db.Cursor();
else
cursor = db.Cursor(new CursorConfig());
cursor.Close();
db.Close();
env.Close();
}
[Test]
public void TestCursorInTxn()
{
testName = "TestCursorInTxn";
SetUpTest(true);
GetCursorWithExplicitTxn(testHome,
testName + ".db", false);
}
[Test]
public void TestConfigedCursorInTxn()
{
testName = "TestConfigedCursorInTxn";
SetUpTest(true);
GetCursorWithExplicitTxn(testHome,
testName + ".db", true);
}
public void GetCursorWithExplicitTxn(string home,
string dbFile, bool ifConfig)
{
DatabaseEnvironmentConfig envConfig =
new DatabaseEnvironmentConfig();
envConfig.Create = true;
envConfig.UseTxns = true;
envConfig.UseMPool = true;
DatabaseEnvironment env = DatabaseEnvironment.Open(
home, envConfig);
Transaction openTxn = env.BeginTransaction();
RecnoDatabaseConfig dbConfig =
new RecnoDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.Env = env;
RecnoDatabase db = RecnoDatabase.Open(dbFile,
dbConfig, openTxn);
openTxn.Commit();
Transaction cursorTxn = env.BeginTransaction();
RecnoCursor cursor;
if (ifConfig == false)
cursor = db.Cursor(cursorTxn);
else
cursor = db.Cursor(new CursorConfig(), cursorTxn);
cursor.Close();
cursorTxn.Commit();
db.Close();
env.Close();
}
[Test]
public void TestDuplicate()
{
KeyValuePair<DatabaseEntry, DatabaseEntry> pair;
RecnoDatabase db;
RecnoDatabaseConfig dbConfig;
RecnoCursor cursor, dupCursor;
string dbFileName;
testName = "TestDuplicate";
SetUpTest(true);
dbFileName = testHome + "/" + testName + ".db";
dbConfig = new RecnoDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
db = RecnoDatabase.Open(dbFileName, dbConfig);
cursor = db.Cursor();
/*
* Add a record(1, 1) by cursor and move
* the cursor to the current record.
*/
AddOneByCursor(cursor);
cursor.Refresh();
//Duplicate a new cursor to the same position.
dupCursor = cursor.Duplicate(true);
// Overwrite the record.
dupCursor.Overwrite(new DatabaseEntry(
ASCIIEncoding.ASCII.GetBytes("newdata")));
// Confirm that the original data doesn't exist.
pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(
new DatabaseEntry(
BitConverter.GetBytes((int)1)),
new DatabaseEntry(
BitConverter.GetBytes((int)1)));
Assert.IsFalse(dupCursor.Move(pair, true));
dupCursor.Close();
cursor.Close();
db.Close();
}
[Test]
public void TestInsertToLoc()
{
RecnoDatabase db;
RecnoDatabaseConfig dbConfig;
RecnoCursor cursor;
DatabaseEntry data;
KeyValuePair<DatabaseEntry, DatabaseEntry> pair;
string dbFileName;
testName = "TestInsertToLoc";
SetUpTest(true);
dbFileName = testHome + "/" + testName + ".db";
// Open database and cursor.
dbConfig = new RecnoDatabaseConfig();
dbConfig.Creation = CreatePolicy.IF_NEEDED;
dbConfig.Renumber = true;
db = RecnoDatabase.Open(dbFileName, dbConfig);
cursor = db.Cursor();
// Add record(1,1) into database.
/*
* Add a record(1, 1) by cursor and move
* the cursor to the current record.
*/
AddOneByCursor(cursor);
cursor.Refresh();
/*
* Insert the new record(1,10) after the
* record(1,1).
*/
data = new DatabaseEntry(
BitConverter.GetBytes((int)10));
cursor.Insert(data, Cursor.InsertLocation.AFTER);
/*
* Move the cursor to the record(1,1) and
* confirm that the next record is the one just inserted.
*/
pair = new KeyValuePair<DatabaseEntry, DatabaseEntry>(
new DatabaseEntry(
BitConverter.GetBytes((int)1)),
new DatabaseEntry(
BitConverter.GetBytes((int)1)));
Assert.IsTrue(cursor.Move(pair, true));
Assert.IsTrue(cursor.MoveNext());
Assert.AreEqual(BitConverter.GetBytes((int)10),
cursor.Current.Value.Data);
cursor.Close();
db.Close();
}
public void AddOneByCursor(RecnoCursor cursor)
{
KeyValuePair<DatabaseEntry, DatabaseEntry> pair =
new KeyValuePair<DatabaseEntry, DatabaseEntry>(
new DatabaseEntry(
BitConverter.GetBytes((int)1)),
new DatabaseEntry(
BitConverter.GetBytes((int)1)));
cursor.Add(pair);
}
}
}
| |
namespace XenAdmin.Controls
{
partial class BondDetails
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(BondDetails));
this.cbxAutomatic = new System.Windows.Forms.CheckBox();
this.dataGridView1 = new System.Windows.Forms.DataGridView();
this.ColumnCheckBox = new System.Windows.Forms.DataGridViewCheckBoxColumn();
this.ColumnNic = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnMac = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnLinkStatus = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnSpeed = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDuplex = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnVendor = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnDevice = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.ColumnPci = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.numericUpDownMTU = new System.Windows.Forms.NumericUpDown();
this.labelMTU = new System.Windows.Forms.Label();
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.panelLACPWarning = new System.Windows.Forms.Panel();
this.label1 = new System.Windows.Forms.Label();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.groupBoxBondMode = new System.Windows.Forms.GroupBox();
this.tableLayoutPanelBondMode = new System.Windows.Forms.TableLayoutPanel();
this.radioButtonLacpTcpudpPorts = new System.Windows.Forms.RadioButton();
this.radioButtonLacpSrcMac = new System.Windows.Forms.RadioButton();
this.radioButtonBalanceSlb = new System.Windows.Forms.RadioButton();
this.radioButtonActiveBackup = new System.Windows.Forms.RadioButton();
this.dataGridViewTextBoxColumn1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn2 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn3 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn4 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn5 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn6 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn7 = new System.Windows.Forms.DataGridViewTextBoxColumn();
this.dataGridViewTextBoxColumn8 = new System.Windows.Forms.DataGridViewTextBoxColumn();
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).BeginInit();
this.tableLayoutPanel1.SuspendLayout();
this.panelLACPWarning.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.groupBoxBondMode.SuspendLayout();
this.tableLayoutPanelBondMode.SuspendLayout();
this.SuspendLayout();
//
// cbxAutomatic
//
resources.ApplyResources(this.cbxAutomatic, "cbxAutomatic");
this.tableLayoutPanel1.SetColumnSpan(this.cbxAutomatic, 3);
this.cbxAutomatic.Name = "cbxAutomatic";
this.cbxAutomatic.UseVisualStyleBackColor = true;
//
// dataGridView1
//
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.AllowUserToDeleteRows = false;
this.dataGridView1.AllowUserToResizeRows = false;
resources.ApplyResources(this.dataGridView1, "dataGridView1");
this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.AllCells;
this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Window;
this.dataGridView1.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None;
this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
this.ColumnCheckBox,
this.ColumnNic,
this.ColumnMac,
this.ColumnLinkStatus,
this.ColumnSpeed,
this.ColumnDuplex,
this.ColumnVendor,
this.ColumnDevice,
this.ColumnPci});
this.tableLayoutPanel1.SetColumnSpan(this.dataGridView1, 3);
this.dataGridView1.Name = "dataGridView1";
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellValueChanged);
this.dataGridView1.CurrentCellDirtyStateChanged += new System.EventHandler(this.dataGridView1_CurrentCellDirtyStateChanged);
//
// ColumnCheckBox
//
this.ColumnCheckBox.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells;
resources.ApplyResources(this.ColumnCheckBox, "ColumnCheckBox");
this.ColumnCheckBox.Name = "ColumnCheckBox";
//
// ColumnNic
//
resources.ApplyResources(this.ColumnNic, "ColumnNic");
this.ColumnNic.Name = "ColumnNic";
this.ColumnNic.ReadOnly = true;
//
// ColumnMac
//
resources.ApplyResources(this.ColumnMac, "ColumnMac");
this.ColumnMac.Name = "ColumnMac";
this.ColumnMac.ReadOnly = true;
//
// ColumnLinkStatus
//
resources.ApplyResources(this.ColumnLinkStatus, "ColumnLinkStatus");
this.ColumnLinkStatus.Name = "ColumnLinkStatus";
this.ColumnLinkStatus.ReadOnly = true;
//
// ColumnSpeed
//
resources.ApplyResources(this.ColumnSpeed, "ColumnSpeed");
this.ColumnSpeed.Name = "ColumnSpeed";
this.ColumnSpeed.ReadOnly = true;
//
// ColumnDuplex
//
resources.ApplyResources(this.ColumnDuplex, "ColumnDuplex");
this.ColumnDuplex.Name = "ColumnDuplex";
this.ColumnDuplex.ReadOnly = true;
//
// ColumnVendor
//
resources.ApplyResources(this.ColumnVendor, "ColumnVendor");
this.ColumnVendor.Name = "ColumnVendor";
this.ColumnVendor.ReadOnly = true;
//
// ColumnDevice
//
resources.ApplyResources(this.ColumnDevice, "ColumnDevice");
this.ColumnDevice.Name = "ColumnDevice";
this.ColumnDevice.ReadOnly = true;
//
// ColumnPci
//
this.ColumnPci.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.ColumnPci, "ColumnPci");
this.ColumnPci.Name = "ColumnPci";
this.ColumnPci.ReadOnly = true;
//
// numericUpDownMTU
//
resources.ApplyResources(this.numericUpDownMTU, "numericUpDownMTU");
this.numericUpDownMTU.Name = "numericUpDownMTU";
//
// labelMTU
//
resources.ApplyResources(this.labelMTU, "labelMTU");
this.labelMTU.Name = "labelMTU";
//
// tableLayoutPanel1
//
resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1");
this.tableLayoutPanel1.Controls.Add(this.panelLACPWarning, 0, 1);
this.tableLayoutPanel1.Controls.Add(this.numericUpDownMTU, 1, 3);
this.tableLayoutPanel1.Controls.Add(this.dataGridView1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.cbxAutomatic, 0, 4);
this.tableLayoutPanel1.Controls.Add(this.labelMTU, 0, 3);
this.tableLayoutPanel1.Controls.Add(this.groupBoxBondMode, 0, 1);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
//
// panelLACPWarning
//
resources.ApplyResources(this.panelLACPWarning, "panelLACPWarning");
this.tableLayoutPanel1.SetColumnSpan(this.panelLACPWarning, 3);
this.panelLACPWarning.Controls.Add(this.label1);
this.panelLACPWarning.Controls.Add(this.pictureBox1);
this.panelLACPWarning.Name = "panelLACPWarning";
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// pictureBox1
//
resources.ApplyResources(this.pictureBox1, "pictureBox1");
this.pictureBox1.Image = global::XenAdmin.Properties.Resources._000_Alert2_h32bit_16;
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.TabStop = false;
//
// groupBoxBondMode
//
resources.ApplyResources(this.groupBoxBondMode, "groupBoxBondMode");
this.tableLayoutPanel1.SetColumnSpan(this.groupBoxBondMode, 2);
this.groupBoxBondMode.Controls.Add(this.tableLayoutPanelBondMode);
this.groupBoxBondMode.Name = "groupBoxBondMode";
this.groupBoxBondMode.TabStop = false;
//
// tableLayoutPanelBondMode
//
resources.ApplyResources(this.tableLayoutPanelBondMode, "tableLayoutPanelBondMode");
this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonLacpTcpudpPorts, 0, 2);
this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonLacpSrcMac, 0, 3);
this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonBalanceSlb, 0, 0);
this.tableLayoutPanelBondMode.Controls.Add(this.radioButtonActiveBackup, 0, 1);
this.tableLayoutPanelBondMode.MinimumSize = new System.Drawing.Size(0, 40);
this.tableLayoutPanelBondMode.Name = "tableLayoutPanelBondMode";
//
// radioButtonLacpTcpudpPorts
//
resources.ApplyResources(this.radioButtonLacpTcpudpPorts, "radioButtonLacpTcpudpPorts");
this.radioButtonLacpTcpudpPorts.Name = "radioButtonLacpTcpudpPorts";
this.radioButtonLacpTcpudpPorts.UseVisualStyleBackColor = true;
this.radioButtonLacpTcpudpPorts.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged);
//
// radioButtonLacpSrcMac
//
resources.ApplyResources(this.radioButtonLacpSrcMac, "radioButtonLacpSrcMac");
this.radioButtonLacpSrcMac.Name = "radioButtonLacpSrcMac";
this.radioButtonLacpSrcMac.UseVisualStyleBackColor = true;
this.radioButtonLacpSrcMac.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged);
//
// radioButtonBalanceSlb
//
resources.ApplyResources(this.radioButtonBalanceSlb, "radioButtonBalanceSlb");
this.radioButtonBalanceSlb.Checked = true;
this.radioButtonBalanceSlb.Name = "radioButtonBalanceSlb";
this.radioButtonBalanceSlb.TabStop = true;
this.radioButtonBalanceSlb.UseVisualStyleBackColor = true;
this.radioButtonBalanceSlb.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged);
//
// radioButtonActiveBackup
//
resources.ApplyResources(this.radioButtonActiveBackup, "radioButtonActiveBackup");
this.radioButtonActiveBackup.Name = "radioButtonActiveBackup";
this.radioButtonActiveBackup.UseVisualStyleBackColor = true;
this.radioButtonActiveBackup.CheckedChanged += new System.EventHandler(this.BondMode_CheckedChanged);
//
// dataGridViewTextBoxColumn1
//
resources.ApplyResources(this.dataGridViewTextBoxColumn1, "dataGridViewTextBoxColumn1");
this.dataGridViewTextBoxColumn1.Name = "dataGridViewTextBoxColumn1";
this.dataGridViewTextBoxColumn1.ReadOnly = true;
//
// dataGridViewTextBoxColumn2
//
resources.ApplyResources(this.dataGridViewTextBoxColumn2, "dataGridViewTextBoxColumn2");
this.dataGridViewTextBoxColumn2.Name = "dataGridViewTextBoxColumn2";
this.dataGridViewTextBoxColumn2.ReadOnly = true;
//
// dataGridViewTextBoxColumn3
//
resources.ApplyResources(this.dataGridViewTextBoxColumn3, "dataGridViewTextBoxColumn3");
this.dataGridViewTextBoxColumn3.Name = "dataGridViewTextBoxColumn3";
this.dataGridViewTextBoxColumn3.ReadOnly = true;
//
// dataGridViewTextBoxColumn4
//
resources.ApplyResources(this.dataGridViewTextBoxColumn4, "dataGridViewTextBoxColumn4");
this.dataGridViewTextBoxColumn4.Name = "dataGridViewTextBoxColumn4";
this.dataGridViewTextBoxColumn4.ReadOnly = true;
//
// dataGridViewTextBoxColumn5
//
resources.ApplyResources(this.dataGridViewTextBoxColumn5, "dataGridViewTextBoxColumn5");
this.dataGridViewTextBoxColumn5.Name = "dataGridViewTextBoxColumn5";
this.dataGridViewTextBoxColumn5.ReadOnly = true;
//
// dataGridViewTextBoxColumn6
//
resources.ApplyResources(this.dataGridViewTextBoxColumn6, "dataGridViewTextBoxColumn6");
this.dataGridViewTextBoxColumn6.Name = "dataGridViewTextBoxColumn6";
this.dataGridViewTextBoxColumn6.ReadOnly = true;
//
// dataGridViewTextBoxColumn7
//
resources.ApplyResources(this.dataGridViewTextBoxColumn7, "dataGridViewTextBoxColumn7");
this.dataGridViewTextBoxColumn7.Name = "dataGridViewTextBoxColumn7";
this.dataGridViewTextBoxColumn7.ReadOnly = true;
//
// dataGridViewTextBoxColumn8
//
this.dataGridViewTextBoxColumn8.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill;
resources.ApplyResources(this.dataGridViewTextBoxColumn8, "dataGridViewTextBoxColumn8");
this.dataGridViewTextBoxColumn8.Name = "dataGridViewTextBoxColumn8";
this.dataGridViewTextBoxColumn8.ReadOnly = true;
//
// BondDetails
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi;
this.BackColor = System.Drawing.Color.LightGray;
this.Controls.Add(this.tableLayoutPanel1);
this.Name = "BondDetails";
((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.numericUpDownMTU)).EndInit();
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.panelLACPWarning.ResumeLayout(false);
this.panelLACPWarning.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.groupBoxBondMode.ResumeLayout(false);
this.groupBoxBondMode.PerformLayout();
this.tableLayoutPanelBondMode.ResumeLayout(false);
this.tableLayoutPanelBondMode.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
public System.Windows.Forms.CheckBox cbxAutomatic;
private System.Windows.Forms.DataGridView dataGridView1;
private System.Windows.Forms.NumericUpDown numericUpDownMTU;
private System.Windows.Forms.Label labelMTU;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.DataGridViewCheckBoxColumn ColumnCheckBox;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnNic;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnMac;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnLinkStatus;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnSpeed;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDuplex;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnVendor;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnDevice;
private System.Windows.Forms.DataGridViewTextBoxColumn ColumnPci;
private System.Windows.Forms.TableLayoutPanel tableLayoutPanelBondMode;
private System.Windows.Forms.RadioButton radioButtonBalanceSlb;
private System.Windows.Forms.RadioButton radioButtonActiveBackup;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn6;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn7;
private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn8;
private System.Windows.Forms.RadioButton radioButtonLacpTcpudpPorts;
private System.Windows.Forms.RadioButton radioButtonLacpSrcMac;
private System.Windows.Forms.GroupBox groupBoxBondMode;
private System.Windows.Forms.Panel panelLACPWarning;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.PictureBox pictureBox1;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using NUnit.Framework;
using System;
using System.Text;
using System.Collections;
using Apache.NMS.Stomp.Commands;
using Apache.NMS.Stomp.Protocol;
using Apache.NMS.Util;
namespace Apache.NMS.Stomp.Test.Commands
{
[TestFixture]
public class MessageTest
{
private string nmsMessageID;
private string nmsCorrelationID;
private Topic nmsDestination;
private TempTopic nmsReplyTo;
private MsgDeliveryMode nmsDeliveryMode;
private bool nmsRedelivered;
private string nmsType;
private MsgPriority nmsPriority;
private DateTime nmsTimestamp;
private long[] consumerIDs;
[SetUp]
public virtual void SetUp()
{
this.nmsMessageID = "testid";
this.nmsCorrelationID = "testcorrelationid";
this.nmsDestination = new Topic("TEST.Message");
this.nmsReplyTo = new TempTopic("TEST.Message.replyto.topic:001");
this.nmsDeliveryMode = MsgDeliveryMode.NonPersistent;
this.nmsRedelivered = true;
this.nmsType = "test type";
this.nmsPriority = MsgPriority.High;
this.nmsTimestamp = DateTime.Now;
this.consumerIDs = new long[3];
for(int i = 0; i < this.consumerIDs.Length; i++)
{
this.consumerIDs[i] = i;
}
}
[Test]
public void TestSetReadOnly()
{
Message msg = new Message();
msg.ReadOnlyProperties = true;
bool test = false;
try
{
msg.Properties.SetInt("test", 1);
}
catch(MessageNotWriteableException)
{
test = true;
}
catch(NMSException)
{
test = false;
}
Assert.IsTrue(test);
}
[Test]
public void TestSetToForeignNMSID()
{
Message msg = new Message();
msg.NMSMessageId = "ID:EMS-SERVER.8B443C380083:429";
}
[Test]
public void TestEqualsObject()
{
Message msg1 = new Message();
Message msg2 = new Message();
msg1.NMSMessageId = this.nmsMessageID;
Assert.IsTrue(!msg1.Equals(msg2));
msg2.NMSMessageId = this.nmsMessageID;
Assert.IsTrue(msg1.Equals(msg2));
}
[Test]
public void TestShallowCopy()
{
Message msg1 = new Message();
msg1.NMSMessageId = nmsMessageID;
Message msg2 = (Message) msg1.Clone();
Assert.IsTrue(msg1 != msg2 && msg1.Equals(msg2));
}
[Test]
public void TestCopy()
{
this.nmsMessageID = "ID:1141:45278:429";
this.nmsCorrelationID = "testcorrelationid";
this.nmsDestination = new Topic("test.topic");
this.nmsReplyTo = new TempTopic("test.replyto.topic:001");
this.nmsDeliveryMode = MsgDeliveryMode.NonPersistent;
this.nmsType = "test type";
this.nmsPriority = MsgPriority.High;
this.nmsTimestamp = DateTime.Now;
Message msg1 = new Message();
msg1.NMSMessageId = this.nmsMessageID;
msg1.NMSCorrelationID = this.nmsCorrelationID;
msg1.FromDestination = this.nmsDestination;
msg1.NMSReplyTo = this.nmsReplyTo;
msg1.NMSDeliveryMode = this.nmsDeliveryMode;
msg1.NMSType = this.nmsType;
msg1.NMSPriority = this.nmsPriority;
msg1.NMSTimestamp = this.nmsTimestamp;
msg1.ReadOnlyProperties = true;
Message msg2 = msg1.Clone() as Message;
Assert.IsTrue(msg1.NMSMessageId.Equals(msg2.NMSMessageId));
Assert.IsTrue(msg1.NMSCorrelationID.Equals(msg2.NMSCorrelationID));
Assert.IsTrue(msg1.NMSDestination.Equals(msg2.NMSDestination));
Assert.IsTrue(msg1.NMSReplyTo.Equals(msg2.NMSReplyTo));
Assert.IsTrue(msg1.NMSDeliveryMode == msg2.NMSDeliveryMode);
Assert.IsTrue(msg1.NMSRedelivered == msg2.NMSRedelivered);
Assert.IsTrue(msg1.NMSType.Equals(msg2.NMSType));
Assert.IsTrue(msg1.NMSPriority == msg2.NMSPriority);
Assert.IsTrue(msg1.NMSTimestamp == msg2.NMSTimestamp);
}
[Test]
public void TestGetAndSetNMSCorrelationID()
{
Message msg = new Message();
msg.NMSCorrelationID = this.nmsCorrelationID;
Assert.IsTrue(msg.NMSCorrelationID.Equals(this.nmsCorrelationID));
}
[Test]
public void TestGetAndSetNMSReplyTo()
{
Message msg = new Message();
msg.NMSReplyTo = this.nmsReplyTo;
Assert.AreEqual(msg.NMSReplyTo, this.nmsReplyTo);
}
[Test]
public void TestGetAndSetNMSDestination()
{
Message msg = new Message();
msg.FromDestination = this.nmsDestination;
Assert.AreEqual(msg.NMSDestination, this.nmsDestination);
}
[Test]
public void TestGetAndSetNMSDeliveryMode()
{
Message msg = new Message();
msg.NMSDeliveryMode = this.nmsDeliveryMode;
Assert.IsTrue(msg.NMSDeliveryMode == this.nmsDeliveryMode);
}
[Test]
public void TestGetAndSetMSRedelivered()
{
Message msg = new Message();
msg.RedeliveryCounter = 2;
Assert.IsTrue(msg.NMSRedelivered == this.nmsRedelivered);
}
[Test]
public void TestGetAndSetNMSType()
{
Message msg = new Message();
msg.NMSType = this.nmsType;
Assert.AreEqual(msg.NMSType, this.nmsType);
}
[Test]
public void TestGetAndSetNMSPriority()
{
Message msg = new Message();
msg.NMSPriority = this.nmsPriority;
Assert.IsTrue(msg.NMSPriority == this.nmsPriority);
}
public void TestClearProperties()
{
Message msg = new Message();
msg.Properties.SetString("test", "test");
msg.Content = new byte[1];
msg.NMSMessageId = this.nmsMessageID;
msg.ClearProperties();
Assert.IsNull(msg.Properties.GetString("test"));
Assert.IsNotNull(msg.NMSMessageId);
Assert.IsNotNull(msg.Content);
}
[Test]
public void TestPropertyExists()
{
Message msg = new Message();
msg.Properties.SetString("test", "test");
Assert.IsTrue(msg.Properties.Contains("test"));
}
[Test]
public void TestGetBooleanProperty()
{
Message msg = new Message();
string name = "booleanProperty";
msg.Properties.SetBool(name, true);
Assert.IsTrue(msg.Properties.GetBool(name));
}
[Test]
public void TestGetByteProperty()
{
Message msg = new Message();
string name = "byteProperty";
msg.Properties.SetByte(name, (byte)1);
Assert.IsTrue(msg.Properties.GetByte(name) == 1);
}
[Test]
public void TestGetShortProperty()
{
Message msg = new Message();
string name = "shortProperty";
msg.Properties.SetShort(name, (short)1);
Assert.IsTrue(msg.Properties.GetShort(name) == 1);
}
[Test]
public void TestGetIntProperty()
{
Message msg = new Message();
string name = "intProperty";
msg.Properties.SetInt(name, 1);
Assert.IsTrue(msg.Properties.GetInt(name) == 1);
}
[Test]
public void TestGetLongProperty()
{
Message msg = new Message();
string name = "longProperty";
msg.Properties.SetLong(name, 1);
Assert.IsTrue(msg.Properties.GetLong(name) == 1);
}
[Test]
public void TestGetFloatProperty()
{
Message msg = new Message();
string name = "floatProperty";
msg.Properties.SetFloat(name, 1.3f);
Assert.IsTrue(msg.Properties.GetFloat(name) == 1.3f);
}
[Test]
public void TestGetDoubleProperty()
{
Message msg = new Message();
string name = "doubleProperty";
msg.Properties.SetDouble(name, 1.3d);
Assert.IsTrue(msg.Properties.GetDouble(name) == 1.3);
}
[Test]
public void TestGetStringProperty()
{
Message msg = new Message();
string name = "stringProperty";
msg.Properties.SetString(name, name);
Assert.IsTrue(msg.Properties.GetString(name).Equals(name));
}
[Test]
public void TestGetObjectProperty()
{
Message msg = new Message();
string name = "floatProperty";
msg.Properties.SetFloat(name, 1.3f);
Assert.IsTrue(msg.Properties[name] is float);
Assert.IsTrue((float)msg.Properties[name] == 1.3f);
}
[Test]
public void TestGetPropertyNames()
{
Message msg = new Message();
string name = "floatProperty";
msg.Properties.SetFloat(name, 1.3f);
foreach(string key in msg.Properties.Keys)
{
Assert.IsTrue(key.Equals(name));
}
}
[Test]
public void TestSetObjectProperty()
{
Message msg = new Message();
string name = "property";
try
{
msg.Properties[name] = "string";
msg.Properties[name] = (Byte) 1;
msg.Properties[name] = (Int16) 1;
msg.Properties[name] = (Int32) 1;
msg.Properties[name] = (Int64) 1;
msg.Properties[name] = (Single) 1.1f;
msg.Properties[name] = (Double) 1.1;
msg.Properties[name] = (Boolean) true;
msg.Properties[name] = null;
}
catch(MessageFormatException)
{
Assert.Fail("should accept object primitives and String");
}
try
{
msg.Properties[name] = new Object();
Assert.Fail("should accept only object primitives and String");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties[name] = new StringBuilder();
Assert.Fail("should accept only object primitives and String");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestConvertProperties()
{
Message msg = new Message();
msg.Properties["stringProperty"] = "string";
msg.Properties["byteProperty"] = (Byte) 1;
msg.Properties["shortProperty"] = (Int16) 1;
msg.Properties["intProperty"] = (Int32) 1;
msg.Properties["longProperty"] = (Int64) 1;
msg.Properties["floatProperty"] = (Single) 1.1f;
msg.Properties["doubleProperty"] = (Double) 1.1;
msg.Properties["booleanProperty"] = (Boolean) true;
msg.Properties["nullProperty"] = null;
msg.BeforeMarshall(new StompWireFormat());
IPrimitiveMap properties = msg.Properties;
Assert.AreEqual(properties["stringProperty"], "string");
Assert.AreEqual((byte)properties["byteProperty"], (byte) 1);
Assert.AreEqual((short)properties["shortProperty"], (short) 1);
Assert.AreEqual((int)properties["intProperty"], (int) 1);
Assert.AreEqual((long)properties["longProperty"], (long) 1);
Assert.AreEqual((float)properties["floatProperty"], 1.1f, 0);
Assert.AreEqual((double)properties["doubleProperty"], 1.1, 0);
Assert.AreEqual((bool)properties["booleanProperty"], true);
Assert.IsNull(properties["nullProperty"]);
}
[Test]
public void TestSetNullProperty()
{
Message msg = new Message();
string name = "cheese";
msg.Properties.SetString(name, "Cheddar");
Assert.AreEqual("Cheddar", msg.Properties.GetString(name));
msg.Properties.SetString(name, null);
Assert.AreEqual(null, msg.Properties.GetString(name));
}
[Test]
public void TestSetNullPropertyName()
{
Message msg = new Message();
try
{
msg.Properties.SetString(null, "Cheese");
Assert.Fail("Should have thrown exception");
}
catch(Exception)
{
}
}
[Test]
public void TestSetEmptyPropertyName()
{
Message msg = new Message();
try
{
msg.Properties.SetString("", "Cheese");
Assert.Fail("Should have thrown exception");
}
catch(Exception)
{
}
}
[Test]
public void TestGetAndSetNMSXDeliveryCount()
{
Message msg = new Message();
msg.Properties.SetInt("NMSXDeliveryCount", 1);
int count = msg.Properties.GetInt("NMSXDeliveryCount");
Assert.IsTrue(count == 1, "expected delivery count = 1 - got: " + count);
}
[Test]
public void TestClearBody()
{
BytesMessage message = new BytesMessage();
message.ClearBody();
Assert.IsFalse(message.ReadOnlyBody);
}
[Test]
public void TestBooleanPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
msg.Properties.SetBool(propertyName, true);
Assert.AreEqual((bool)msg.Properties[propertyName], true);
Assert.IsTrue(msg.Properties.GetBool(propertyName));
Assert.AreEqual(msg.Properties.GetString(propertyName), "True");
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetInt(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetLong(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestBytePropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
msg.Properties.SetByte(propertyName, (byte)1);
Assert.AreEqual((byte)msg.Properties[propertyName], 1);
Assert.AreEqual(msg.Properties.GetByte(propertyName), 1);
Assert.AreEqual(msg.Properties.GetShort(propertyName), 1);
Assert.AreEqual(msg.Properties.GetInt(propertyName), 1);
Assert.AreEqual(msg.Properties.GetLong(propertyName), 1);
Assert.AreEqual(msg.Properties.GetString(propertyName), "1");
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try {
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestShortPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
msg.Properties.SetShort(propertyName, (short)1);
Assert.AreEqual((short)msg.Properties[propertyName], 1);
Assert.AreEqual(msg.Properties.GetShort(propertyName), 1);
Assert.AreEqual(msg.Properties.GetInt(propertyName), 1);
Assert.AreEqual(msg.Properties.GetLong(propertyName), 1);
Assert.AreEqual(msg.Properties.GetString(propertyName), "1");
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestIntPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
msg.Properties.SetInt(propertyName, (int)1);
Assert.AreEqual((int)msg.Properties[propertyName], 1);
Assert.AreEqual(msg.Properties.GetInt(propertyName), 1);
Assert.AreEqual(msg.Properties.GetLong(propertyName), 1);
Assert.AreEqual(msg.Properties.GetString(propertyName), "1");
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestLongPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
msg.Properties.SetLong(propertyName, 1);
Assert.AreEqual((long)msg.Properties[propertyName], 1);
Assert.AreEqual(msg.Properties.GetLong(propertyName), 1);
Assert.AreEqual(msg.Properties.GetString(propertyName), "1");
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
} catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetInt(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestFloatPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
float floatValue = (float)1.5;
msg.Properties.SetFloat(propertyName, floatValue);
Assert.AreEqual((float)msg.Properties[propertyName], floatValue, 0);
Assert.AreEqual(msg.Properties.GetFloat(propertyName), floatValue, 0);
Assert.AreEqual(msg.Properties.GetDouble(propertyName), floatValue, 0);
Assert.AreEqual(msg.Properties.GetString(propertyName), floatValue.ToString());
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetInt(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetLong(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestDoublePropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
Double doubleValue = 1.5;
msg.Properties.SetDouble(propertyName, doubleValue);
Assert.AreEqual((double)msg.Properties[propertyName], doubleValue, 0);
Assert.AreEqual(msg.Properties.GetDouble(propertyName), doubleValue, 0);
Assert.AreEqual(msg.Properties.GetString(propertyName), doubleValue.ToString());
try
{
msg.Properties.GetBool(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetInt(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetLong(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
}
[Test]
public void TestStringPropertyConversion()
{
Message msg = new Message();
String propertyName = "property";
String stringValue = "True";
msg.Properties.SetString(propertyName, stringValue);
Assert.AreEqual(msg.Properties.GetString(propertyName), stringValue);
Assert.AreEqual((string)msg.Properties[propertyName], stringValue);
Assert.AreEqual(msg.Properties.GetBool(propertyName), true);
stringValue = "1";
msg.Properties.SetString(propertyName, stringValue);
Assert.AreEqual(msg.Properties.GetByte(propertyName), 1);
Assert.AreEqual(msg.Properties.GetShort(propertyName), 1);
Assert.AreEqual(msg.Properties.GetInt(propertyName), 1);
Assert.AreEqual(msg.Properties.GetLong(propertyName), 1);
Double doubleValue = 1.5;
stringValue = doubleValue.ToString();
msg.Properties.SetString(propertyName, stringValue);
Assert.AreEqual(msg.Properties.GetFloat(propertyName), 1.5, 0);
Assert.AreEqual(msg.Properties.GetDouble(propertyName), 1.5, 0);
stringValue = "bad";
msg.Properties.SetString(propertyName, stringValue);
try
{
msg.Properties.GetByte(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetShort(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetInt(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetLong(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetFloat(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
try
{
msg.Properties.GetDouble(propertyName);
Assert.Fail("Should have thrown exception");
}
catch(MessageFormatException)
{
}
Assert.IsFalse(msg.Properties.GetBool(propertyName));
}
[Test]
public void TestReadOnlyProperties()
{
Message msg = new Message();
String propertyName = "property";
msg.ReadOnlyProperties = true;
try
{
msg.Properties[propertyName] = new Object();
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetString(propertyName, "test");
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetBool(propertyName, true);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetByte(propertyName, (byte)1);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException) {
}
try
{
msg.Properties.SetShort(propertyName, (short)1);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetInt(propertyName, 1);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetLong(propertyName, 1);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetFloat(propertyName, (float)1.5);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
try
{
msg.Properties.SetDouble(propertyName, 1.5);
Assert.Fail("Should have thrown exception");
}
catch(MessageNotWriteableException)
{
}
}
}
}
| |
// Copyright (c) 2006, ComponentAce
// http://www.componentace.com
// 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 ComponentAce 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.
/*
Copyright (c) 2001 Lapo Luchini.
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.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS SOFTWARE 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
using System;
using System.IO;
namespace CocosSharp.Compression.Zlib
{
internal class ZOutputStream : Stream
{
protected internal byte[] buf, buf1 = new byte[1];
protected internal int bufsize = 4096;
protected internal bool compress;
protected internal int flush_Renamed_Field;
private Stream out_Renamed;
protected internal ZStream z = new ZStream();
public ZOutputStream(Stream out_Renamed)
{
InitBlock();
this.out_Renamed = out_Renamed;
z.InflateInit();
compress = false;
}
public ZOutputStream(Stream out_Renamed, int level)
{
InitBlock();
this.out_Renamed = out_Renamed;
z.DeflateInit(level);
compress = true;
}
public virtual int FlushMode
{
get { return (flush_Renamed_Field); }
set { flush_Renamed_Field = value; }
}
/// <summary> Returns the total number of bytes input so far.</summary>
public virtual long TotalIn
{
get { return z.total_in; }
}
/// <summary> Returns the total number of bytes output so far.</summary>
public virtual long TotalOut
{
get { return z.total_out; }
}
public override Boolean CanRead
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Boolean CanSeek
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Boolean CanWrite
{
get { return false; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Length
{
get { return 0; }
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Position
{
get { return 0; }
set { }
}
private void InitBlock()
{
flush_Renamed_Field = zlibConst.Z_NO_FLUSH;
buf = new byte[bufsize];
}
public void WriteByte(int b)
{
buf1[0] = (byte) b;
Write(buf1, 0, 1);
}
//UPGRADE_TODO: The differences in the Expected value of parameters for method 'WriteByte' may cause compilation errors. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1092_3"'
public override void WriteByte(byte b)
{
WriteByte(b);
}
public override void Write(Byte[] b1, int off, int len)
{
if (len == 0)
return;
int err;
var b = new byte[b1.Length];
Array.Copy(b1, 0, b, 0, b1.Length);
z.next_in = b;
z.next_in_index = off;
z.avail_in = len;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
err = z.Deflate(flush_Renamed_Field);
else
err = z.Inflate(flush_Renamed_Field);
if (err != zlibConst.Z_OK && err != zlibConst.Z_STREAM_END)
throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
} while (z.avail_in > 0 || z.avail_out == 0);
}
public virtual void Finish()
{
int err;
do
{
z.next_out = buf;
z.next_out_index = 0;
z.avail_out = bufsize;
if (compress)
{
err = z.Deflate(zlibConst.Z_FINISH);
}
else
{
err = z.Inflate(zlibConst.Z_FINISH);
}
if (err != zlibConst.Z_STREAM_END && err != zlibConst.Z_OK)
throw new ZStreamException((compress ? "de" : "in") + "flating: " + z.msg);
if (bufsize - z.avail_out > 0)
{
out_Renamed.Write(buf, 0, bufsize - z.avail_out);
}
} while (z.avail_in > 0 || z.avail_out == 0);
try
{
Flush();
}
catch
{
}
}
public virtual void End()
{
if (compress)
{
z.DeflateEnd();
}
else
{
z.InflateEnd();
}
z.Free();
z = null;
}
#if NETFX_CORE
public void Close()
#else
public override void Close()
#endif
{
try
{
try
{
Finish();
}
catch
{
}
}
finally
{
End();
out_Renamed.Close();
out_Renamed = null;
}
}
public override void Flush()
{
out_Renamed.Flush();
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int32 Read(Byte[] buffer, Int32 offset, Int32 count)
{
return 0;
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override void SetLength(Int64 value)
{
}
//UPGRADE_TODO: The following method was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
public override Int64 Seek(Int64 offset, SeekOrigin origin)
{
return 0;
}
//UPGRADE_TODO: The following property was automatically generated and it must be implemented in order to preserve the class logic. 'ms-help://MS.VSCC.2003/commoner/redir/redirect.htm?keyword="jlca1232_3"'
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Collections.Immutable;
using System.Globalization;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.NetCore.Analyzers.Runtime
{
using static MicrosoftNetCoreAnalyzersResources;
/// <summary>
/// CA2208: Instantiate argument exceptions correctly
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)]
public sealed class InstantiateArgumentExceptionsCorrectlyAnalyzer : DiagnosticAnalyzer
{
internal const string RuleId = "CA2208";
internal const string MessagePosition = nameof(MessagePosition);
private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(InstantiateArgumentExceptionsCorrectlyTitle));
private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(InstantiateArgumentExceptionsCorrectlyDescription));
internal static readonly DiagnosticDescriptor RuleNoArguments = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(InstantiateArgumentExceptionsCorrectlyMessageNoArguments)),
DiagnosticCategory.Usage,
RuleLevel.IdeSuggestion,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor RuleIncorrectMessage = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(InstantiateArgumentExceptionsCorrectlyMessageIncorrectMessage)),
DiagnosticCategory.Usage,
RuleLevel.IdeSuggestion,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
internal static readonly DiagnosticDescriptor RuleIncorrectParameterName = DiagnosticDescriptorHelper.Create(
RuleId,
s_localizableTitle,
CreateLocalizableResourceString(nameof(InstantiateArgumentExceptionsCorrectlyMessageIncorrectParameterName)),
DiagnosticCategory.Usage,
RuleLevel.IdeSuggestion,
description: s_localizableDescription,
isPortedFxCopRule: true,
isDataflowRule: false);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(RuleNoArguments, RuleIncorrectMessage, RuleIncorrectParameterName);
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(
compilationContext =>
{
Compilation compilation = compilationContext.Compilation;
ITypeSymbol? argumentExceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException);
if (argumentExceptionType == null)
{
return;
}
compilationContext.RegisterOperationAction(
operationContext => AnalyzeObjectCreation(
operationContext,
operationContext.ContainingSymbol,
argumentExceptionType),
OperationKind.ObjectCreation);
});
}
private static void AnalyzeObjectCreation(
OperationAnalysisContext context,
ISymbol owningSymbol,
ITypeSymbol argumentExceptionType)
{
var creation = (IObjectCreationOperation)context.Operation;
if (!creation.Type.Inherits(argumentExceptionType) || !MatchesConfiguredVisibility(owningSymbol, context) || !HasParameterNameConstructor(creation.Type))
{
return;
}
if (creation.Arguments.IsEmpty)
{
if (HasParameters(owningSymbol))
{
// Call the {0} constructor that contains a message and/ or paramName parameter
context.ReportDiagnostic(context.Operation.Syntax.CreateDiagnostic(RuleNoArguments, creation.Type.Name));
}
}
else
{
Diagnostic? diagnostic = null;
foreach (IArgumentOperation argument in creation.Arguments)
{
if (argument.Parameter.Type.SpecialType != SpecialType.System_String)
{
continue;
}
string? value = argument.Value.ConstantValue.HasValue ? argument.Value.ConstantValue.Value as string : null;
if (value == null)
{
continue;
}
diagnostic = CheckArgument(owningSymbol, creation, argument.Parameter, value, context);
// RuleIncorrectMessage is the highest priority rule, no need to check other rules
if (diagnostic != null && diagnostic.Descriptor.Equals(RuleIncorrectMessage))
{
break;
}
}
if (diagnostic != null)
{
context.ReportDiagnostic(diagnostic);
}
}
}
private static bool MatchesConfiguredVisibility(ISymbol owningSymbol, OperationAnalysisContext context) =>
context.Options.MatchesConfiguredVisibility(RuleIncorrectParameterName, owningSymbol, context.Compilation,
defaultRequiredVisibility: SymbolVisibilityGroup.All);
private static bool HasParameters(ISymbol owningSymbol) => !owningSymbol.GetParameters().IsEmpty;
private static Diagnostic? CheckArgument(
ISymbol targetSymbol,
IObjectCreationOperation creation,
IParameterSymbol parameter,
string stringArgument,
OperationAnalysisContext context)
{
bool matchesParameter = MatchesParameter(targetSymbol, creation, stringArgument);
if (IsMessage(parameter) && matchesParameter)
{
var dictBuilder = ImmutableDictionary.CreateBuilder<string, string?>();
dictBuilder.Add(MessagePosition, parameter.Ordinal.ToString(CultureInfo.InvariantCulture));
return context.Operation.CreateDiagnostic(RuleIncorrectMessage, dictBuilder.ToImmutable(), targetSymbol.Name, stringArgument, parameter.Name, creation.Type.Name);
}
else if (HasParameters(targetSymbol) && IsParameterName(parameter) && !matchesParameter)
{
// Allow argument exceptions in accessors to use the associated property symbol name.
if (!MatchesAssociatedSymbol(targetSymbol, stringArgument))
{
return context.Operation.CreateDiagnostic(RuleIncorrectParameterName, targetSymbol.Name, stringArgument, parameter.Name, creation.Type.Name);
}
}
return null;
}
private static bool IsMessage(IParameterSymbol parameter)
{
return parameter.Name == "message";
}
private static bool IsParameterName(IParameterSymbol parameter)
{
return parameter.Name is "paramName" or "parameterName";
}
private static bool HasParameterNameConstructor(ITypeSymbol type)
{
foreach (ISymbol member in type.GetMembers())
{
if (!member.IsConstructor())
{
continue;
}
foreach (IParameterSymbol parameter in member.GetParameters())
{
if (parameter.Type.SpecialType == SpecialType.System_String
&& IsParameterName(parameter))
{
return true;
}
}
}
return false;
}
private static bool MatchesParameter(ISymbol? symbol, IObjectCreationOperation creation, string stringArgumentValue)
{
if (MatchesParameterCore(symbol, stringArgumentValue))
{
return true;
}
var operation = creation.Parent;
while (operation != null)
{
symbol = null;
switch (operation.Kind)
{
case OperationKind.LocalFunction:
symbol = ((ILocalFunctionOperation)operation).Symbol;
break;
case OperationKind.AnonymousFunction:
symbol = ((IAnonymousFunctionOperation)operation).Symbol;
break;
}
if (symbol != null && MatchesParameterCore(symbol, stringArgumentValue))
{
return true;
}
operation = operation.Parent;
}
return false;
}
private static bool MatchesParameterCore(ISymbol? symbol, string stringArgumentValue)
{
foreach (IParameterSymbol parameter in symbol.GetParameters())
{
if (parameter.Name == stringArgumentValue)
{
return true;
}
}
if (symbol is IMethodSymbol method)
{
if (method.IsGenericMethod)
{
foreach (ITypeParameterSymbol parameter in method.TypeParameters)
{
if (parameter.Name == stringArgumentValue)
{
return true;
}
}
}
}
return false;
}
private static bool MatchesAssociatedSymbol(ISymbol targetSymbol, string stringArgument)
=> targetSymbol.IsAccessorMethod() &&
((IMethodSymbol)targetSymbol).AssociatedSymbol?.Name == stringArgument;
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
namespace Microsoft.Azure.Management.Automation
{
public static partial class ConnectionTypeOperationsExtensions
{
/// <summary>
/// Create a connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update
/// connectiontype operation.
/// </param>
/// <returns>
/// The response model for the create or update connection type
/// operation.
/// </returns>
public static ConnectionTypeCreateOrUpdateResponse CreateOrUpdate(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Create a connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The parameters supplied to the create or update
/// connectiontype operation.
/// </param>
/// <returns>
/// The response model for the create or update connection type
/// operation.
/// </returns>
public static Task<ConnectionTypeCreateOrUpdateResponse> CreateOrUpdateAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, ConnectionTypeCreateOrUpdateParameters parameters)
{
return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None);
}
/// <summary>
/// Delete the connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static AzureOperationResponse Delete(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).DeleteAsync(resourceGroupName, automationAccount, connectionTypeName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Delete the connectiontype. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public static Task<AzureOperationResponse> DeleteAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName)
{
return operations.DeleteAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None);
}
/// <summary>
/// Retrieve the connectiontype identified by connectiontype name.
/// (see http://aka.ms/azureautomationsdk/connectiontypeoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// The response model for the get connection type operation.
/// </returns>
public static ConnectionTypeGetResponse Get(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).GetAsync(resourceGroupName, automationAccount, connectionTypeName);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve the connectiontype identified by connectiontype name.
/// (see http://aka.ms/azureautomationsdk/connectiontypeoperations
/// for more information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='connectionTypeName'>
/// Required. The name of connectiontype.
/// </param>
/// <returns>
/// The response model for the get connection type operation.
/// </returns>
public static Task<ConnectionTypeGetResponse> GetAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount, string connectionTypeName)
{
return operations.GetAsync(resourceGroupName, automationAccount, connectionTypeName, CancellationToken.None);
}
/// <summary>
/// Retrieve a list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static ConnectionTypeListResponse List(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).ListAsync(resourceGroupName, automationAccount);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve a list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static Task<ConnectionTypeListResponse> ListAsync(this IConnectionTypeOperations operations, string resourceGroupName, string automationAccount)
{
return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None);
}
/// <summary>
/// Retrieve next list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static ConnectionTypeListResponse ListNext(this IConnectionTypeOperations operations, string nextLink)
{
return Task.Factory.StartNew((object s) =>
{
return ((IConnectionTypeOperations)s).ListNextAsync(nextLink);
}
, operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Retrieve next list of connectiontypes. (see
/// http://aka.ms/azureautomationsdk/connectiontypeoperations for more
/// information)
/// </summary>
/// <param name='operations'>
/// Reference to the
/// Microsoft.Azure.Management.Automation.IConnectionTypeOperations.
/// </param>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <returns>
/// The response model for the list connection type operation.
/// </returns>
public static Task<ConnectionTypeListResponse> ListNextAsync(this IConnectionTypeOperations operations, string nextLink)
{
return operations.ListNextAsync(nextLink, CancellationToken.None);
}
}
}
| |
/*
* Copyright 2002-2010 the original author or 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;
using System.Collections.Generic;
using System.Reflection;
using Spring.Collections;
using Spring.Util;
using Spring.Core;
namespace Spring.Transaction.Interceptor
{
/// <summary>
/// Abstract implementation of
/// <see cref="Spring.Transaction.Interceptor.ITransactionAttributeSource"/>
/// that caches attributes for methods, and implements a default fallback policy.
/// </summary>
/// <remarks>
/// <p>
/// The default fallback policy applied by this class is:
/// <list type="numbered">
/// <item>
/// <description>most specific method</description>
/// </item>
/// <item>
/// <description>target class attribute</description>
/// </item>
/// <item>
/// <description>declaring method</description>
/// </item>
/// <item>
/// <description>declaring class</description>
/// </item>
/// </list>
/// </p>
/// <p>
/// Defaults to using class's transaction attribute if none is associated
/// with the target method. Any transaction attribute associated with the
/// target method completely overrides a class transaction attribute.
/// </p>
/// <p>
/// This implementation caches attributes by method after they are first used.
/// If it's ever desirable to allow dynamic changing of transaction attributes
/// (unlikely) caching could be made configurable. Caching is desirable because
/// of the cost of evaluating rollback rules.
/// </p>
/// </remarks>
/// <author>Rod Johnson</author>
/// <author>Griffin Caprio (.NET)</author>
/// <author>Mark Pollack (.NET)</author>
public abstract class AbstractFallbackTransactionAttributeSource : ITransactionAttributeSource
{
/// <summary>
/// Canonical value held in cache to indicate no transaction attibute was found
/// for this method, and we don't need to look again.
/// </summary>
private static readonly object NULL_TX_ATTIBUTE = new object();
/// <summary>
/// Cache of <see cref="ITransactionAttribute"/>s, keyed by method and target class.
/// </summary>
private readonly IDictionary _transactionAttibuteCache = new Hashtable();
/// <summary>
/// Creates a new instance of the
/// <see cref="Spring.Transaction.Interceptor.AbstractFallbackTransactionAttributeSource"/>
/// class.
/// </summary>
/// <remarks>
/// <p>
/// This is an <see langword="abstract"/> class, and as such exposes no public constructors.
/// </p>
/// </remarks>
protected AbstractFallbackTransactionAttributeSource()
{
}
/// <summary>
/// Subclasses should implement this to return all attributes for this method.
/// May return null.
/// </summary>
/// <remarks>
/// We need all because of the need to analyze rollback rules.
/// </remarks>
/// <param name="method">The method to retrieve attributes for.</param>
/// <returns>The transactional attributes associated with the method.</returns>
protected abstract Attribute[] FindAllAttributes(MethodInfo method);
/// <summary>
/// Subclasses should implement this to return all attributes for this class.
/// May return null.
/// </summary>
/// <param name="targetType">
/// The <see cref="System.Type"/> to retrieve attributes for.
/// </param>
/// <returns>
/// All attributes associated with the supplied <paramref name="targetType"/>.
/// </returns>
protected abstract Attribute[] FindAllAttributes(Type targetType);
/// <summary>
/// Return the transaction attribute for this method invocation.
/// </summary>
/// <remarks>
/// Defaults to the class's transaction attribute if no method
/// attribute is found
/// </remarks>
/// <param name="method">method for the current invocation. Can't be null</param>
/// <param name="targetType">target class for this invocation. May be null.</param>
/// <returns><see cref="ITransactionAttribute"/> for this method, or null if the method is non-transactional</returns>
public ITransactionAttribute ReturnTransactionAttribute(MethodInfo method, Type targetType)
{
object cacheKey = GetCacheKey(method, targetType);
lock (_transactionAttibuteCache)
{
object cached = _transactionAttibuteCache[cacheKey];
if (cached != null)
{
if (NULL_TX_ATTIBUTE == cached)
{
return null;
}
{
return (ITransactionAttribute)cached;
}
}
else
{
ITransactionAttribute transactionAttribute = ComputeTransactionAttribute(method, targetType);
if (null == transactionAttribute)
{
_transactionAttibuteCache.Add(cacheKey, NULL_TX_ATTIBUTE);
}
else
{
_transactionAttibuteCache.Add(cacheKey, transactionAttribute);
}
return transactionAttribute;
}
}
}
/// <summary>
/// Return the transaction attribute, given this set of attributes
/// attached to a method or class. Return null if it's not transactional.
/// </summary>
/// <remarks>
/// Protected rather than private as subclasses may want to customize
/// how this is done: for example, returning a
/// <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/>
/// affected by the values of other attributes.
/// This implementation takes into account
/// <see cref="Spring.Transaction.Interceptor.RollbackRuleAttribute"/>s, if
/// the TransactionAttribute is a RuleBasedTransactionAttribute.
/// </remarks>
/// <param name="attributes">
/// Attributes attached to a method or class. May be null, in which case a null
/// <see cref="Spring.Transaction.Interceptor.ITransactionAttribute"/> will be returned.
/// </param>
/// <returns>
/// The <see cref="ITransactionAttribute"/> configured transaction attribute, or null
/// if none was found.
/// </returns>
protected virtual ITransactionAttribute FindTransactionAttribute(Attribute[] attributes)
{
if (null == attributes)
{
return null;
}
ITransactionAttribute transactionAttribute = null;
foreach (Attribute currentAttribute in attributes)
{
transactionAttribute = currentAttribute as ITransactionAttribute;
if (null != transactionAttribute)
{
break;
}
}
if (transactionAttribute is RuleBasedTransactionAttribute ruleBasedTransactionAttribute)
{
var rollbackRules = new List<RollbackRuleAttribute>();
foreach (Attribute currentAttribute in attributes)
{
if (currentAttribute is RollbackRuleAttribute rollbackRuleAttribute)
{
rollbackRules.Add(rollbackRuleAttribute);
}
}
ruleBasedTransactionAttribute.RollbackRules = rollbackRules;
return ruleBasedTransactionAttribute;
}
return transactionAttribute;
}
private static object GetCacheKey(MethodBase method, Type targetType)
{
return string.Intern(targetType.AssemblyQualifiedName + "." + method);
}
private ITransactionAttribute ComputeTransactionAttribute(MethodInfo method, Type targetType)
{
MethodInfo specificMethod;
if (targetType == null)
{
specificMethod = method;
}
else
{
ParameterInfo[] parameters = method.GetParameters();
ComposedCriteria searchCriteria = new ComposedCriteria();
searchCriteria.Add(new MethodNameMatchCriteria(method.Name));
searchCriteria.Add(new MethodParametersCountCriteria(parameters.Length));
searchCriteria.Add(new MethodGenericArgumentsCountCriteria(method.GetGenericArguments().Length));
searchCriteria.Add(new MethodParametersCriteria(ReflectionUtils.GetParameterTypes(parameters)));
MemberInfo[] matchingMethods = targetType.FindMembers(
MemberTypes.Method,
BindingFlags.Instance | BindingFlags.Public,
new MemberFilter(new CriteriaMemberFilter().FilterMemberByCriteria),
searchCriteria);
if (matchingMethods != null && matchingMethods.Length == 1)
{
specificMethod = matchingMethods[0] as MethodInfo;
}
else
{
specificMethod = method;
}
}
ITransactionAttribute transactionAttribute = GetTransactionAttribute(specificMethod);
if (null != transactionAttribute)
{
return transactionAttribute;
}
else if (specificMethod != method)
{
transactionAttribute = GetTransactionAttribute(method);
}
return null;
}
private ITransactionAttribute GetTransactionAttribute(MethodInfo methodInfo)
{
ITransactionAttribute transactionAttribute = FindTransactionAttribute(FindAllAttributes(methodInfo));
if (null != transactionAttribute)
{
return transactionAttribute;
}
transactionAttribute = FindTransactionAttribute(FindAllAttributes(methodInfo.DeclaringType));
if (null != transactionAttribute)
{
return transactionAttribute;
}
return null;
}
}
}
| |
using System;
using Shouldly;
using Xunit;
namespace AutoMapper.UnitTests.Bug
{
namespace InterfaceMultipleInheritance
{
public class InterfaceMultipleInheritanceBug1036 : AutoMapperSpecBase
{
private MapTo _destination;
public interface IMapFrom
{
IMapFromElement Element { get; }
}
public interface IMapFromElement
{
string Prop { get; }
}
public interface IMapFromElementDerived1 : IMapFromElement
{
string Prop2 { get; }
}
public interface IMapFromElementDerived2 : IMapFromElement
{
}
public interface IMapFromElementDerivedBoth : IMapFromElementDerived1, IMapFromElementDerived2
{
}
public interface IMapToElementWritable
{
string Prop { get; set; }
}
public interface IMapToElementWritableDerived : IMapToElementWritable
{
string Prop2 { get; set; }
}
public class MapFrom : IMapFrom
{
public MapFromElement Element { get; set; }
IMapFromElement IMapFrom.Element => Element;
}
public class MapFromElement : IMapFromElement
{
public string Prop { get; set; }
}
public class MapFromElementDerived : MapFromElement, IMapFromElementDerivedBoth
{
public new string Prop { get; set; }
public string Prop2 { get; set; }
}
public class MapTo
{
public IMapToElementWritable Element { get; set; }
}
public abstract class MapToElement : IMapToElementWritable
{
public string Prop { get; set; }
}
public class MapToElementDerived : MapToElement, IMapToElementWritableDerived
{
public string Prop2 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<IMapFrom, MapTo>();
cfg.CreateMap<IMapFromElement, IMapToElementWritable>()
.Include<IMapFromElementDerived1, IMapToElementWritableDerived>();
cfg.CreateMap<IMapFromElementDerived1, IMapToElementWritableDerived>()
.ConstructUsing(src => new MapToElementDerived());
});
protected override void Because_of()
{
var source = new MapFrom
{
Element = new MapFromElementDerived { Prop = "PROP1", Prop2 = "PROP2" }
};
_destination = Mapper.Map<MapTo>(source);
}
[Fact]
public void Should_Map_UsingDerivedInterface()
{
var element = (IMapToElementWritableDerived)_destination.Element;
element.Prop2.ShouldBe("PROP2");
}
}
public class InterfaceMultipleInheritanceBug1016 : AutoMapperSpecBase
{
private class4DTO _destination;
public abstract class class1 : iclass1
{
public string prop1 { get; set; }
}
public class class2 : class1, iclass2
{
public string prop2 { get; set; }
}
public class class3 : class2, iclass3
{
public string prop3 { get; set; }
}
public class class4 : class3, iclass4
{
public string prop4 { get; set; }
}
public abstract class class1DTO : iclass1DTO
{
public string prop1 { get; set; }
}
public class class2DTO : class1DTO, iclass2DTO
{
public string prop2 { get; set; }
}
public class class3DTO : class2DTO, iclass3DTO
{
public string prop3 { get; set; }
}
public class class4DTO : class3DTO, iclass4DTO
{
public string prop4 { get; set; }
}
public interface iclass1
{
string prop1 { get; set; }
}
public interface iclass2 : iclass1
{
string prop2 { get; set; }
}
public interface iclass3 : iclass2
{
string prop3 { get; set; }
}
public interface iclass4 : iclass3
{
string prop4 { get; set; }
}
public interface iclass1DTO
{
string prop1 { get; set; }
}
public interface iclass2DTO : iclass1DTO
{
string prop2 { get; set; }
}
public interface iclass3DTO : iclass2DTO
{
string prop3 { get; set; }
}
public interface iclass4DTO : iclass3DTO
{
string prop4 { get; set; }
}
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<iclass1, iclass1DTO>()
.Include<iclass2, iclass2DTO>()
.Include<iclass3, iclass3DTO>()
.Include<iclass4, iclass4DTO>();
cfg.CreateMap<iclass2, iclass2DTO>();
cfg.CreateMap<iclass3, iclass3DTO>();
cfg.CreateMap<iclass4, iclass4DTO>()
.ConstructUsing(src => new class4DTO());
});
protected override void Because_of()
{
iclass4 source = new class4();
source.prop1 = "PROP1";
source.prop2 = "PROP2";
source.prop3 = "PROP3";
source.prop4 = "PROP4";
_destination = new class4DTO();
Mapper.Map<iclass4, iclass4DTO>(source, _destination);
}
[Fact]
public void Should_Map_UsingDerivedInterface()
{
_destination.prop4.ShouldBe("PROP4");
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Realms;
using Realms.Exceptions;
namespace Tests.Database
{
[TestFixture, Preserve(AllMembers = true)]
public class AddOrUpdateTests : RealmInstanceTest
{
[Test]
public void AddOrUpdate_WhenDoesntExist_ShouldAdd()
{
var standalone = new PrimaryKeyObject
{
Id = 1,
StringValue = "bla"
};
_realm.Write(() =>
{
_realm.Add(standalone, update: true);
});
Assert.That(standalone.IsManaged, Is.True);
var queried = _realm.Find<PrimaryKeyObject>(1);
Assert.That(queried, Is.EqualTo(standalone));
}
[Test]
public void AddOrUpdate_WhenExists_ShouldUpdate()
{
var first = new PrimaryKeyObject
{
Id = 1,
StringValue = "first"
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyObject
{
Id = 1,
StringValue = "second"
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
var queried = _realm.Find<PrimaryKeyObject>(1);
Assert.That(queried.StringValue, Is.EqualTo("second"));
Assert.That(first.StringValue, Is.EqualTo("second"));
Assert.That(second.StringValue, Is.EqualTo("second"));
}
[Test]
public void AddOrUpdate_WhenNoPrimaryKey_ShouldAdd()
{
var noPK = new NonPrimaryKeyObject
{
StringValue = "123"
};
_realm.Write(() =>
{
_realm.Add(noPK, update: true);
});
var noPK2 = new NonPrimaryKeyObject
{
StringValue = "123"
};
_realm.Write(() =>
{
_realm.Add(noPK2, update: true);
});
Assert.That(noPK2, Is.Not.EqualTo(noPK));
Assert.That(_realm.All<NonPrimaryKeyObject>().Count(), Is.EqualTo(2));
}
[Test]
public void AddOrUpdate_WhenParentAndChildDontExist_ShouldAddBoth()
{
var first = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var queried = _realm.Find<PrimaryKeyWithPKRelation>(1);
Assert.That(queried.OtherObject, Is.Not.Null);
Assert.That(queried.StringValue, Is.EqualTo("parent"));
Assert.That(queried.OtherObject.StringValue, Is.EqualTo("child"));
}
[Test]
public void AddOrUpdate_WhenParentExistsChildDoesnt_ShouldAddChild()
{
var first = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new PrimaryKeyObject
{
Id = 2,
StringValue = "child2"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
var queried = _realm.Find<PrimaryKeyWithPKRelation>(1);
Assert.That(queried.OtherObject, Is.Not.Null);
Assert.That(queried.StringValue, Is.EqualTo("parent"));
Assert.That(queried.OtherObject.StringValue, Is.EqualTo("child2"));
var child1 = _realm.Find<PrimaryKeyObject>(1);
Assert.That(child1.StringValue, Is.EqualTo("child"));
var child2 = _realm.Find<PrimaryKeyObject>(2);
Assert.That(child2.StringValue, Is.EqualTo("child2"));
}
[Test]
public void AddOrUpdate_WhenParentAndChildExist_ShouldUpdateBoth()
{
var first = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent2",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child2"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
var queried = _realm.Find<PrimaryKeyWithPKRelation>(1);
Assert.That(queried.OtherObject, Is.Not.Null);
Assert.That(queried.StringValue, Is.EqualTo("parent2"));
Assert.That(queried.OtherObject.StringValue, Is.EqualTo("child2"));
var child1 = _realm.Find<PrimaryKeyObject>(1);
Assert.That(child1.StringValue, Is.EqualTo("child2"));
}
[Test]
public void AddOrUpdate_WhenChildHasNoPK_ShouldAddChild()
{
var first = new PrimaryKeyWithNonPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new NonPrimaryKeyObject
{
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithNonPKRelation
{
Id = 2,
StringValue = "parent2",
OtherObject = new NonPrimaryKeyObject
{
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(second.OtherObject, Is.Not.EqualTo(first.OtherObject));
Assert.That(_realm.All<NonPrimaryKeyObject>().Count(), Is.EqualTo(2));
}
[Test]
public void AddOrUpdate_WhenChildHasPK_ShouldUpdateChild()
{
var first = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithPKRelation
{
Id = 2,
StringValue = "parent2",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child2"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(second.OtherObject, Is.EqualTo(first.OtherObject));
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(1));
Assert.That(_realm.Find<PrimaryKeyObject>(1).StringValue, Is.EqualTo("child2"));
}
[Test]
public void AddOrUpdate_WhenListHasPK_ShouldUpdateListItems()
{
var first = new PrimaryKeyWithPKList
{
Id = 1,
StringValue = "first"
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
});
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithPKList
{
Id = 2,
StringValue = "second"
};
second.ListValue.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "secondChild"
});
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(first.ListValue, Is.EqualTo(second.ListValue));
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(1));
Assert.That(_realm.Find<PrimaryKeyObject>(1).StringValue, Is.EqualTo("secondChild"));
}
// confirm when we do this in a single Write that child objects correctly owned
[Test]
public void AddOrUpdate_WhenListHasPK_ShouldUpdateListItemsSingleWrite()
{
PrimaryKeyWithPKList first = null;
_realm.Write(() =>
{
for (var i = 0; i < 10; i++)
{
first = new PrimaryKeyWithPKList
{
Id = 1,
StringValue = "first"
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
});
first.ListValue.Add(new PrimaryKeyObject
{
Id = 2,
StringValue = "secondChild"
});
_realm.Add(first, update: true);
}
});
Assert.That(first.ListValue.Count(), Is.EqualTo(2)); // did the Add keep adding dups?
Assert.That(_realm.Find<PrimaryKeyWithPKList>(1).ListValue.Count(), Is.EqualTo(2));
Assert.That(_realm.Find<PrimaryKeyObject>(1).StringValue, Is.EqualTo("child"));
Assert.That(_realm.Find<PrimaryKeyObject>(2).StringValue, Is.EqualTo("secondChild"));
}
[Test]
public void AddOrUpdate_WhenListHasNoPK_ShouldAddListItems()
{
var first = new PrimaryKeyWithNoPKList
{
Id = 1,
StringValue = "first"
};
first.ListValue.Add(new NonPrimaryKeyObject
{
StringValue = "child"
});
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new PrimaryKeyWithNoPKList
{
Id = 2,
StringValue = "second"
};
second.ListValue.Add(new NonPrimaryKeyObject
{
StringValue = "secondChild"
});
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(first.ListValue, Is.Not.EqualTo(second.ListValue));
Assert.That(_realm.All<NonPrimaryKeyObject>().Count(), Is.EqualTo(2));
}
[Test]
public void AddOrUpdate_WhenListHasPK_ShouldAddNewAndUpdateOldItems()
{
var first = new PrimaryKeyWithPKList
{
Id = 1,
StringValue = "first"
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
});
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var updatedFirst = new PrimaryKeyWithPKList
{
Id = 1,
StringValue = "updated first"
};
updatedFirst.ListValue.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "updated child"
});
updatedFirst.ListValue.Add(new PrimaryKeyObject
{
Id = 2,
StringValue = "new child"
});
_realm.Write(() =>
{
_realm.Add(updatedFirst, update: true);
});
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(2));
Assert.That(_realm.Find<PrimaryKeyObject>(1).StringValue, Is.EqualTo("updated child"));
Assert.That(_realm.Find<PrimaryKeyObject>(2).StringValue, Is.EqualTo("new child"));
}
[Test]
public void AddOrUpdate_WhenParentHasNoPKChildHasPK_ShouldAddParentUpdateChild()
{
var first = new NonPrimaryKeyWithPKRelation
{
StringValue = "first parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new NonPrimaryKeyWithPKRelation
{
StringValue = "second parent",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "updated child"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(_realm.All<NonPrimaryKeyWithPKRelation>().Count(), Is.EqualTo(2));
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(1));
Assert.That(_realm.Find<PrimaryKeyObject>(1).StringValue, Is.EqualTo("updated child"));
}
[Test]
public void AddOrUpdate_WhenParentHasNoPKChildHasNoPK_ShouldAddBoth()
{
var first = new NonPrimaryKeyWithNonPKRelation
{
StringValue = "first parent",
OtherObject = new NonPrimaryKeyObject
{
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new NonPrimaryKeyWithNonPKRelation
{
StringValue = "second parent",
OtherObject = new NonPrimaryKeyObject
{
StringValue = "second child"
}
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(_realm.All<NonPrimaryKeyWithNonPKRelation>().Count(), Is.EqualTo(2));
Assert.That(_realm.All<NonPrimaryKeyObject>().Count(), Is.EqualTo(2));
}
[Test]
public void AddOrUpdate_WhenRelationIsNull_ShouldClearLink()
{
var first = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "has child",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "child"
}
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var updatedFirst = new PrimaryKeyWithPKRelation
{
Id = 1,
StringValue = "no child"
};
_realm.Write(() =>
{
_realm.Add(updatedFirst, update: true);
});
Assert.That(first.OtherObject, Is.Null);
Assert.That(updatedFirst.OtherObject, Is.Null);
Assert.That(_realm.Find<PrimaryKeyWithPKRelation>(1).OtherObject, Is.Null);
}
[Test, Ignore("Cyclic relations don't work yet.")]
public void CyclicRelations_ShouldWork()
{
var parent = new Parent
{
Id = 1,
Name = "Peter",
Child = new Child
{
Id = 1,
Name = "Kate",
Parent = new Parent
{
Id = 1
}
}
};
_realm.Write(() =>
{
_realm.Add(parent, update: true);
});
var persistedParent = _realm.Find<Parent>(1);
var persistedChild = _realm.Find<Child>(1);
Assert.That(persistedParent.Name, Is.EqualTo("Peter"));
Assert.That(persistedChild.Name, Is.EqualTo("Kate"));
Assert.That(persistedParent.Child, Is.Not.Null);
Assert.That(persistedChild.Parent, Is.Not.Null);
Assert.That(persistedChild.Parent.Name, Is.EqualTo("Peter"));
Assert.That(persistedParent.Child.Name, Is.EqualTo("Kate"));
}
[Test]
public void AddOrUpdate_WhenChildHasNoPKAndGrandchildHasPK_ShouldAddChildUpdateGrandchild()
{
var parent = new PrimaryKeyWithNonPKChildWithPKGrandChild
{
Id = 1,
StringValue = "parent",
NonPKChild = new NonPrimaryKeyWithPKRelation
{
StringValue = "child",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "grandchild"
}
}
};
_realm.Write(() =>
{
_realm.Add(parent, update: true);
});
var updatedParent = new PrimaryKeyWithNonPKChildWithPKGrandChild
{
Id = 1,
StringValue = "updated parent",
NonPKChild = new NonPrimaryKeyWithPKRelation
{
StringValue = "new child",
OtherObject = new PrimaryKeyObject
{
Id = 1,
StringValue = "updated grandchild"
}
}
};
_realm.Write(() =>
{
_realm.Add(updatedParent, update: true);
});
var persistedParent = _realm.Find<PrimaryKeyWithNonPKChildWithPKGrandChild>(1);
Assert.That(persistedParent.StringValue, Is.EqualTo("updated parent"));
Assert.That(persistedParent.NonPKChild, Is.Not.Null);
Assert.That(persistedParent.NonPKChild.StringValue, Is.EqualTo("new child"));
Assert.That(persistedParent.NonPKChild.OtherObject, Is.Not.Null);
Assert.That(persistedParent.NonPKChild.OtherObject.StringValue, Is.EqualTo("updated grandchild"));
Assert.That(_realm.All<PrimaryKeyWithNonPKChildWithPKGrandChild>().Count(), Is.EqualTo(1));
Assert.That(_realm.All<NonPrimaryKeyWithPKRelation>().Count(), Is.EqualTo(2));
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(1));
}
[Test]
public void AddOrUpdate_WhenPKIsNull_ShouldUpdate()
{
var first = new NullablePrimaryKeyObject
{
StringValue = "first"
};
_realm.Write(() =>
{
_realm.Add(first, update: true);
});
var second = new NullablePrimaryKeyObject
{
StringValue = "second"
};
_realm.Write(() =>
{
_realm.Add(second, update: true);
});
Assert.That(first.StringValue, Is.EqualTo("second"));
Assert.That(second.StringValue, Is.EqualTo("second"));
Assert.That(_realm.All<NullablePrimaryKeyObject>().Count(), Is.EqualTo(1));
}
[Test]
public void Add_ShouldReturnPassedInObject()
{
var first = new Person
{
FirstName = "Peter"
};
Person added = null;
_realm.Write(() =>
{
added = _realm.Add(first, update: false);
});
Assert.That(added, Is.SameAs(first));
}
[Test]
public void AddOrUpdate_ShouldReturnPassedInObject()
{
var first = new PrimaryKeyObject
{
Id = 1,
StringValue = "1"
};
PrimaryKeyObject firstAdded = null;
_realm.Write(() =>
{
firstAdded = _realm.Add(first, update: true);
});
Assert.That(firstAdded, Is.SameAs(first));
var second = new PrimaryKeyObject
{
Id = 1,
StringValue = "2"
};
PrimaryKeyObject secondAdded = null;
_realm.Write(() =>
{
secondAdded = _realm.Add(second, update: true);
});
Assert.That(secondAdded, Is.SameAs(second));
Assert.That(first.StringValue, Is.EqualTo("2"));
Assert.That(firstAdded.StringValue, Is.EqualTo("2"));
Assert.That(second.StringValue, Is.EqualTo("2"));
Assert.That(secondAdded.StringValue, Is.EqualTo("2"));
}
[Test]
public void Add_ShouldReturnManaged()
{
Person person = null;
_realm.Write(() =>
{
person = _realm.Add(new Person
{
FirstName = "Peter"
});
});
Assert.That(person.IsManaged);
Assert.That(person.FirstName == "Peter");
}
[Test]
public void AddOrUpdate_ShouldReturnManaged()
{
PrimaryKeyObject item = null;
_realm.Write(() =>
{
item = _realm.Add(new PrimaryKeyObject
{
Id = 1,
StringValue = "1"
}, update: true);
});
Assert.That(item.IsManaged);
Assert.That(item.StringValue == "1");
}
[TestCase(typeof(PrimaryKeyCharObject))]
[TestCase(typeof(PrimaryKeyByteObject))]
[TestCase(typeof(PrimaryKeyInt16Object))]
[TestCase(typeof(PrimaryKeyInt32Object))]
[TestCase(typeof(PrimaryKeyInt64Object))]
[TestCase(typeof(PrimaryKeyNullableCharObject))]
[TestCase(typeof(PrimaryKeyNullableByteObject))]
[TestCase(typeof(PrimaryKeyNullableInt16Object))]
[TestCase(typeof(PrimaryKeyNullableInt32Object))]
[TestCase(typeof(PrimaryKeyNullableInt64Object))]
public void Add_WhenPKIsDefaultAndDuplicate_ShouldThrow(Type type)
{
Assert.That(() =>
{
_realm.Write(() =>
{
_realm.Add((RealmObject)Activator.CreateInstance(type));
_realm.Add((RealmObject)Activator.CreateInstance(type));
});
}, Throws.TypeOf<RealmDuplicatePrimaryKeyValueException>());
}
[Test]
public void Add_WhenPKIsStringAndNull_ShouldThrow()
{
Assert.That(() =>
{
_realm.Write(() =>
{
_realm.Add(new PrimaryKeyStringObject());
});
}, Throws.TypeOf<ArgumentNullException>());
}
[Test]
public void Add_WhenPKIsNotDefaultButDuplicate_ShouldThrow()
{
Assert.That(() =>
{
_realm.Write(() =>
{
_realm.Add(new PrimaryKeyStringObject { StringProperty = "1" });
_realm.Add(new PrimaryKeyStringObject { StringProperty = "1" });
});
}, Throws.TypeOf<RealmDuplicatePrimaryKeyValueException>());
}
[Test]
public void Add_WhenRequiredPropertyIsNotSet_ShouldThrow()
{
Assert.That(() =>
{
_realm.Write(() =>
{
_realm.Add(new RequiredStringObject());
});
}, Throws.TypeOf<RealmException>());
}
[Test]
public void AddOrUpdate_WhenObjectHasNonEmptyList_ShouldNotThrow()
{
// This test verifies that updating an object that has PK and non-empty list will not throw an exception.
// The reason it *could* throw is a limitation on core in table.cpp: Table::check_lists_are_empty.
// The comment states:
// FIXME: Due to a limitation in Sync, it is not legal to change the primary
// key of a row that contains lists (including linklists) after those lists
// have been populated. This limitation may be lifted in the future, but for
// now it is necessary to ensure that all lists are empty before setting a
// primary key (by way of set_int_unique() or set_string_unique() or set_null_unique()).
//
// So if we set the Primary Key unnecessarily in the .NET binding, we could trigger that case.
var first = new PrimaryKeyWithPKList
{
Id = 42,
StringValue = "value1"
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1
});
_realm.Write(() => _realm.Add(first));
var second = new PrimaryKeyWithPKList
{
Id = 42,
StringValue = "value2"
};
second.ListValue.Add(new PrimaryKeyObject
{
Id = 1
});
Assert.That(() =>
{
_realm.Write(() => _realm.Add(second, update: true));
}, Throws.Nothing);
}
[Test]
public void AddOrUpdate_WhenListIsNull_ShouldNotThrow()
{
var first = new PrimaryKeyWithPKList
{
Id = 42
};
Assert.That(() =>
{
_realm.Write(() => _realm.Add(first, update: true));
}, Throws.Nothing);
}
[Test]
public void AddOrUpdate_WhenNewListIsNull_ShouldNotThrow()
{
var first = new PrimaryKeyWithPKList
{
Id = 1
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1
});
_realm.Write(() => _realm.Add(first));
var second = new PrimaryKeyWithPKList
{
Id = 1
};
// second.listValue is null, because the getter is never invoked.
_realm.Write(() => _realm.Add(second, update: true));
Assert.That(first.ListValue, Is.EquivalentTo(second.ListValue));
// Verify that the original list was cleared
Assert.That(first.ListValue.Count, Is.EqualTo(0));
// Verify that clearing the list hasn't deleted the item from the Realm.
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(1));
}
[Test]
public void AddOrUpdate_WhenListObjectsHavePK_ShouldOverwriteList()
{
// Original object - has 2 elements in the list
var first = new PrimaryKeyWithPKList
{
Id = 1
};
first.ListValue.Add(new PrimaryKeyObject
{
Id = 1
});
first.ListValue.Add(new PrimaryKeyObject
{
Id = 2
});
_realm.Write(() => _realm.Add(first));
// Object to update with - has 1 element in the list
var second = new PrimaryKeyWithPKList
{
Id = 1
};
second.ListValue.Add(new PrimaryKeyObject
{
Id = 3
});
_realm.Write(() => _realm.Add(second, update: true));
Assert.That(first.ListValue, Is.EquivalentTo(second.ListValue));
// Verify that the original list was replaced with the new one.
Assert.That(first.ListValue.Count, Is.EqualTo(1));
// Verify that the list's sole element has the correct Id.
Assert.That(first.ListValue[0].Id, Is.EqualTo(3));
// Verify that overwriting the list hasn't deleted any elements from the Realm.
Assert.That(_realm.All<PrimaryKeyObject>().Count(), Is.EqualTo(3));
}
[Test]
public void AddOrUpdate_WhenListObjectsDontHavePK_ShouldOverwriteList()
{
var first = new PrimaryKeyWithNoPKList
{
Id = 1
};
first.ListValue.Add(new NonPrimaryKeyObject
{
StringValue = "1"
});
_realm.Write(() => _realm.Add(first));
var second = new PrimaryKeyWithNoPKList
{
Id = 1
};
second.ListValue.Add(new NonPrimaryKeyObject
{
StringValue = "2"
});
_realm.Write(() => _realm.Add(second, update: true));
Assert.That(first.ListValue, Is.EquivalentTo(second.ListValue));
// Verify that the original list was replaced with the new one and not merged with it.
Assert.That(first.ListValue.Count, Is.EqualTo(1));
// Verify that the list's sole element has the correct String value.
Assert.That(first.ListValue[0].StringValue, Is.EqualTo("2"));
// Verify that overwriting the list hasn't deleted any elements from the Realm.
Assert.That(_realm.All<NonPrimaryKeyObject>().Count(), Is.EqualTo(2));
}
private class Parent : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string Name { get; set; }
public Child Child { get; set; }
}
private class Child : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string Name { get; set; }
public Parent Parent { get; set; }
}
private class PrimaryKeyWithNonPKChildWithPKGrandChild : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
public NonPrimaryKeyWithPKRelation NonPKChild { get; set; }
}
private class NonPrimaryKeyObject : RealmObject
{
public string StringValue { get; set; }
}
private class PrimaryKeyObject : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
}
private class NullablePrimaryKeyObject : RealmObject
{
[PrimaryKey]
public long? Id { get; set; }
public string StringValue { get; set; }
}
private class PrimaryKeyWithPKRelation : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
public PrimaryKeyObject OtherObject { get; set; }
}
private class PrimaryKeyWithNonPKRelation : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
public NonPrimaryKeyObject OtherObject { get; set; }
}
private class PrimaryKeyWithPKList : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
public IList<PrimaryKeyObject> ListValue { get; }
}
private class PrimaryKeyWithNoPKList : RealmObject
{
[PrimaryKey]
public long Id { get; set; }
public string StringValue { get; set; }
public IList<NonPrimaryKeyObject> ListValue { get; }
}
private class NonPrimaryKeyWithPKRelation : RealmObject
{
public string StringValue { get; set; }
public PrimaryKeyObject OtherObject { get; set; }
}
private class NonPrimaryKeyWithNonPKRelation : RealmObject
{
public string StringValue { get; set; }
public NonPrimaryKeyObject OtherObject { get; set; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// 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.
//
// Author:
//
// Jordi Mas i Hernandez, jordimash@gmail.com
//
using System.Runtime.InteropServices;
using System.Collections;
using System.Drawing.Printing;
using System.ComponentModel;
using System.Drawing.Imaging;
using System.Diagnostics;
using System.Text;
using System.IO;
using System.Collections.Specialized;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Printing
{
/// <summary>
/// This class is designed to cache the values retrieved by the
/// native printing services, as opposed to GlobalPrintingServices, which
/// doesn't cache any values.
/// </summary>
internal static class PrintingServices
{
#region Private Fields
private static Hashtable doc_info = new Hashtable();
private static bool cups_installed;
private static Hashtable installed_printers;
private static string default_printer = string.Empty;
#endregion
#region Constructor
static PrintingServices()
{
installed_printers = new Hashtable();
CheckCupsInstalled();
}
#endregion
#region Properties
internal static PrinterSettings.StringCollection InstalledPrinters
{
get
{
LoadPrinters();
PrinterSettings.StringCollection list = new PrinterSettings.StringCollection(Array.Empty<string>());
foreach (object key in installed_printers.Keys)
{
list.Add(key.ToString());
}
return list;
}
}
internal static string DefaultPrinter
{
get
{
if (installed_printers.Count == 0)
LoadPrinters();
return default_printer;
}
}
#endregion
#region Methods
/// <summary>
/// Do a cups call to check if it is installed
/// </summary>
private static void CheckCupsInstalled()
{
try
{
LibcupsNative.cupsGetDefault();
}
catch (DllNotFoundException)
{
#if NETCORE
System.Diagnostics.Debug.WriteLine("libcups not found. To have printing support, you need cups installed");
#else
Console.WriteLine("libcups not found. To have printing support, you need cups installed");
#endif
cups_installed = false;
return;
}
cups_installed = true;
}
/// <summary>
/// Open the printer's PPD file
/// </summary>
/// <param name="printer">Printer name, returned from cupsGetDests</param>
private static IntPtr OpenPrinter(string printer)
{
try
{
IntPtr ptr = LibcupsNative.cupsGetPPD(printer);
string ppd_filename = Marshal.PtrToStringAnsi(ptr);
IntPtr ppd_handle = LibcupsNative.ppdOpenFile(ppd_filename);
return ppd_handle;
}
catch (Exception)
{
#if NETCORE
System.Diagnostics.Debug.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#else
Console.WriteLine("There was an error opening the printer {0}. Please check your cups installation.");
#endif
}
return IntPtr.Zero;
}
/// <summary>
/// Close the printer file
/// </summary>
/// <param name="handle">PPD handle</param>
private static void ClosePrinter(ref IntPtr handle)
{
try
{
if (handle != IntPtr.Zero)
LibcupsNative.ppdClose(handle);
}
finally
{
handle = IntPtr.Zero;
}
}
private static int OpenDests(ref IntPtr ptr)
{
try
{
return LibcupsNative.cupsGetDests(ref ptr);
}
catch
{
ptr = IntPtr.Zero;
}
return 0;
}
private static void CloseDests(ref IntPtr ptr, int count)
{
try
{
if (ptr != IntPtr.Zero)
LibcupsNative.cupsFreeDests(count, ptr);
}
finally
{
ptr = IntPtr.Zero;
}
}
/// <summary>
/// Checks if a printer has a valid PPD file. Caches the result unless force is true
/// </summary>
/// <param name="printer">Printer name</param>
internal static bool IsPrinterValid(string printer)
{
if (!cups_installed || printer == null | printer == string.Empty)
return false;
return installed_printers.Contains(printer);
}
/// <summary>
/// Loads the printer settings and initializes the PrinterSettings and PageSettings fields
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to initialize</param>
internal static void LoadPrinterSettings(string printer, PrinterSettings settings)
{
if (cups_installed == false || (printer == null) || (printer == string.Empty))
return;
if (installed_printers.Count == 0)
LoadPrinters();
if (((SysPrn.Printer)installed_printers[printer]).Settings != null)
{
SysPrn.Printer p = (SysPrn.Printer)installed_printers[printer];
settings.can_duplex = p.Settings.can_duplex;
settings.is_plotter = p.Settings.is_plotter;
settings.landscape_angle = p.Settings.landscape_angle;
settings.maximum_copies = p.Settings.maximum_copies;
settings.paper_sizes = p.Settings.paper_sizes;
settings.paper_sources = p.Settings.paper_sources;
settings.printer_capabilities = p.Settings.printer_capabilities;
settings.printer_resolutions = p.Settings.printer_resolutions;
settings.supports_color = p.Settings.supports_color;
return;
}
settings.PrinterCapabilities.Clear();
IntPtr dests = IntPtr.Zero, ptr = IntPtr.Zero, ptr_printer, ppd_handle = IntPtr.Zero;
string name = string.Empty;
CUPS_DESTS printer_dest;
PPD_FILE ppd;
int ret = 0, cups_dests_size;
NameValueCollection options, paper_names, paper_sources;
try
{
ret = OpenDests(ref dests);
if (ret == 0)
return;
cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
ptr = dests;
for (int i = 0; i < ret; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
name = printer;
break;
}
ptr = (IntPtr)((long)ptr + cups_dests_size);
}
if (!name.Equals(printer))
{
return;
}
ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
printer_dest = (CUPS_DESTS)Marshal.PtrToStructure(ptr, typeof(CUPS_DESTS));
options = new NameValueCollection();
paper_names = new NameValueCollection();
paper_sources = new NameValueCollection();
string defsize;
string defsource;
LoadPrinterOptions(printer_dest.options, printer_dest.num_options, ppd_handle, options,
paper_names, out defsize,
paper_sources, out defsource);
if (settings.paper_sizes == null)
settings.paper_sizes = new PrinterSettings.PaperSizeCollection(Array.Empty<PaperSize>());
else
settings.paper_sizes.Clear();
if (settings.paper_sources == null)
settings.paper_sources = new PrinterSettings.PaperSourceCollection(Array.Empty<PaperSource>());
else
settings.paper_sources.Clear();
settings.DefaultPageSettings.PaperSource = LoadPrinterPaperSources(settings, defsource, paper_sources);
settings.DefaultPageSettings.PaperSize = LoadPrinterPaperSizes(ppd_handle, settings, defsize, paper_names);
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
settings.landscape_angle = ppd.landscape;
settings.supports_color = (ppd.color_device == 0) ? false : true;
settings.can_duplex = options["Duplex"] != null;
ClosePrinter(ref ppd_handle);
((SysPrn.Printer)installed_printers[printer]).Settings = settings;
}
finally
{
CloseDests(ref dests, ret);
}
}
/// <summary>
/// Loads the global options of a printer plus the paper types and trays supported,
/// and sets the default paper size and source tray.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
/// <param name="ppd">A ppd handle for the printer, returned by ppdOpen</param>
/// <param name="list">The list of options</param>
/// <param name="paper_names">A list of types of paper (PageSize)</param>
/// <param name="defsize">The default paper size, set by LoadOptionList</param>
/// <param name="paper_sources">A list of trays(InputSlot) </param>
/// <param name="defsource">The default source tray, set by LoadOptionList</param>
private static void LoadPrinterOptions(IntPtr options, int numOptions, IntPtr ppd,
NameValueCollection list,
NameValueCollection paper_names, out string defsize,
NameValueCollection paper_sources, out string defsource)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
LoadOptionList(ppd, "PageSize", paper_names, out defsize);
LoadOptionList(ppd, "InputSlot", paper_sources, out defsource);
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
if (option_name == "PageSize")
defsize = option_value;
else if (option_name == "InputSlot")
defsource = option_value;
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
}
/// <summary>
/// Loads the global options of a printer.
/// </summary>
/// <param name="options">The options field of a printer's CUPS_DESTS structure</param>
/// <param name="numOptions">The number of options of the printer</param>
private static NameValueCollection LoadPrinterOptions(IntPtr options, int numOptions)
{
CUPS_OPTIONS cups_options;
string option_name, option_value;
int cups_size = Marshal.SizeOf(typeof(CUPS_OPTIONS));
NameValueCollection list = new NameValueCollection();
for (int j = 0; j < numOptions; j++)
{
cups_options = (CUPS_OPTIONS)Marshal.PtrToStructure(options, typeof(CUPS_OPTIONS));
option_name = Marshal.PtrToStringAnsi(cups_options.name);
option_value = Marshal.PtrToStringAnsi(cups_options.val);
#if PrintDebug
Console.WriteLine("{0} = {1}", option_name, option_value);
#endif
list.Add(option_name, option_value);
options = (IntPtr)((long)options + cups_size);
}
return list;
}
/// <summary>
/// Loads a printer's options (selection of paper sizes, paper sources, etc)
/// and sets the default option from the selected list.
/// </summary>
/// <param name="ppd">Printer ppd file handle</param>
/// <param name="option_name">Name of the option group to load</param>
/// <param name="list">List of loaded options</param>
/// <param name="defoption">The default option from the loaded options list</param>
private static void LoadOptionList(IntPtr ppd, string option_name, NameValueCollection list, out string defoption)
{
IntPtr ptr = IntPtr.Zero;
PPD_OPTION ppd_option;
PPD_CHOICE choice;
int choice_size = Marshal.SizeOf(typeof(PPD_CHOICE));
defoption = null;
ptr = LibcupsNative.ppdFindOption(ppd, option_name);
if (ptr != IntPtr.Zero)
{
ppd_option = (PPD_OPTION)Marshal.PtrToStructure(ptr, typeof(PPD_OPTION));
#if PrintDebug
Console.WriteLine (" OPTION key:{0} def:{1} text: {2}", ppd_option.keyword, ppd_option.defchoice, ppd_option.text);
#endif
defoption = ppd_option.defchoice;
ptr = ppd_option.choices;
for (int c = 0; c < ppd_option.num_choices; c++)
{
choice = (PPD_CHOICE)Marshal.PtrToStructure(ptr, typeof(PPD_CHOICE));
list.Add(choice.choice, choice.text);
#if PrintDebug
Console.WriteLine (" choice:{0} - text: {1}", choice.choice, choice.text);
#endif
ptr = (IntPtr)((long)ptr + choice_size);
}
}
}
/// <summary>
/// Loads a printer's available resolutions
/// </summary>
/// <param name="printer">Printer name</param>
/// <param name="settings">PrinterSettings object to fill</param>
internal static void LoadPrinterResolutions(string printer, PrinterSettings settings)
{
IntPtr ppd_handle = OpenPrinter(printer);
if (ppd_handle == IntPtr.Zero)
return;
LoadPrinterResolutionsAndDefault(printer, settings, ppd_handle);
ClosePrinter(ref ppd_handle);
}
/// <summary>
/// Create a PrinterResolution from a string Resolution that is set in the PPD option.
/// An example of Resolution is "600x600dpi" or "600dpi". Returns null if malformed or "Unknown".
/// </summary>
private static PrinterResolution ParseResolution(string resolution)
{
if (string.IsNullOrEmpty(resolution))
return null;
int dpiIndex = resolution.IndexOf("dpi");
if (dpiIndex == -1)
{
// Resolution is "Unknown" or unparsable
return null;
}
resolution = resolution.Substring(0, dpiIndex);
int x_resolution, y_resolution;
try
{
if (resolution.Contains("x")) // string.Contains(char) is .NetCore2.1+ specific
{
string[] resolutions = resolution.Split(new[] { 'x' });
x_resolution = Convert.ToInt32(resolutions[0]);
y_resolution = Convert.ToInt32(resolutions[1]);
}
else
{
x_resolution = Convert.ToInt32(resolution);
y_resolution = x_resolution;
}
}
catch (Exception)
{
return null;
}
return new PrinterResolution(PrinterResolutionKind.Custom, x_resolution, y_resolution);
}
/// <summary>
/// Loads a printer's paper sizes. Returns the default PaperSize, and fills a list of paper_names for use in dialogues
/// </summary>
/// <param name="ppd_handle">PPD printer file handle</param>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_size">Default paper size, from the global options of the printer</param>
/// <param name="paper_names">List of available paper sizes that gets filled</param>
private static PaperSize LoadPrinterPaperSizes(IntPtr ppd_handle, PrinterSettings settings,
string def_size, NameValueCollection paper_names)
{
IntPtr ptr;
string real_name;
PPD_FILE ppd;
PPD_SIZE size;
PaperSize ps;
PaperSize defsize = new PaperSize(GetPaperKind(827, 1169), "A4", 827, 1169);
ppd = (PPD_FILE)Marshal.PtrToStructure(ppd_handle, typeof(PPD_FILE));
ptr = ppd.sizes;
float w, h;
for (int i = 0; i < ppd.num_sizes; i++)
{
size = (PPD_SIZE)Marshal.PtrToStructure(ptr, typeof(PPD_SIZE));
real_name = paper_names[size.name];
w = size.width * 100 / 72;
h = size.length * 100 / 72;
PaperKind kind = GetPaperKind((int)w, (int)h);
ps = new PaperSize(kind, real_name, (int)w, (int)h);
ps.RawKind = (int)kind;
if (def_size == ps.Kind.ToString())
defsize = ps;
settings.paper_sizes.Add(ps);
ptr = (IntPtr)((long)ptr + Marshal.SizeOf(size));
}
return defsize;
}
/// <summary>
/// Loads a printer's paper sources (trays). Returns the default PaperSource, and fills a list of paper_sources for use in dialogues
/// </summary>
/// <param name="settings">PrinterSettings object to fill</param>
/// <param name="def_source">Default paper source, from the global options of the printer</param>
/// <param name="paper_sources">List of available paper sizes that gets filled</param>
private static PaperSource LoadPrinterPaperSources(PrinterSettings settings, string def_source,
NameValueCollection paper_sources)
{
PaperSourceKind kind;
PaperSource defsource = null;
foreach (string source in paper_sources)
{
switch (source)
{
case "Auto":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Standard":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Tray":
kind = PaperSourceKind.AutomaticFeed;
break;
case "Envelope":
kind = PaperSourceKind.Envelope;
break;
case "Manual":
kind = PaperSourceKind.Manual;
break;
default:
kind = PaperSourceKind.Custom;
break;
}
settings.paper_sources.Add(new PaperSource(kind, paper_sources[source]));
if (def_source == source)
defsource = settings.paper_sources[settings.paper_sources.Count - 1];
}
if (defsource == null && settings.paper_sources.Count > 0)
return settings.paper_sources[0];
return defsource;
}
/// <summary>
/// Sets the available resolutions and default resolution from a
/// printer's PPD file into settings.
/// </summary>
private static void LoadPrinterResolutionsAndDefault(string printer,
PrinterSettings settings, IntPtr ppd_handle)
{
if (settings.printer_resolutions == null)
settings.printer_resolutions = new PrinterSettings.PrinterResolutionCollection(Array.Empty<PrinterResolution>());
else
settings.printer_resolutions.Clear();
var printer_resolutions = new NameValueCollection();
string defresolution;
LoadOptionList(ppd_handle, "Resolution", printer_resolutions, out defresolution);
foreach (var resolution in printer_resolutions.Keys)
{
var new_resolution = ParseResolution(resolution.ToString());
settings.PrinterResolutions.Add(new_resolution);
}
var default_resolution = ParseResolution(defresolution);
if (default_resolution == null)
default_resolution = ParseResolution("300dpi");
if (printer_resolutions.Count == 0)
settings.PrinterResolutions.Add(default_resolution);
settings.DefaultPageSettings.PrinterResolution = default_resolution;
}
/// <summary>
/// </summary>
private static void LoadPrinters()
{
installed_printers.Clear();
if (cups_installed == false)
return;
IntPtr dests = IntPtr.Zero, ptr_printers;
CUPS_DESTS printer;
int n_printers = 0;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
string name, first, type, status, comment;
first = type = status = comment = string.Empty;
int state = 0;
try
{
n_printers = OpenDests(ref dests);
ptr_printers = dests;
for (int i = 0; i < n_printers; i++)
{
printer = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
name = Marshal.PtrToStringAnsi(printer.name);
if (printer.is_default == 1)
default_printer = name;
if (first.Equals(string.Empty))
first = name;
NameValueCollection options = LoadPrinterOptions(printer.options, printer.num_options);
if (options["printer-state"] != null)
state = int.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
installed_printers.Add(name, new SysPrn.Printer(string.Empty, type, status, comment));
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
}
finally
{
CloseDests(ref dests, n_printers);
}
if (default_printer.Equals(string.Empty))
default_printer = first;
}
/// <summary>
/// Gets a printer's settings for use in the print dialogue
/// </summary>
/// <param name="printer"></param>
/// <param name="port"></param>
/// <param name="type"></param>
/// <param name="status"></param>
/// <param name="comment"></param>
internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
int count = 0, state = -1;
bool found = false;
CUPS_DESTS cups_dests;
IntPtr dests = IntPtr.Zero, ptr_printers, ptr_printer;
int cups_dests_size = Marshal.SizeOf(typeof(CUPS_DESTS));
if (cups_installed == false)
return;
try
{
count = OpenDests(ref dests);
if (count == 0)
return;
ptr_printers = dests;
for (int i = 0; i < count; i++)
{
ptr_printer = (IntPtr)Marshal.ReadIntPtr(ptr_printers);
if (Marshal.PtrToStringAnsi(ptr_printer).Equals(printer))
{
found = true;
break;
}
ptr_printers = (IntPtr)((long)ptr_printers + cups_dests_size);
}
if (!found)
return;
cups_dests = (CUPS_DESTS)Marshal.PtrToStructure(ptr_printers, typeof(CUPS_DESTS));
NameValueCollection options = LoadPrinterOptions(cups_dests.options, cups_dests.num_options);
if (options["printer-state"] != null)
state = int.Parse(options["printer-state"]);
if (options["printer-comment"] != null)
comment = options["printer-state"];
switch (state)
{
case 4:
status = "Printing";
break;
case 5:
status = "Stopped";
break;
default:
status = "Ready";
break;
}
}
finally
{
CloseDests(ref dests, count);
}
}
/// <summary>
/// Returns the appropriate PaperKind for the width and height
/// </summary>
/// <param name="width"></param>
/// <param name="height"></param>
private static PaperKind GetPaperKind(int width, int height)
{
if (width == 827 && height == 1169)
return PaperKind.A4;
if (width == 583 && height == 827)
return PaperKind.A5;
if (width == 717 && height == 1012)
return PaperKind.B5;
if (width == 693 && height == 984)
return PaperKind.B5Envelope;
if (width == 638 && height == 902)
return PaperKind.C5Envelope;
if (width == 449 && height == 638)
return PaperKind.C6Envelope;
if (width == 1700 && height == 2200)
return PaperKind.CSheet;
if (width == 433 && height == 866)
return PaperKind.DLEnvelope;
if (width == 2200 && height == 3400)
return PaperKind.DSheet;
if (width == 3400 && height == 4400)
return PaperKind.ESheet;
if (width == 725 && height == 1050)
return PaperKind.Executive;
if (width == 850 && height == 1300)
return PaperKind.Folio;
if (width == 850 && height == 1200)
return PaperKind.GermanStandardFanfold;
if (width == 1700 && height == 1100)
return PaperKind.Ledger;
if (width == 850 && height == 1400)
return PaperKind.Legal;
if (width == 927 && height == 1500)
return PaperKind.LegalExtra;
if (width == 850 && height == 1100)
return PaperKind.Letter;
if (width == 927 && height == 1200)
return PaperKind.LetterExtra;
if (width == 850 && height == 1269)
return PaperKind.LetterPlus;
if (width == 387 && height == 750)
return PaperKind.MonarchEnvelope;
if (width == 387 && height == 887)
return PaperKind.Number9Envelope;
if (width == 413 && height == 950)
return PaperKind.Number10Envelope;
if (width == 450 && height == 1037)
return PaperKind.Number11Envelope;
if (width == 475 && height == 1100)
return PaperKind.Number12Envelope;
if (width == 500 && height == 1150)
return PaperKind.Number14Envelope;
if (width == 363 && height == 650)
return PaperKind.PersonalEnvelope;
if (width == 1000 && height == 1100)
return PaperKind.Standard10x11;
if (width == 1000 && height == 1400)
return PaperKind.Standard10x14;
if (width == 1100 && height == 1700)
return PaperKind.Standard11x17;
if (width == 1200 && height == 1100)
return PaperKind.Standard12x11;
if (width == 1500 && height == 1100)
return PaperKind.Standard15x11;
if (width == 900 && height == 1100)
return PaperKind.Standard9x11;
if (width == 550 && height == 850)
return PaperKind.Statement;
if (width == 1100 && height == 1700)
return PaperKind.Tabloid;
if (width == 1487 && height == 1100)
return PaperKind.USStandardFanfold;
return PaperKind.Custom;
}
#endregion
#region Print job methods
static string tmpfile;
/// <summary>
/// Gets a pointer to an options list parsed from the printer's current settings, to use when setting up the printing job
/// </summary>
/// <param name="printer_settings"></param>
/// <param name="page_settings"></param>
/// <param name="options"></param>
internal static int GetCupsOptions(PrinterSettings printer_settings, PageSettings page_settings, out IntPtr options)
{
options = IntPtr.Zero;
PaperSize size = page_settings.PaperSize;
int width = size.Width * 72 / 100;
int height = size.Height * 72 / 100;
var sb = new StringBuilder();
sb.Append("copies=").Append(printer_settings.Copies).Append(' ')
.Append("Collate=").Append(printer_settings.Collate).Append(' ')
.Append("ColorModel=").Append(page_settings.Color ? "Color" : "Black").Append(' ')
.Append("PageSize=Custom.").Append(width).Append('x').Append(height).Append(' ')
.Append("landscape=").Append(page_settings.Landscape);
if (printer_settings.CanDuplex)
{
if (printer_settings.Duplex == Duplex.Simplex)
{
sb.Append(" Duplex=None");
}
else
{
sb.Append(" Duplex=DuplexNoTumble");
}
}
return LibcupsNative.cupsParseOptions(sb.ToString(), 0, ref options);
}
internal static bool StartDoc(GraphicsPrinter gr, string doc_name, string output_file)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
doc.title = doc_name;
return true;
}
internal static bool EndDoc(GraphicsPrinter gr)
{
DOCINFO doc = (DOCINFO)doc_info[gr.Hdc];
gr.Graphics.Dispose(); // Dispose object to force surface finish
IntPtr options;
int options_count = GetCupsOptions(doc.settings, doc.default_page_settings, out options);
LibcupsNative.cupsPrintFile(doc.settings.PrinterName, doc.filename, doc.title, options_count, options);
LibcupsNative.cupsFreeOptions(options_count, options);
doc_info.Remove(gr.Hdc);
if (tmpfile != null)
{
try
{ File.Delete(tmpfile); }
catch { }
}
return true;
}
internal static bool StartPage(GraphicsPrinter gr)
{
return true;
}
internal static bool EndPage(GraphicsPrinter gr)
{
Gdip.GdipGetPostScriptSavePage(gr.Hdc);
return true;
}
// Unfortunately, PrinterSettings and PageSettings couldn't be referencing each other,
// thus we need to pass them separately
internal static IntPtr CreateGraphicsContext(PrinterSettings settings, PageSettings default_page_settings)
{
IntPtr graphics = IntPtr.Zero;
string name;
if (!settings.PrintToFile)
{
StringBuilder sb = new StringBuilder(1024);
int length = sb.Capacity;
LibcupsNative.cupsTempFd(sb, length);
name = sb.ToString();
tmpfile = name;
}
else
name = settings.PrintFileName;
PaperSize psize = default_page_settings.PaperSize;
int width, height;
if (default_page_settings.Landscape)
{ // Swap in case of landscape
width = psize.Height;
height = psize.Width;
}
else
{
width = psize.Width;
height = psize.Height;
}
Gdip.GdipGetPostScriptGraphicsContext(name,
width * 72 / 100,
height * 72 / 100,
default_page_settings.PrinterResolution.X,
default_page_settings.PrinterResolution.Y, ref graphics);
DOCINFO doc = new DOCINFO();
doc.filename = name;
doc.settings = settings;
doc.default_page_settings = default_page_settings;
doc_info.Add(graphics, doc);
return graphics;
}
#endregion
#pragma warning disable 649
#region Struct
public struct DOCINFO
{
public PrinterSettings settings;
public PageSettings default_page_settings;
public string title;
public string filename;
}
public struct PPD_SIZE
{
public int marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public float width;
public float length;
public float left;
public float bottom;
public float right;
public float top;
}
public struct PPD_GROUP
{
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 40)]
public string text;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 42)]
public string name;
public int num_options;
public IntPtr options;
public int num_subgroups;
public IntPtr subgrups;
}
public struct PPD_OPTION
{
public byte conflicted;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string keyword;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string defchoice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public int ui;
public int section;
public float order;
public int num_choices;
public IntPtr choices;
}
public struct PPD_CHOICE
{
public byte marked;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 41)]
public string choice;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 81)]
public string text;
public IntPtr code;
public IntPtr option;
}
public struct PPD_FILE
{
public int language_level;
public int color_device;
public int variable_sizes;
public int accurate_screens;
public int contone_only;
public int landscape;
public int model_number;
public int manual_copies;
public int throughput;
public int colorspace;
public IntPtr patches;
public int num_emulations;
public IntPtr emulations;
public IntPtr jcl_begin;
public IntPtr jcl_ps;
public IntPtr jcl_end;
public IntPtr lang_encoding;
public IntPtr lang_version;
public IntPtr modelname;
public IntPtr ttrasterizer;
public IntPtr manufacturer;
public IntPtr product;
public IntPtr nickname;
public IntPtr shortnickname;
public int num_groups;
public IntPtr groups;
public int num_sizes;
public IntPtr sizes;
/* There is more data after this that we are not using*/
}
public struct CUPS_OPTIONS
{
public IntPtr name;
public IntPtr val;
}
public struct CUPS_DESTS
{
public IntPtr name;
public IntPtr instance;
public int is_default;
public int num_options;
public IntPtr options;
}
#endregion
#pragma warning restore 649
internal static void LoadDefaultResolutions(PrinterSettings.PrinterResolutionCollection col)
{
col.Add(new PrinterResolution(PrinterResolutionKind.High, (int)PrinterResolutionKind.High, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Medium, (int)PrinterResolutionKind.Medium, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Low, (int)PrinterResolutionKind.Low, -1));
col.Add(new PrinterResolution(PrinterResolutionKind.Draft, (int)PrinterResolutionKind.Draft, -1));
}
}
internal class SysPrn
{
internal static void GetPrintDialogInfo(string printer, ref string port, ref string type, ref string status, ref string comment)
{
PrintingServices.GetPrintDialogInfo(printer, ref port, ref type, ref status, ref comment);
}
internal class Printer
{
public readonly string Comment;
public readonly string Port;
public readonly string Type;
public readonly string Status;
public PrinterSettings Settings;
public Printer(string port, string type, string status, string comment)
{
Port = port;
Type = type;
Status = status;
Comment = comment;
}
}
}
internal class GraphicsPrinter
{
private Graphics graphics;
private IntPtr hDC;
internal GraphicsPrinter(Graphics gr, IntPtr dc)
{
graphics = gr;
hDC = dc;
}
internal Graphics Graphics
{
get { return graphics; }
set { graphics = value; }
}
internal IntPtr Hdc { get { return hDC; } }
}
}
| |
using System;
using System.IO;
using System.Collections;
namespace GrillScript
{
public class ExpressionTyping
{
public static ArrayList FunctionTypes = new ArrayList();
public static ArrayList Contracts = new ArrayList();
public static SortedList ClassTypes = new SortedList();
public static string DocumentType = "doc";
public static string GetTypOfDom(string x)
{
if(x.Equals("int")) return "int";
if(x.Equals("long")) return "int";
if(x.Equals("bool")) return "int";
if(x.Equals("char")) return "char";
if(x.Equals("uint32")) return "int";
if(x.Equals("uint16")) return "int";
if(x.Equals("int*")) return "int*";
if(x.Equals("long*")) return "int*";
if(x.Equals("bool*")) return "int*";
if(x.Equals("char*")) return "char*";
if(x.Equals("uint32*")) return "int*";
if(x.Equals("uint16*")) return "int*";
if(x.Equals("string")) return "char*";
if(x.Equals("float")) return "real";
if(x.Equals("double")) return "real";
if(x.Equals("float")) return "real*";
if(x.Equals("double")) return "real*";
if(x.Equals("Vector4")) return "real*";
if(x.Equals("Vector3")) return "real*";
if(x.Equals("Vector2")) return "real*";
if(x.Equals("Matrix4x4")) return "real*";
if(x.Equals("Matrix3x4")) return "real*";
if(x.Equals("Quaternion")) return "real*";
if(x.Equals("fun")) return "fun";
return x;
}
public static void ResetClassTypes()
{
ClassTypes = new SortedList();
}
public static void ParseFireDOM(string x)
{
StreamReader sr = new StreamReader(x);
string line = sr.ReadLine();
while(line != null)
{
string [] xz = line.Split(new char[] {'='});
if(xz[0].IndexOf("Document")>=0)
{
DocumentType = xz[0].Substring(0,xz[0].IndexOf(":"));
}
ClassTypes.Add(xz[0],GetTypOfDom(xz[1]));
line = sr.ReadLine();
}
sr.Close();
}
public static bool IsConstant(LispNode N)
{
if(N.node.Equals("null")) return true;
if(N.node.Equals("false")) return true;
if(N.node.Equals("nil")) return true;
if(N.node.Equals("true")) return true;
if(N.node.Equals("document")) return true;
if(N.node.Equals("random")) return true;
if(N.node.Equals("pi")) return true;
if(N.node.Equals("euler")) return true;
if(N.node.Equals("real")) return true;
if(N.node.Equals("integer")) return true;
if(N.node.Equals("string")) return true;//{ throw new Exception("string not supported yet"); }
return false;
}
public static int IsMathFunctionTrueImpliesArity(string y)
{
string x = y.ToLower();
if(x.Equals("abs")) return 1;
if(x.Equals("acos")) return 1;
if(x.Equals("asin")) return 1;
if(x.Equals("atan")) return 1;
if(x.Equals("atan2")) return 2;
if(x.Equals("ceil")||x.Equals("ceiling")) return 1;
if(x.Equals("floor")) return 1;
if(x.Equals("cos")) return 1;
if(x.Equals("sin")) return 1;
if(x.Equals("tan")) return 1;
if(x.Equals("cosh")) return 1;
if(x.Equals("sinh")) return 1;
if(x.Equals("tanh")) return 1;
if(x.Equals("deg")) return 1;
if(x.Equals("rad")) return 1;
if(x.Equals("exp")) return 1;
if(x.Equals("log")) return 1;
if(x.Equals("ln")) return 1;
if(x.Equals("log2")) return 1;
if(x.Equals("log10")) return 1;
if(x.Equals("pow")) return 2;
if(x.Equals("min")) return 10000;
if(x.Equals("max")) return 10000;
if(x.Equals("poly")) return 10000;
if(x.Equals("sqrt")) return 1;
if(x.Equals("concat")) return 10000;
if(x.Equals("num2str")) return 1;
if(x.Equals("left")) return 2;
if(x.Equals("subset")) return 3;
if(x.Equals("tail")) return 2;
return -1;
}
public static bool IsSpecialRealType(LispNode N)
{
if(N.node.Equals("vec2")) return true;
if(N.node.Equals("vec3")) return true;
if(N.node.Equals("vec4")) return true;
if(N.node.Equals("matrix2x2")) return true;
if(N.node.Equals("matrix2x3")) return true;
if(N.node.Equals("matrix3x3")) return true;
if(N.node.Equals("matrix3x4")) return true;
if(N.node.Equals("matrix4x4")) return true;
if(N.node.Equals("quaterion")) return true;
return false;
}
public static bool IsSpecialRealType2(string x)
{
if(x.Equals("vec2")) return true;
if(x.Equals("vec3")) return true;
if(x.Equals("vec4")) return true;
if(x.Equals("matrix2x2")) return true;
if(x.Equals("matrix2x3")) return true;
if(x.Equals("matrix3x3")) return true;
if(x.Equals("matrix3x4")) return true;
if(x.Equals("matrix4x4")) return true;
if(x.Equals("quaterion")) return true;
return false;
}
public static int GetSpecialRealTypeWidth(LispNode N)
{
if(N.node.Equals("vec2")) return 2;
if(N.node.Equals("vec3")) return 3;
if(N.node.Equals("vec4")) return 4;
if(N.node.Equals("matrix2x2")) return 4;
if(N.node.Equals("matrix2x3")) return 6;
if(N.node.Equals("matrix3x3")) return 9;
if(N.node.Equals("matrix3x4")) return 12;
if(N.node.Equals("matrix4x4")) return 16;
if(N.node.Equals("quaterion")) return 4;
return 1;
}
public static int GetSpecialRealTypePitch(LispNode N)
{
if(N.node.Equals("vec2")) return 1;
if(N.node.Equals("vec3")) return 1;
if(N.node.Equals("vec4")) return 1;
if(N.node.Equals("matrix2x2")) return 2;
if(N.node.Equals("matrix2x3")) return 3;
if(N.node.Equals("matrix3x3")) return 3;
if(N.node.Equals("matrix3x4")) return 4;
if(N.node.Equals("matrix4x4")) return 4;
if(N.node.Equals("quaterion")) return 1;
return 1;
}
public static bool IsAssignment(LispNode N)
{
if(N.node.Equals("=")) return true;
if(N.node.Equals("+=")) return true;
if(N.node.Equals("-=")) return true;
if(N.node.Equals("*=")) return true;
if(N.node.Equals("/=")) return true;
if(N.node.Equals("%=")) return true;
if(N.node.Equals("|=")) return true;
if(N.node.Equals("&=")) return true;
if(N.node.Equals("^=")) return true;
if(N.node.Equals("++")) return true;
if(N.node.Equals("--")) return true;
return false;
}
public static bool IsArithmeticOperator(LispNode N)
{
if(N.node.Equals("+")) return true;
if(N.node.Equals("-")) return true;
if(N.node.Equals("*")) return true;
if(N.node.Equals("/")) return true;
if(N.node.Equals("%")) return true;
return false;
}
public static bool IsComparionOperator(LispNode N)
{
if(N.node.Equals("==")) return true;
if(N.node.Equals("!=")) return true;
if(N.node.Equals("<=")) return true;
if(N.node.Equals("<")) return true;
if(N.node.Equals(">")) return true;
if(N.node.Equals(">=")) return true;
return false;
}
public static bool IsBooleanOperator(LispNode N)
{
if(N.node.Equals("||")) return true;
if(N.node.Equals("&&")) return true;
if(N.node.Equals("^^")) return true;
if(N.node.Equals("!")) return true;
return false;
}
public static bool IsIntegralType(string x)
{
if(x.Equals("int")) return true;
return false;
}
public static bool IsCharacterType(string x)
{
if(x.Equals("char")) return true;
return false;
}
public static bool IsRealType(string x)
{
if(x.Equals("real")) return true;
if(x.Equals("float")) return true;
if(x.Equals("double")) return true;
return false;
}
public static bool IsFunctional(string x)
{
if(x.Equals("fun")) return true;
foreach(string y in FunctionTypes) if(x.Equals(y)) return true;
return false;
}
public static bool IsContract(string x)
{
foreach(string y in Contracts) if(x.Equals(y)) return true;
return false;
}
public static string TypeConstant(LispNode N)
{
if(N.node.Equals("real")) return "real";
if(N.node.Equals("integer")) return "int";
if(N.node.Equals("int")) return "int";
if(N.node.Equals("null")) return "ptr";
if(N.node.Equals("nil")) return "fun";
if(N.node.Equals("true")) return "int";
if(N.node.Equals("false")) return "int";
if(N.node.Equals("dom")) return "ptr";
if(N.node.Equals("document")) return DocumentType;
throw new Exception("not supported");
}
public static string TypeArithmeticOperation(LispNode N, Environment E)
{
string typ = "int";
for(uint i = 0; i < N.children.Length; i++)
{
string xyz = TypeExpression(N.children[i],E);
if(xyz.Equals("int") || xyz.Equals("real"))
{
// good
if(xyz.Equals("real"))
typ = "real";
}
else
{
throw new Exception("not supported");
}
}
return typ;
}
public static string TypeExpression(LispNode N, Environment E)
{
if(N.node.Equals("len"))
{
TypeExpression(N.children[0],E);
return "int";
}
if(N.node.Equals("random"))
{
return "real";
}
if(N.node.Equals("request"))
{
return "ptr";
}
if(N.node.Equals("nil"))
{
return "fun";
}
if(IsConstant(N)) return TypeConstant(N);
if(IsArithmeticOperator(N)) return TypeArithmeticOperation(N,E);
if(IsComparionOperator(N)||IsBooleanOperator(N))
{
TypeArithmeticOperation(N,E);
return "int";
}
if(N.node.Equals("as"))
{
TypeExpression(N.children[0],E);
return N.children[1].node;
}
if(N.node.Equals("var"))
{
string vTyp = (string)E.Get(N.children[0].node);
if(vTyp==null) return "?";
if(vTyp.Equals("")) return "?";
return vTyp;
}
if(N.node.Equals("."))
{
LispNode PtrObj = N.children[0];
string Field = N.children[1].node;
string TypClass = ExpressionTyping.TypeExpression(PtrObj,E);
string TypCF = TypClass+":"+Field;
if(ClassTypes.ContainsKey(TypCF))
{
return (string)ClassTypes[TypCF];
}
return "?";
}
if(N.node.Equals("["))
{
string exr = ExpressionTyping.TypeExpression(N.children[0],E);
if(exr[exr.Length-1]=='*')
return exr.Substring(0,exr.Length-1);
}
return "?";
}
}
}
| |
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Diagnostics;
using System.Windows.Forms;
namespace FeedBuilder
{
partial class frmMain
{
/// <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(frmMain));
this.lstFiles = new System.Windows.Forms.ListView();
this.colFilename = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colVersion = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colDate = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.colHash = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.imgFiles = new System.Windows.Forms.ImageList(this.components);
this.fbdOutputFolder = new System.Windows.Forms.FolderBrowserDialog();
this.sfdFeedXML = new System.Windows.Forms.SaveFileDialog();
this.tsMain = new System.Windows.Forms.ToolStrip();
this.btnNew = new System.Windows.Forms.ToolStripButton();
this.btnOpen = new System.Windows.Forms.ToolStripButton();
this.btnSave = new System.Windows.Forms.ToolStripButton();
this.btnSaveAs = new System.Windows.Forms.ToolStripButton();
this.tsSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnRefresh = new System.Windows.Forms.ToolStripButton();
this.btnOpenOutputs = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.btnBuild = new System.Windows.Forms.ToolStripButton();
this.ToolStripContainer1 = new System.Windows.Forms.ToolStripContainer();
this.panFiles = new System.Windows.Forms.Panel();
this.grpSettings = new System.Windows.Forms.GroupBox();
this.chkCleanUp = new System.Windows.Forms.CheckBox();
this.chkCopyFiles = new System.Windows.Forms.CheckBox();
this.lblIgnore = new System.Windows.Forms.Label();
this.lblMisc = new System.Windows.Forms.Label();
this.lblCompare = new System.Windows.Forms.Label();
this.chkHash = new System.Windows.Forms.CheckBox();
this.chkDate = new System.Windows.Forms.CheckBox();
this.chkSize = new System.Windows.Forms.CheckBox();
this.chkVersion = new System.Windows.Forms.CheckBox();
this.txtBaseURL = new FeedBuilder.HelpfulTextBox(this.components);
this.lblBaseURL = new System.Windows.Forms.Label();
this.chkIgnoreVsHost = new System.Windows.Forms.CheckBox();
this.chkIgnoreSymbols = new System.Windows.Forms.CheckBox();
this.cmdFeedXML = new System.Windows.Forms.Button();
this.txtFeedXML = new FeedBuilder.HelpfulTextBox(this.components);
this.lblFeedXML = new System.Windows.Forms.Label();
this.cmdOutputFolder = new System.Windows.Forms.Button();
this.txtOutputFolder = new FeedBuilder.HelpfulTextBox(this.components);
this.lblOutputFolder = new System.Windows.Forms.Label();
this.tsMain.SuspendLayout();
this.ToolStripContainer1.ContentPanel.SuspendLayout();
this.ToolStripContainer1.TopToolStripPanel.SuspendLayout();
this.ToolStripContainer1.SuspendLayout();
this.panFiles.SuspendLayout();
this.grpSettings.SuspendLayout();
this.SuspendLayout();
//
// lstFiles
//
this.lstFiles.CheckBoxes = true;
this.lstFiles.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.colFilename,
this.colVersion,
this.colSize,
this.colDate,
this.colHash});
this.lstFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.lstFiles.Location = new System.Drawing.Point(0, 12);
this.lstFiles.Margin = new System.Windows.Forms.Padding(0);
this.lstFiles.Name = "lstFiles";
this.lstFiles.Size = new System.Drawing.Size(810, 230);
this.lstFiles.SmallImageList = this.imgFiles;
this.lstFiles.TabIndex = 0;
this.lstFiles.UseCompatibleStateImageBehavior = false;
this.lstFiles.View = System.Windows.Forms.View.Details;
//
// colFilename
//
this.colFilename.Text = "Filename";
this.colFilename.Width = 200;
//
// colVersion
//
this.colVersion.Text = "Version";
this.colVersion.Width = 80;
//
// colSize
//
this.colSize.Text = "Size";
this.colSize.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colSize.Width = 80;
//
// colDate
//
this.colDate.Text = "Date";
this.colDate.TextAlign = System.Windows.Forms.HorizontalAlignment.Right;
this.colDate.Width = 120;
//
// colHash
//
this.colHash.Text = "Hash";
this.colHash.Width = 300;
//
// imgFiles
//
this.imgFiles.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imgFiles.ImageStream")));
this.imgFiles.TransparentColor = System.Drawing.Color.Transparent;
this.imgFiles.Images.SetKeyName(0, "file_extension_other.png");
this.imgFiles.Images.SetKeyName(1, "file_extension_bmp.png");
this.imgFiles.Images.SetKeyName(2, "file_extension_dll.png");
this.imgFiles.Images.SetKeyName(3, "file_extension_doc.png");
this.imgFiles.Images.SetKeyName(4, "file_extension_exe.png");
this.imgFiles.Images.SetKeyName(5, "file_extension_htm.png");
this.imgFiles.Images.SetKeyName(6, "file_extension_jpg.png");
this.imgFiles.Images.SetKeyName(7, "file_extension_pdf.png");
this.imgFiles.Images.SetKeyName(8, "file_extension_png.png");
this.imgFiles.Images.SetKeyName(9, "file_extension_txt.png");
this.imgFiles.Images.SetKeyName(10, "file_extension_wav.png");
this.imgFiles.Images.SetKeyName(11, "file_extension_wmv.png");
this.imgFiles.Images.SetKeyName(12, "file_extension_zip.png");
//
// fbdOutputFolder
//
this.fbdOutputFolder.Description = "Select your projects output folder:";
//
// sfdFeedXML
//
this.sfdFeedXML.DefaultExt = "xml";
this.sfdFeedXML.Filter = "XML Files (*.xml)|*.xml|All Files (*.*)|*.*";
this.sfdFeedXML.Title = "Select the location to save your NauXML file:";
//
// tsMain
//
this.tsMain.Dock = System.Windows.Forms.DockStyle.None;
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.btnNew,
this.btnOpen,
this.btnSave,
this.btnSaveAs,
this.tsSeparator1,
this.btnRefresh,
this.btnOpenOutputs,
this.toolStripSeparator1,
this.btnBuild});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.Size = new System.Drawing.Size(834, 25);
this.tsMain.Stretch = true;
this.tsMain.TabIndex = 2;
this.tsMain.Text = "Commands";
//
// btnNew
//
this.btnNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnNew.Image = ((System.Drawing.Image)(resources.GetObject("btnNew.Image")));
this.btnNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnNew.Name = "btnNew";
this.btnNew.Size = new System.Drawing.Size(23, 22);
this.btnNew.Text = "&New";
this.btnNew.Click += new System.EventHandler(this.btnNew_Click);
//
// btnOpen
//
this.btnOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnOpen.Image = ((System.Drawing.Image)(resources.GetObject("btnOpen.Image")));
this.btnOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(23, 22);
this.btnOpen.Text = "&Open";
this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click);
//
// btnSave
//
this.btnSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.btnSave.Image = ((System.Drawing.Image)(resources.GetObject("btnSave.Image")));
this.btnSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(23, 22);
this.btnSave.Text = "&Save";
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// btnSaveAs
//
this.btnSaveAs.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text;
this.btnSaveAs.Image = ((System.Drawing.Image)(resources.GetObject("btnSaveAs.Image")));
this.btnSaveAs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnSaveAs.Name = "btnSaveAs";
this.btnSaveAs.Size = new System.Drawing.Size(60, 22);
this.btnSaveAs.Text = "Save As...";
this.btnSaveAs.Click += new System.EventHandler(this.btnSaveAs_Click);
//
// tsSeparator1
//
this.tsSeparator1.Name = "tsSeparator1";
this.tsSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnRefresh
//
this.btnRefresh.Image = ((System.Drawing.Image)(resources.GetObject("btnRefresh.Image")));
this.btnRefresh.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnRefresh.Name = "btnRefresh";
this.btnRefresh.Size = new System.Drawing.Size(92, 22);
this.btnRefresh.Text = "Refresh Files";
this.btnRefresh.Click += new System.EventHandler(this.btnRefresh_Click);
//
// btnOpenOutputs
//
this.btnOpenOutputs.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnOpenOutputs.Image = ((System.Drawing.Image)(resources.GetObject("btnOpenOutputs.Image")));
this.btnOpenOutputs.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnOpenOutputs.Name = "btnOpenOutputs";
this.btnOpenOutputs.Size = new System.Drawing.Size(133, 22);
this.btnOpenOutputs.Text = "Open Output Folder";
this.btnOpenOutputs.Click += new System.EventHandler(this.btnOpenOutputs_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// btnBuild
//
this.btnBuild.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
this.btnBuild.Image = ((System.Drawing.Image)(resources.GetObject("btnBuild.Image")));
this.btnBuild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.btnBuild.Name = "btnBuild";
this.btnBuild.Size = new System.Drawing.Size(54, 22);
this.btnBuild.Text = "Build";
this.btnBuild.Click += new System.EventHandler(this.cmdBuild_Click);
//
// ToolStripContainer1
//
//
// ToolStripContainer1.ContentPanel
//
this.ToolStripContainer1.ContentPanel.Controls.Add(this.panFiles);
this.ToolStripContainer1.ContentPanel.Controls.Add(this.grpSettings);
this.ToolStripContainer1.ContentPanel.Padding = new System.Windows.Forms.Padding(12, 8, 12, 12);
this.ToolStripContainer1.ContentPanel.Size = new System.Drawing.Size(834, 467);
this.ToolStripContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.ToolStripContainer1.Location = new System.Drawing.Point(0, 0);
this.ToolStripContainer1.Name = "ToolStripContainer1";
this.ToolStripContainer1.Size = new System.Drawing.Size(834, 492);
this.ToolStripContainer1.TabIndex = 3;
this.ToolStripContainer1.Text = "ToolStripContainer1";
//
// ToolStripContainer1.TopToolStripPanel
//
this.ToolStripContainer1.TopToolStripPanel.Controls.Add(this.tsMain);
//
// panFiles
//
this.panFiles.Controls.Add(this.lstFiles);
this.panFiles.Dock = System.Windows.Forms.DockStyle.Fill;
this.panFiles.Location = new System.Drawing.Point(12, 213);
this.panFiles.Name = "panFiles";
this.panFiles.Padding = new System.Windows.Forms.Padding(0, 12, 0, 0);
this.panFiles.Size = new System.Drawing.Size(810, 242);
this.panFiles.TabIndex = 2;
//
// grpSettings
//
this.grpSettings.Controls.Add(this.chkCleanUp);
this.grpSettings.Controls.Add(this.chkCopyFiles);
this.grpSettings.Controls.Add(this.lblIgnore);
this.grpSettings.Controls.Add(this.lblMisc);
this.grpSettings.Controls.Add(this.lblCompare);
this.grpSettings.Controls.Add(this.chkHash);
this.grpSettings.Controls.Add(this.chkDate);
this.grpSettings.Controls.Add(this.chkSize);
this.grpSettings.Controls.Add(this.chkVersion);
this.grpSettings.Controls.Add(this.txtBaseURL);
this.grpSettings.Controls.Add(this.lblBaseURL);
this.grpSettings.Controls.Add(this.chkIgnoreVsHost);
this.grpSettings.Controls.Add(this.chkIgnoreSymbols);
this.grpSettings.Controls.Add(this.cmdFeedXML);
this.grpSettings.Controls.Add(this.txtFeedXML);
this.grpSettings.Controls.Add(this.lblFeedXML);
this.grpSettings.Controls.Add(this.cmdOutputFolder);
this.grpSettings.Controls.Add(this.txtOutputFolder);
this.grpSettings.Controls.Add(this.lblOutputFolder);
this.grpSettings.Dock = System.Windows.Forms.DockStyle.Top;
this.grpSettings.Location = new System.Drawing.Point(12, 8);
this.grpSettings.Name = "grpSettings";
this.grpSettings.Padding = new System.Windows.Forms.Padding(12, 8, 12, 8);
this.grpSettings.Size = new System.Drawing.Size(810, 205);
this.grpSettings.TabIndex = 1;
this.grpSettings.TabStop = false;
this.grpSettings.Text = "Settings:";
//
// chkCleanUp
//
this.chkCleanUp.AutoSize = true;
this.chkCleanUp.Checked = true;
this.chkCleanUp.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCleanUp.Location = new System.Drawing.Point(293, 145);
this.chkCleanUp.Name = "chkCleanUp";
this.chkCleanUp.Size = new System.Drawing.Size(134, 17);
this.chkCleanUp.TabIndex = 17;
this.chkCleanUp.Text = "Clean Unselected Files";
this.chkCleanUp.UseVisualStyleBackColor = true;
//
// chkCopyFiles
//
this.chkCopyFiles.AutoSize = true;
this.chkCopyFiles.Checked = true;
this.chkCopyFiles.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkCopyFiles.Location = new System.Drawing.Point(146, 145);
this.chkCopyFiles.Name = "chkCopyFiles";
this.chkCopyFiles.Size = new System.Drawing.Size(141, 17);
this.chkCopyFiles.TabIndex = 16;
this.chkCopyFiles.Text = "Copy Files with NauXML";
this.chkCopyFiles.UseVisualStyleBackColor = true;
this.chkCopyFiles.CheckedChanged += new System.EventHandler(this.chkCopyFiles_CheckedChanged);
//
// lblIgnore
//
this.lblIgnore.AutoSize = true;
this.lblIgnore.Location = new System.Drawing.Point(15, 174);
this.lblIgnore.Name = "lblIgnore";
this.lblIgnore.Size = new System.Drawing.Size(40, 13);
this.lblIgnore.TabIndex = 15;
this.lblIgnore.Text = "Ignore:";
//
// lblMisc
//
this.lblMisc.AutoSize = true;
this.lblMisc.Location = new System.Drawing.Point(15, 146);
this.lblMisc.Name = "lblMisc";
this.lblMisc.Size = new System.Drawing.Size(32, 13);
this.lblMisc.TabIndex = 15;
this.lblMisc.Text = "Misc:";
//
// lblCompare
//
this.lblCompare.AutoSize = true;
this.lblCompare.Location = new System.Drawing.Point(15, 118);
this.lblCompare.Name = "lblCompare";
this.lblCompare.Size = new System.Drawing.Size(52, 13);
this.lblCompare.TabIndex = 14;
this.lblCompare.Text = "Compare:";
//
// chkHash
//
this.chkHash.AutoSize = true;
this.chkHash.Checked = true;
this.chkHash.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkHash.Location = new System.Drawing.Point(320, 117);
this.chkHash.Name = "chkHash";
this.chkHash.Size = new System.Drawing.Size(51, 17);
this.chkHash.TabIndex = 13;
this.chkHash.Text = "Hash";
this.chkHash.UseVisualStyleBackColor = true;
//
// chkDate
//
this.chkDate.AutoSize = true;
this.chkDate.Location = new System.Drawing.Point(265, 117);
this.chkDate.Name = "chkDate";
this.chkDate.Size = new System.Drawing.Size(49, 17);
this.chkDate.TabIndex = 12;
this.chkDate.Text = "Date";
this.chkDate.UseVisualStyleBackColor = true;
//
// chkSize
//
this.chkSize.AutoSize = true;
this.chkSize.Location = new System.Drawing.Point(213, 117);
this.chkSize.Name = "chkSize";
this.chkSize.Size = new System.Drawing.Size(46, 17);
this.chkSize.TabIndex = 11;
this.chkSize.Text = "Size";
this.chkSize.UseVisualStyleBackColor = true;
//
// chkVersion
//
this.chkVersion.AutoSize = true;
this.chkVersion.Checked = true;
this.chkVersion.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkVersion.Location = new System.Drawing.Point(146, 117);
this.chkVersion.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.chkVersion.Name = "chkVersion";
this.chkVersion.Size = new System.Drawing.Size(61, 17);
this.chkVersion.TabIndex = 10;
this.chkVersion.Text = "Version";
this.chkVersion.UseVisualStyleBackColor = true;
//
// txtBaseURL
//
this.txtBaseURL.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtBaseURL.HelpfulText = "Where you will upload the feed and update files for distribution to clients";
this.txtBaseURL.Location = new System.Drawing.Point(146, 86);
this.txtBaseURL.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtBaseURL.Name = "txtBaseURL";
this.txtBaseURL.Size = new System.Drawing.Size(617, 20);
this.txtBaseURL.TabIndex = 9;
//
// lblBaseURL
//
this.lblBaseURL.AutoSize = true;
this.lblBaseURL.Location = new System.Drawing.Point(15, 89);
this.lblBaseURL.Name = "lblBaseURL";
this.lblBaseURL.Size = new System.Drawing.Size(59, 13);
this.lblBaseURL.TabIndex = 8;
this.lblBaseURL.Text = "Base URL:";
//
// chkIgnoreVsHost
//
this.chkIgnoreVsHost.AutoSize = true;
this.chkIgnoreVsHost.Checked = true;
this.chkIgnoreVsHost.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreVsHost.Location = new System.Drawing.Point(293, 173);
this.chkIgnoreVsHost.Name = "chkIgnoreVsHost";
this.chkIgnoreVsHost.Size = new System.Drawing.Size(103, 17);
this.chkIgnoreVsHost.TabIndex = 7;
this.chkIgnoreVsHost.Text = "VS Hosting Files";
this.chkIgnoreVsHost.UseVisualStyleBackColor = true;
//
// chkIgnoreSymbols
//
this.chkIgnoreSymbols.AutoSize = true;
this.chkIgnoreSymbols.Checked = true;
this.chkIgnoreSymbols.CheckState = System.Windows.Forms.CheckState.Checked;
this.chkIgnoreSymbols.Location = new System.Drawing.Point(146, 173);
this.chkIgnoreSymbols.Name = "chkIgnoreSymbols";
this.chkIgnoreSymbols.Size = new System.Drawing.Size(100, 17);
this.chkIgnoreSymbols.TabIndex = 7;
this.chkIgnoreSymbols.Text = "Debug Symbols";
this.chkIgnoreSymbols.UseVisualStyleBackColor = true;
this.chkIgnoreSymbols.CheckedChanged += new System.EventHandler(this.chkIgnoreSymbols_CheckedChanged);
//
// cmdFeedXML
//
this.cmdFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdFeedXML.Location = new System.Drawing.Point(769, 53);
this.cmdFeedXML.Name = "cmdFeedXML";
this.cmdFeedXML.Size = new System.Drawing.Size(26, 23);
this.cmdFeedXML.TabIndex = 5;
this.cmdFeedXML.Text = "...";
this.cmdFeedXML.UseVisualStyleBackColor = true;
this.cmdFeedXML.Click += new System.EventHandler(this.cmdFeedXML_Click);
//
// txtFeedXML
//
this.txtFeedXML.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtFeedXML.BackColor = System.Drawing.Color.White;
this.txtFeedXML.HelpfulText = "The file your application downloads to determine if there are updates";
this.txtFeedXML.Location = new System.Drawing.Point(146, 55);
this.txtFeedXML.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtFeedXML.Name = "txtFeedXML";
this.txtFeedXML.Size = new System.Drawing.Size(617, 20);
this.txtFeedXML.TabIndex = 4;
//
// lblFeedXML
//
this.lblFeedXML.AutoSize = true;
this.lblFeedXML.Location = new System.Drawing.Point(15, 58);
this.lblFeedXML.Name = "lblFeedXML";
this.lblFeedXML.Size = new System.Drawing.Size(98, 13);
this.lblFeedXML.TabIndex = 3;
this.lblFeedXML.Text = "Feed NauXML File:";
//
// cmdOutputFolder
//
this.cmdOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOutputFolder.Location = new System.Drawing.Point(769, 22);
this.cmdOutputFolder.Name = "cmdOutputFolder";
this.cmdOutputFolder.Size = new System.Drawing.Size(26, 23);
this.cmdOutputFolder.TabIndex = 2;
this.cmdOutputFolder.Text = "...";
this.cmdOutputFolder.UseVisualStyleBackColor = true;
this.cmdOutputFolder.Click += new System.EventHandler(this.cmdOutputFolder_Click);
//
// txtOutputFolder
//
this.txtOutputFolder.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.txtOutputFolder.BackColor = System.Drawing.Color.White;
this.txtOutputFolder.HelpfulText = "The folder that contains the files you want to distribute";
this.txtOutputFolder.Location = new System.Drawing.Point(146, 24);
this.txtOutputFolder.Margin = new System.Windows.Forms.Padding(3, 3, 3, 8);
this.txtOutputFolder.Name = "txtOutputFolder";
this.txtOutputFolder.Size = new System.Drawing.Size(617, 20);
this.txtOutputFolder.TabIndex = 1;
//
// lblOutputFolder
//
this.lblOutputFolder.AutoSize = true;
this.lblOutputFolder.Location = new System.Drawing.Point(15, 27);
this.lblOutputFolder.Name = "lblOutputFolder";
this.lblOutputFolder.Size = new System.Drawing.Size(110, 13);
this.lblOutputFolder.TabIndex = 0;
this.lblOutputFolder.Text = "Project Output Folder:";
//
// frmMain
//
this.AllowDrop = true;
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(834, 492);
this.Controls.Add(this.ToolStripContainer1);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(850, 530);
this.Name = "frmMain";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Feed Builder";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.frmMain_FormClosing);
this.Load += new System.EventHandler(this.frmMain_Load);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.frmMain_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.frmMain_DragEnter);
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ToolStripContainer1.ContentPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.ResumeLayout(false);
this.ToolStripContainer1.TopToolStripPanel.PerformLayout();
this.ToolStripContainer1.ResumeLayout(false);
this.ToolStripContainer1.PerformLayout();
this.panFiles.ResumeLayout(false);
this.grpSettings.ResumeLayout(false);
this.grpSettings.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.FolderBrowserDialog fbdOutputFolder;
private System.Windows.Forms.SaveFileDialog sfdFeedXML;
private System.Windows.Forms.ImageList imgFiles;
private System.Windows.Forms.ListView lstFiles;
private System.Windows.Forms.ColumnHeader colFilename;
private System.Windows.Forms.ColumnHeader colVersion;
private System.Windows.Forms.ColumnHeader colSize;
private System.Windows.Forms.ColumnHeader colDate;
private System.Windows.Forms.ColumnHeader colHash;
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton btnNew;
private System.Windows.Forms.ToolStripButton btnOpen;
private System.Windows.Forms.ToolStripButton btnSave;
private System.Windows.Forms.ToolStripButton btnRefresh;
private System.Windows.Forms.ToolStripContainer ToolStripContainer1;
private System.Windows.Forms.GroupBox grpSettings;
private System.Windows.Forms.CheckBox chkCleanUp;
private System.Windows.Forms.CheckBox chkCopyFiles;
private System.Windows.Forms.Label lblIgnore;
private System.Windows.Forms.Label lblMisc;
private System.Windows.Forms.Label lblCompare;
private System.Windows.Forms.CheckBox chkHash;
private System.Windows.Forms.CheckBox chkDate;
private System.Windows.Forms.CheckBox chkSize;
private System.Windows.Forms.CheckBox chkVersion;
private HelpfulTextBox txtBaseURL;
private System.Windows.Forms.Label lblBaseURL;
private System.Windows.Forms.CheckBox chkIgnoreVsHost;
private System.Windows.Forms.CheckBox chkIgnoreSymbols;
private System.Windows.Forms.Button cmdFeedXML;
private HelpfulTextBox txtFeedXML;
private System.Windows.Forms.Label lblFeedXML;
private System.Windows.Forms.Button cmdOutputFolder;
private HelpfulTextBox txtOutputFolder;
private System.Windows.Forms.Label lblOutputFolder;
private System.Windows.Forms.ToolStripButton btnSaveAs;
private System.Windows.Forms.ToolStripButton btnBuild;
private System.Windows.Forms.ToolStripSeparator tsSeparator1;
private ToolStripButton btnOpenOutputs;
private Panel panFiles;
private ToolStripSeparator toolStripSeparator1;
}
}
| |
using System;
using System.Collections;
using System.IO;
using System.Text;
using NUnit.Framework;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Test;
namespace Org.BouncyCastle.Bcpg.OpenPgp.Tests
{
[TestFixture]
public class PgpDsaElGamalTest
: SimpleTest
{
private static readonly byte[] testPubKeyRing = Base64.Decode(
"mQGiBEAR8jYRBADNifuSopd20JOQ5x30ljIaY0M6927+vo09NeNxS3KqItba"
+ "nz9o5e2aqdT0W1xgdHYZmdElOHTTsugZxdXTEhghyxoo3KhVcNnTABQyrrvX"
+ "qouvmP2fEDEw0Vpyk+90BpyY9YlgeX/dEA8OfooRLCJde/iDTl7r9FT+mts8"
+ "g3azjwCgx+pOLD9LPBF5E4FhUOdXISJ0f4EEAKXSOi9nZzajpdhe8W2ZL9gc"
+ "BpzZi6AcrRZBHOEMqd69gtUxA4eD8xycUQ42yH89imEcwLz8XdJ98uHUxGJi"
+ "qp6hq4oakmw8GQfiL7yQIFgaM0dOAI9Afe3m84cEYZsoAFYpB4/s9pVMpPRH"
+ "NsVspU0qd3NHnSZ0QXs8L8DXGO1uBACjDUj+8GsfDCIP2QF3JC+nPUNa0Y5t"
+ "wKPKl+T8hX/0FBD7fnNeC6c9j5Ir/Fp/QtdaDAOoBKiyNLh1JaB1NY6US5zc"
+ "qFks2seZPjXEiE6OIDXYra494mjNKGUobA4hqT2peKWXt/uBcuL1mjKOy8Qf"
+ "JxgEd0MOcGJO+1PFFZWGzLQ3RXJpYyBILiBFY2hpZG5hICh0ZXN0IGtleSBv"
+ "bmx5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3JnPohZBBMRAgAZBQJAEfI2BAsH"
+ "AwIDFQIDAxYCAQIeAQIXgAAKCRAOtk6iUOgnkDdnAKC/CfLWikSBdbngY6OK"
+ "5UN3+o7q1ACcDRqjT3yjBU3WmRUNlxBg3tSuljmwAgAAuQENBEAR8jgQBAC2"
+ "kr57iuOaV7Ga1xcU14MNbKcA0PVembRCjcVjei/3yVfT/fuCVtGHOmYLEBqH"
+ "bn5aaJ0P/6vMbLCHKuN61NZlts+LEctfwoya43RtcubqMc7eKw4k0JnnoYgB"
+ "ocLXOtloCb7jfubOsnfORvrUkK0+Ne6anRhFBYfaBmGU75cQgwADBQP/XxR2"
+ "qGHiwn+0YiMioRDRiIAxp6UiC/JQIri2AKSqAi0zeAMdrRsBN7kyzYVVpWwN"
+ "5u13gPdQ2HnJ7d4wLWAuizUdKIQxBG8VoCxkbipnwh2RR4xCXFDhJrJFQUm+"
+ "4nKx9JvAmZTBIlI5Wsi5qxst/9p5MgP3flXsNi1tRbTmRhqIRgQYEQIABgUC"
+ "QBHyOAAKCRAOtk6iUOgnkBStAJoCZBVM61B1LG2xip294MZecMtCwQCbBbsk"
+ "JVCXP0/Szm05GB+WN+MOCT2wAgAA");
private static readonly byte[] testPrivKeyRing = Base64.Decode(
"lQHhBEAR8jYRBADNifuSopd20JOQ5x30ljIaY0M6927+vo09NeNxS3KqItba"
+ "nz9o5e2aqdT0W1xgdHYZmdElOHTTsugZxdXTEhghyxoo3KhVcNnTABQyrrvX"
+ "qouvmP2fEDEw0Vpyk+90BpyY9YlgeX/dEA8OfooRLCJde/iDTl7r9FT+mts8"
+ "g3azjwCgx+pOLD9LPBF5E4FhUOdXISJ0f4EEAKXSOi9nZzajpdhe8W2ZL9gc"
+ "BpzZi6AcrRZBHOEMqd69gtUxA4eD8xycUQ42yH89imEcwLz8XdJ98uHUxGJi"
+ "qp6hq4oakmw8GQfiL7yQIFgaM0dOAI9Afe3m84cEYZsoAFYpB4/s9pVMpPRH"
+ "NsVspU0qd3NHnSZ0QXs8L8DXGO1uBACjDUj+8GsfDCIP2QF3JC+nPUNa0Y5t"
+ "wKPKl+T8hX/0FBD7fnNeC6c9j5Ir/Fp/QtdaDAOoBKiyNLh1JaB1NY6US5zc"
+ "qFks2seZPjXEiE6OIDXYra494mjNKGUobA4hqT2peKWXt/uBcuL1mjKOy8Qf"
+ "JxgEd0MOcGJO+1PFFZWGzP4DAwLeUcsVxIC2s2Bb9ab2XD860TQ2BI2rMD/r"
+ "7/psx9WQ+Vz/aFAT3rXkEJ97nFeqEACgKmUCAEk9939EwLQ3RXJpYyBILiBF"
+ "Y2hpZG5hICh0ZXN0IGtleSBvbmx5KSA8ZXJpY0Bib3VuY3ljYXN0bGUub3Jn"
+ "PohZBBMRAgAZBQJAEfI2BAsHAwIDFQIDAxYCAQIeAQIXgAAKCRAOtk6iUOgn"
+ "kDdnAJ9Ala3OcwEV1DbK906CheYWo4zIQwCfUqUOLMp/zj6QAk02bbJAhV1r"
+ "sAewAgAAnQFYBEAR8jgQBAC2kr57iuOaV7Ga1xcU14MNbKcA0PVembRCjcVj"
+ "ei/3yVfT/fuCVtGHOmYLEBqHbn5aaJ0P/6vMbLCHKuN61NZlts+LEctfwoya"
+ "43RtcubqMc7eKw4k0JnnoYgBocLXOtloCb7jfubOsnfORvrUkK0+Ne6anRhF"
+ "BYfaBmGU75cQgwADBQP/XxR2qGHiwn+0YiMioRDRiIAxp6UiC/JQIri2AKSq"
+ "Ai0zeAMdrRsBN7kyzYVVpWwN5u13gPdQ2HnJ7d4wLWAuizUdKIQxBG8VoCxk"
+ "bipnwh2RR4xCXFDhJrJFQUm+4nKx9JvAmZTBIlI5Wsi5qxst/9p5MgP3flXs"
+ "Ni1tRbTmRhr+AwMC3lHLFcSAtrNg/EiWFLAnKNXH27zjwuhje8u2r+9iMTYs"
+ "GjbRxaxRY0GKRhttCwqe2BC0lHhzifdlEcc9yjIjuKfepG2fnnSIRgQYEQIA"
+ "BgUCQBHyOAAKCRAOtk6iUOgnkBStAJ9HFejVtVJ/A9LM/mDPe0ExhEXt/QCg"
+ "m/KM7hJ/JrfnLQl7IaZsdg1F6vCwAgAA");
private static readonly byte[] encMessage = Base64.Decode(
"hQEOAynbo4lhNjcHEAP/dgCkMtPB6mIgjFvNiotjaoh4sAXf4vFNkSeehQ2c"
+ "r+IMt9CgIYodJI3FoJXxOuTcwesqTp5hRzgUBJS0adLDJwcNubFMy0M2tp5o"
+ "KTWpXulIiqyO6f5jI/oEDHPzFoYgBmR4x72l/YpMy8UoYGtNxNvR7LVOfqJv"
+ "uDY/71KMtPQEAIadOWpf1P5Td+61Zqn2VH2UV7H8eI6hGa6Lsy4sb9iZNE7f"
+ "c+spGJlgkiOt8TrQoq3iOK9UN9nHZLiCSIEGCzsEn3uNuorD++Qs065ij+Oy"
+ "36TKeuJ+38CfT7u47dEshHCPqWhBKEYrxZWHUJU/izw2Q1Yxd2XRxN+nafTL"
+ "X1fQ0lABQUASa18s0BkkEERIdcKQXVLEswWcGqWNv1ZghC7xO2VDBX4HrPjp"
+ "drjL63p2UHzJ7/4gPWGGtnqq1Xita/1mrImn7pzLThDWiT55vjw6Hw==");
private static readonly byte[] signedAndEncMessage = Base64.Decode(
"hQEOAynbo4lhNjcHEAP+K20MVhzdX57hf/cU8TH0prP0VePr9mmeBedzqqMn"
+ "fp2p8Zb68zmcMlI/WiL5XMNLYRmCgEcXyWbKdP/XV9m9LDBe1CMAGrkCeGBy"
+ "je69IQQ5LS9vDPyEMF4iAAv/EqACjqHkizdY/a/FRx/t2ioXYdEC2jA6kS9C"
+ "McpsNz16DE8EAIk3uKn4bGo/+15TXkyFYzW5Cf71SfRoHNmU2zAI93zhjN+T"
+ "B7mGJwWXzsMkIO6FkMU5TCSrwZS3DBWCIaJ6SYoaawE/C/2j9D7bX1Jv8kum"
+ "4cq+eZM7z6JYs6xend+WAwittpUxbEiyC2AJb3fBSXPAbLqWd6J6xbZZ7GDK"
+ "r2Ca0pwBxwGhbMDyi2zpHLzw95H7Ah2wMcGU6kMLB+hzBSZ6mSTGFehqFQE3"
+ "2BnAj7MtnbghiefogacJ891jj8Y2ggJeKDuRz8j2iICaTOy+Y2rXnnJwfYzm"
+ "BMWcd2h1C5+UeBJ9CrrLniCCI8s5u8z36Rno3sfhBnXdRmWSxExXtocbg1Ht"
+ "dyiThf6TK3W29Yy/T6x45Ws5zOasaJdsFKM=");
private static readonly char[] pass = "hello world".ToCharArray();
private static readonly SecureRandom random = new SecureRandom();
public override void PerformTest()
{
PgpPublicKey pubKey = null;
//
// Read the public key
//
PgpObjectFactory pgpFact = new PgpObjectFactory(testPubKeyRing);
PgpPublicKeyRing pgpPub = (PgpPublicKeyRing)pgpFact.NextPgpObject();
pubKey = pgpPub.GetPublicKey();
if (pubKey.BitStrength != 1024)
{
Fail("failed - key strength reported incorrectly.");
}
//
// Read the private key
//
PgpSecretKeyRing sKey = new PgpSecretKeyRing(testPrivKeyRing);
PgpSecretKey secretKey = sKey.GetSecretKey();
PgpPrivateKey pgpPrivKey = secretKey.ExtractPrivateKey(pass);
//
// signature generation
//
const string data = "hello world!";
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
MemoryStream bOut = new MemoryStream();
MemoryStream testIn = new MemoryStream(dataBytes, false);
PgpSignatureGenerator sGen = new PgpSignatureGenerator(PublicKeyAlgorithmTag.Dsa,
HashAlgorithmTag.Sha1);
sGen.InitSign(PgpSignature.BinaryDocument, pgpPrivKey);
PgpCompressedDataGenerator cGen = new PgpCompressedDataGenerator(
CompressionAlgorithmTag.Zip);
BcpgOutputStream bcOut = new BcpgOutputStream(
cGen.Open(new UncloseableStream(bOut)));
sGen.GenerateOnePassVersion(false).Encode(bcOut);
PgpLiteralDataGenerator lGen = new PgpLiteralDataGenerator();
DateTime testDateTime = new DateTime(1973, 7, 27);
Stream lOut = lGen.Open(
new UncloseableStream(bcOut),
PgpLiteralData.Binary,
"_CONSOLE",
dataBytes.Length,
testDateTime);
int ch;
while ((ch = testIn.ReadByte()) >= 0)
{
lOut.WriteByte((byte) ch);
sGen.Update((byte) ch);
}
lGen.Close();
sGen.Generate().Encode(bcOut);
cGen.Close();
//
// verify Generated signature
//
pgpFact = new PgpObjectFactory(bOut.ToArray());
PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();
pgpFact = new PgpObjectFactory(c1.GetDataStream());
PgpOnePassSignatureList p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
PgpOnePassSignature ops = p1[0];
PgpLiteralData p2 = (PgpLiteralData)pgpFact.NextPgpObject();
if (!p2.ModificationTime.Equals(testDateTime))
{
Fail("Modification time not preserved");
}
Stream dIn = p2.GetInputStream();
ops.InitVerify(pubKey);
while ((ch = dIn.ReadByte()) >= 0)
{
ops.Update((byte)ch);
}
PgpSignatureList p3 = (PgpSignatureList)pgpFact.NextPgpObject();
if (!ops.Verify(p3[0]))
{
Fail("Failed Generated signature check");
}
//
// test encryption
//
//
// find a key sutiable for encryption
//
long pgpKeyID = 0;
AsymmetricKeyParameter pKey = null;
foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
{
if (pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalEncrypt
|| pgpKey.Algorithm == PublicKeyAlgorithmTag.ElGamalGeneral)
{
pKey = pgpKey.GetKey();
pgpKeyID = pgpKey.KeyId;
if (pgpKey.BitStrength != 1024)
{
Fail("failed - key strength reported incorrectly.");
}
//
// verify the key
//
}
}
IBufferedCipher c = CipherUtilities.GetCipher("ElGamal/None/PKCS1Padding");
c.Init(true, pKey);
byte[] inBytes = Encoding.ASCII.GetBytes("hello world");
byte[] outBytes = c.DoFinal(inBytes);
pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);
c.Init(false, pgpPrivKey.Key);
outBytes = c.DoFinal(outBytes);
if (!Arrays.AreEqual(inBytes, outBytes))
{
Fail("decryption failed.");
}
//
// encrypted message
//
byte[] text = { (byte)'h', (byte)'e', (byte)'l', (byte)'l', (byte)'o',
(byte)' ', (byte)'w', (byte)'o', (byte)'r', (byte)'l', (byte)'d', (byte)'!', (byte)'\n' };
PgpObjectFactory pgpF = new PgpObjectFactory(encMessage);
PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();
PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];
Stream clear = encP.GetDataStream(pgpPrivKey);
pgpFact = new PgpObjectFactory(clear);
c1 = (PgpCompressedData)pgpFact.NextPgpObject();
pgpFact = new PgpObjectFactory(c1.GetDataStream());
PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();
if (!ld.FileName.Equals("test.txt"))
{
throw new Exception("wrong filename in packet");
}
Stream inLd = ld.GetDataStream();
byte[] bytes = Streams.ReadAll(inLd);
if (!Arrays.AreEqual(bytes, text))
{
Fail("wrong plain text in decrypted packet");
}
//
// signed and encrypted message
//
pgpF = new PgpObjectFactory(signedAndEncMessage);
encList = (PgpEncryptedDataList)pgpF.NextPgpObject();
encP = (PgpPublicKeyEncryptedData)encList[0];
clear = encP.GetDataStream(pgpPrivKey);
pgpFact = new PgpObjectFactory(clear);
c1 = (PgpCompressedData)pgpFact.NextPgpObject();
pgpFact = new PgpObjectFactory(c1.GetDataStream());
p1 = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
ops = p1[0];
ld = (PgpLiteralData)pgpFact.NextPgpObject();
bOut = new MemoryStream();
if (!ld.FileName.Equals("test.txt"))
{
throw new Exception("wrong filename in packet");
}
inLd = ld.GetDataStream();
//
// note: we use the DSA public key here.
//
ops.InitVerify(pgpPub.GetPublicKey());
while ((ch = inLd.ReadByte()) >= 0)
{
ops.Update((byte) ch);
bOut.WriteByte((byte) ch);
}
p3 = (PgpSignatureList)pgpFact.NextPgpObject();
if (!ops.Verify(p3[0]))
{
Fail("Failed signature check");
}
if (!Arrays.AreEqual(bOut.ToArray(), text))
{
Fail("wrong plain text in decrypted packet");
}
//
// encrypt
//
MemoryStream cbOut = new MemoryStream();
PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(
SymmetricKeyAlgorithmTag.TripleDes, random);
PgpPublicKey puK = sKey.GetSecretKey(pgpKeyID).PublicKey;
cPk.AddMethod(puK);
Stream cOut = cPk.Open(new UncloseableStream(cbOut), bOut.ToArray().Length);
cOut.Write(text, 0, text.Length);
cOut.Close();
pgpF = new PgpObjectFactory(cbOut.ToArray());
encList = (PgpEncryptedDataList)pgpF.NextPgpObject();
encP = (PgpPublicKeyEncryptedData)encList[0];
pgpPrivKey = sKey.GetSecretKey(pgpKeyID).ExtractPrivateKey(pass);
clear = encP.GetDataStream(pgpPrivKey);
outBytes = Streams.ReadAll(clear);
if (!Arrays.AreEqual(outBytes, text))
{
Fail("wrong plain text in Generated packet");
}
//
// use of PgpKeyPair
//
BigInteger g = new BigInteger("153d5d6172adb43045b68ae8e1de1070b6137005686d29d3d73a7749199681ee5b212c9b96bfdcfa5b20cd5e3fd2044895d609cf9b410b7a0f12ca1cb9a428cc", 16);
BigInteger p = new BigInteger("9494fec095f3b85ee286542b3836fc81a5dd0a0349b4c239dd38744d488cf8e31db8bcb7d33b41abb9e5a33cca9144b1cef332c94bf0573bf047a3aca98cdf3b", 16);
ElGamalParameters elParams = new ElGamalParameters(p, g);
IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));
AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();
PgpKeyPair pgpKp = new PgpKeyPair(PublicKeyAlgorithmTag.ElGamalGeneral ,
kp.Public, kp.Private, DateTime.UtcNow);
PgpPublicKey k1 = pgpKp.PublicKey;
PgpPrivateKey k2 = pgpKp.PrivateKey;
// Test bug with ElGamal P size != 0 mod 8 (don't use these sizes at home!)
for (int pSize = 257; pSize < 264; ++pSize)
{
// Generate some parameters of the given size
ElGamalParametersGenerator epg = new ElGamalParametersGenerator();
epg.Init(pSize, 2, random);
elParams = epg.GenerateParameters();
kpg = GeneratorUtilities.GetKeyPairGenerator("ELGAMAL");
kpg.Init(new ElGamalKeyGenerationParameters(random, elParams));
// Run a short encrypt/decrypt test with random key for the given parameters
kp = kpg.GenerateKeyPair();
PgpKeyPair elGamalKeyPair = new PgpKeyPair(
PublicKeyAlgorithmTag.ElGamalGeneral, kp, DateTime.UtcNow);
cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, random);
puK = elGamalKeyPair.PublicKey;
cPk.AddMethod(puK);
cbOut = new MemoryStream();
cOut = cPk.Open(new UncloseableStream(cbOut), text.Length);
cOut.Write(text, 0, text.Length);
cOut.Close();
pgpF = new PgpObjectFactory(cbOut.ToArray());
encList = (PgpEncryptedDataList)pgpF.NextPgpObject();
encP = (PgpPublicKeyEncryptedData)encList[0];
pgpPrivKey = elGamalKeyPair.PrivateKey;
// Note: This is where an exception would be expected if the P size causes problems
clear = encP.GetDataStream(pgpPrivKey);
byte[] decText = Streams.ReadAll(clear);
if (!Arrays.AreEqual(text, decText))
{
Fail("decrypted message incorrect");
}
}
// check sub key encoding
foreach (PgpPublicKey pgpKey in pgpPub.GetPublicKeys())
{
if (!pgpKey.IsMasterKey)
{
byte[] kEnc = pgpKey.GetEncoded();
PgpObjectFactory objF = new PgpObjectFactory(kEnc);
// TODO Make PgpPublicKey a PgpObject or return a PgpPublicKeyRing
// PgpPublicKey k = (PgpPublicKey)objF.NextPgpObject();
//
// pKey = k.GetKey();
// pgpKeyID = k.KeyId;
// if (k.BitStrength != 1024)
// {
// Fail("failed - key strength reported incorrectly.");
// }
//
// if (objF.NextPgpObject() != null)
// {
// Fail("failed - stream not fully parsed.");
// }
}
}
}
public override string Name
{
get { return "PGPDSAElGamalTest"; }
}
public static void Main(
string[] args)
{
RunTest(new PgpDsaElGamalTest());
}
[Test]
public void TestFunction()
{
string resultText = Perform().ToString();
Assert.AreEqual(Name + ": Okay", resultText);
}
}
}
| |
using System.Diagnostics;
using System;
using System.Management;
using System.Collections;
using Microsoft.VisualBasic;
using System.Data.SqlClient;
using System.Web.UI.Design;
using System.Data;
using System.Collections.Generic;
using System.Linq;
namespace SoftLogik.Mail
{
namespace Mail
{
namespace Pop3
{
[System.ComponentModel.DataObjectAttribute(true)]public class MailViewer
{
const int MAX_RECENTDAYS = 7;
private InboxManager m_MailService = null;
public InboxItemCollection GetRecentInbox(string ServerName, int PortNumber, bool UseSSL, string UserName, string Password)
{
InboxItemCollection colInbox = new InboxItemCollection();
colInbox = PrepareInbox(ServerName, PortNumber, UseSSL, UserName, Password, true, MAX_RECENTDAYS);
return colInbox;
}
public InboxItemCollection GetInbox(string ServerName, int PortNumber, bool UseSSL, string UserName, string Password)
{
InboxItemCollection colInbox = new InboxItemCollection();
colInbox = PrepareInbox(ServerName, PortNumber, UseSSL, UserName, Password, false, - 1);
return colInbox;
}
private InboxItemCollection PrepareInbox(string ServerName, int PortNumber, bool UseSSL, string UserName, string Password, bool Recent, int RecentPeriod)
{
InboxItemCollection colInbox = new InboxItemCollection();
try
{
if (!(string.IsNullOrEmpty(ServerName) && string.IsNullOrEmpty(UserName) && string.IsNullOrEmpty(Password)))
{
m_MailService = new InboxManager(ServerName, PortNumber, UseSSL, UserName, Password);
List<Mail.Pop3.RxMailMessage> inboxList = m_MailService.DownloadEmail(250);
try
{
foreach (Mail.Pop3.RxMailMessage inboxItem in inboxList)
{
if (Recent && RecentPeriod != - 1)
{
if (inboxItem.DeliveryDate >= DateTime.Now.AddDays(- RecentPeriod))
{
colInbox.Add(new InboxItem(inboxItem));
}
}
else
{
colInbox.Add(new InboxItem(inboxItem));
}
}
//Sort the inbox
colInbox.Sort(new InboxItemComparer());
}
catch (System.Exception)
{
}
}
}
catch (Mail.Pop3.Pop3Exception)
{
}
catch (System.Exception)
{
}
return colInbox;
}
}
#region Inbox Item Comparer
public class InboxItemComparer : IComparer<InboxItem>
{
public int Compare(InboxItem x, InboxItem y)
{
if (x == null)
{
if (y == null)
{
// If x is Nothing and y is Nothing, they're
// equal.
return 0;
}
else
{
// If x is Nothing and y is not Nothing, y
// is greater.
return - 1;
}
}
else
{
// If x is not Nothing...
//
if (y == null)
{
// ...and y is Nothing, x is greater.
return 1;
}
else
{
// ...and y is not Nothing, compare the
// date of the two inbox items.
//
int retval = y.DeliveryDate.CompareTo(x.DeliveryDate);
if (retval != 0)
{
// If the strings are not of equal length,
// the longer string is greater.
//
return retval;
}
else
{
// If the strings are of equal length,
// sort them with ordinary string comparison.
//
return x.EmailID.CompareTo(y.EmailID);
}
}
}
}
}
#endregion
#region Inbox Collection
public class InboxItemCollection : List<InboxItem>
{
public InboxItem this[string EmailID]
{
get
{
InboxItem itm = null;
foreach (InboxItem tempLoopVar_itm in this)
{
itm = tempLoopVar_itm;
if (itm.EmailID == EmailID)
{
break;
}
}
return itm;
}
}
}
#endregion
#region Inbox Item
public class InboxItem
{
private string m_strName;
private string m_strSubject;
private bool m_Select = false;
private Mail.Pop3.RxMailMessage m_innerEmail = null;
private Guid m_guidEmailID;
public InboxItem(Mail.Pop3.RxMailMessage NewMail)
{
m_guidEmailID = Guid.NewGuid();
this.m_strName = m_guidEmailID.ToString();
this.m_innerEmail = NewMail;
}
public string EmailID
{
get
{
return m_guidEmailID.ToString();
}
}
public Mail.Pop3.RxMailMessage Email
{
get
{
return m_innerEmail;
}
}
public bool @Select
{
get
{
return m_Select;
}
set
{
m_Select = value;
}
}
public string Sender
{
get
{
if (m_innerEmail.From != null)
{
return m_innerEmail.From.DisplayName;
}
else
{
return string.Empty;
}
}
}
public string Subject
{
get
{
return m_innerEmail.Subject;
}
}
public DateTime DeliveryDate
{
get
{
return m_innerEmail.DeliveryDate;
}
}
}
#endregion
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Workflows.V1Beta.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Workflows.Common.V1Beta;
using Google.LongRunning;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedWorkflowsClientSnippets
{
/// <summary>Snippet for ListWorkflows</summary>
public void ListWorkflowsRequestObject()
{
// Snippet: ListWorkflows(ListWorkflowsRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
ListWorkflowsRequest request = new ListWorkflowsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workflow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListWorkflowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkflowsAsync</summary>
public async Task ListWorkflowsRequestObjectAsync()
{
// Snippet: ListWorkflowsAsync(ListWorkflowsRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
ListWorkflowsRequest request = new ListWorkflowsRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Filter = "",
OrderBy = "",
};
// Make the request
PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workflow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkflows</summary>
public void ListWorkflows()
{
// Snippet: ListWorkflows(string, string, int?, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workflow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListWorkflowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkflowsAsync</summary>
public async Task ListWorkflowsAsync()
{
// Snippet: ListWorkflowsAsync(string, string, int?, CallSettings)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
// Make the request
PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workflow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkflows</summary>
public void ListWorkflowsResourceNames()
{
// Snippet: ListWorkflows(LocationName, string, int?, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflows(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (Workflow item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListWorkflowsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListWorkflowsAsync</summary>
public async Task ListWorkflowsResourceNamesAsync()
{
// Snippet: ListWorkflowsAsync(LocationName, string, int?, CallSettings)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
// Make the request
PagedAsyncEnumerable<ListWorkflowsResponse, Workflow> response = workflowsClient.ListWorkflowsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Workflow item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListWorkflowsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Workflow item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Workflow> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Workflow item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetWorkflow</summary>
public void GetWorkflowRequestObject()
{
// Snippet: GetWorkflow(GetWorkflowRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
// Make the request
Workflow response = workflowsClient.GetWorkflow(request);
// End snippet
}
/// <summary>Snippet for GetWorkflowAsync</summary>
public async Task GetWorkflowRequestObjectAsync()
{
// Snippet: GetWorkflowAsync(GetWorkflowRequest, CallSettings)
// Additional: GetWorkflowAsync(GetWorkflowRequest, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
GetWorkflowRequest request = new GetWorkflowRequest
{
WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
// Make the request
Workflow response = await workflowsClient.GetWorkflowAsync(request);
// End snippet
}
/// <summary>Snippet for GetWorkflow</summary>
public void GetWorkflow()
{
// Snippet: GetWorkflow(string, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]";
// Make the request
Workflow response = workflowsClient.GetWorkflow(name);
// End snippet
}
/// <summary>Snippet for GetWorkflowAsync</summary>
public async Task GetWorkflowAsync()
{
// Snippet: GetWorkflowAsync(string, CallSettings)
// Additional: GetWorkflowAsync(string, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]";
// Make the request
Workflow response = await workflowsClient.GetWorkflowAsync(name);
// End snippet
}
/// <summary>Snippet for GetWorkflow</summary>
public void GetWorkflowResourceNames()
{
// Snippet: GetWorkflow(WorkflowName, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]");
// Make the request
Workflow response = workflowsClient.GetWorkflow(name);
// End snippet
}
/// <summary>Snippet for GetWorkflowAsync</summary>
public async Task GetWorkflowResourceNamesAsync()
{
// Snippet: GetWorkflowAsync(WorkflowName, CallSettings)
// Additional: GetWorkflowAsync(WorkflowName, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]");
// Make the request
Workflow response = await workflowsClient.GetWorkflowAsync(name);
// End snippet
}
/// <summary>Snippet for CreateWorkflow</summary>
public void CreateWorkflowRequestObject()
{
// Snippet: CreateWorkflow(CreateWorkflowRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
CreateWorkflowRequest request = new CreateWorkflowRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Workflow = new Workflow(),
WorkflowId = "",
};
// Make the request
Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(request);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkflowAsync</summary>
public async Task CreateWorkflowRequestObjectAsync()
{
// Snippet: CreateWorkflowAsync(CreateWorkflowRequest, CallSettings)
// Additional: CreateWorkflowAsync(CreateWorkflowRequest, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
CreateWorkflowRequest request = new CreateWorkflowRequest
{
ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"),
Workflow = new Workflow(),
WorkflowId = "",
};
// Make the request
Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(request);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkflow</summary>
public void CreateWorkflow()
{
// Snippet: CreateWorkflow(string, Workflow, string, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Workflow workflow = new Workflow();
string workflowId = "";
// Make the request
Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(parent, workflow, workflowId);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkflowAsync</summary>
public async Task CreateWorkflowAsync()
{
// Snippet: CreateWorkflowAsync(string, Workflow, string, CallSettings)
// Additional: CreateWorkflowAsync(string, Workflow, string, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/locations/[LOCATION]";
Workflow workflow = new Workflow();
string workflowId = "";
// Make the request
Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(parent, workflow, workflowId);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkflow</summary>
public void CreateWorkflowResourceNames()
{
// Snippet: CreateWorkflow(LocationName, Workflow, string, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Workflow workflow = new Workflow();
string workflowId = "";
// Make the request
Operation<Workflow, OperationMetadata> response = workflowsClient.CreateWorkflow(parent, workflow, workflowId);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceCreateWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for CreateWorkflowAsync</summary>
public async Task CreateWorkflowResourceNamesAsync()
{
// Snippet: CreateWorkflowAsync(LocationName, Workflow, string, CallSettings)
// Additional: CreateWorkflowAsync(LocationName, Workflow, string, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
LocationName parent = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]");
Workflow workflow = new Workflow();
string workflowId = "";
// Make the request
Operation<Workflow, OperationMetadata> response = await workflowsClient.CreateWorkflowAsync(parent, workflow, workflowId);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceCreateWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflow</summary>
public void DeleteWorkflowRequestObject()
{
// Snippet: DeleteWorkflow(DeleteWorkflowRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
DeleteWorkflowRequest request = new DeleteWorkflowRequest
{
WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflowAsync</summary>
public async Task DeleteWorkflowRequestObjectAsync()
{
// Snippet: DeleteWorkflowAsync(DeleteWorkflowRequest, CallSettings)
// Additional: DeleteWorkflowAsync(DeleteWorkflowRequest, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
DeleteWorkflowRequest request = new DeleteWorkflowRequest
{
WorkflowName = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]"),
};
// Make the request
Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(request);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflow</summary>
public void DeleteWorkflow()
{
// Snippet: DeleteWorkflow(string, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]";
// Make the request
Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflowAsync</summary>
public async Task DeleteWorkflowAsync()
{
// Snippet: DeleteWorkflowAsync(string, CallSettings)
// Additional: DeleteWorkflowAsync(string, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/locations/[LOCATION]/workflows/[WORKFLOW]";
// Make the request
Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflow</summary>
public void DeleteWorkflowResourceNames()
{
// Snippet: DeleteWorkflow(WorkflowName, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]");
// Make the request
Operation<Empty, OperationMetadata> response = workflowsClient.DeleteWorkflow(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = workflowsClient.PollOnceDeleteWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for DeleteWorkflowAsync</summary>
public async Task DeleteWorkflowResourceNamesAsync()
{
// Snippet: DeleteWorkflowAsync(WorkflowName, CallSettings)
// Additional: DeleteWorkflowAsync(WorkflowName, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
WorkflowName name = WorkflowName.FromProjectLocationWorkflow("[PROJECT]", "[LOCATION]", "[WORKFLOW]");
// Make the request
Operation<Empty, OperationMetadata> response = await workflowsClient.DeleteWorkflowAsync(name);
// Poll until the returned long-running operation is complete
Operation<Empty, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Empty result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Empty, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceDeleteWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Empty retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateWorkflow</summary>
public void UpdateWorkflowRequestObject()
{
// Snippet: UpdateWorkflow(UpdateWorkflowRequest, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
UpdateWorkflowRequest request = new UpdateWorkflowRequest
{
Workflow = new Workflow(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<Workflow, OperationMetadata> response = workflowsClient.UpdateWorkflow(request);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceUpdateWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateWorkflowAsync</summary>
public async Task UpdateWorkflowRequestObjectAsync()
{
// Snippet: UpdateWorkflowAsync(UpdateWorkflowRequest, CallSettings)
// Additional: UpdateWorkflowAsync(UpdateWorkflowRequest, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
UpdateWorkflowRequest request = new UpdateWorkflowRequest
{
Workflow = new Workflow(),
UpdateMask = new FieldMask(),
};
// Make the request
Operation<Workflow, OperationMetadata> response = await workflowsClient.UpdateWorkflowAsync(request);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceUpdateWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateWorkflow</summary>
public void UpdateWorkflow()
{
// Snippet: UpdateWorkflow(Workflow, FieldMask, CallSettings)
// Create client
WorkflowsClient workflowsClient = WorkflowsClient.Create();
// Initialize request argument(s)
Workflow workflow = new Workflow();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Workflow, OperationMetadata> response = workflowsClient.UpdateWorkflow(workflow, updateMask);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = response.PollUntilCompleted();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = workflowsClient.PollOnceUpdateWorkflow(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
/// <summary>Snippet for UpdateWorkflowAsync</summary>
public async Task UpdateWorkflowAsync()
{
// Snippet: UpdateWorkflowAsync(Workflow, FieldMask, CallSettings)
// Additional: UpdateWorkflowAsync(Workflow, FieldMask, CancellationToken)
// Create client
WorkflowsClient workflowsClient = await WorkflowsClient.CreateAsync();
// Initialize request argument(s)
Workflow workflow = new Workflow();
FieldMask updateMask = new FieldMask();
// Make the request
Operation<Workflow, OperationMetadata> response = await workflowsClient.UpdateWorkflowAsync(workflow, updateMask);
// Poll until the returned long-running operation is complete
Operation<Workflow, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync();
// Retrieve the operation result
Workflow result = completedResponse.Result;
// Or get the name of the operation
string operationName = response.Name;
// This name can be stored, then the long-running operation retrieved later by name
Operation<Workflow, OperationMetadata> retrievedResponse = await workflowsClient.PollOnceUpdateWorkflowAsync(operationName);
// Check if the retrieved long-running operation has completed
if (retrievedResponse.IsCompleted)
{
// If it has completed, then access the result
Workflow retrievedResult = retrievedResponse.Result;
}
// End snippet
}
}
}
| |
// 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.VSNetIntegration.Shared
{
using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Castle.VSNetIntegration.CastleWizards.Shared;
using Castle.VSNetIntegration.CastleWizards.Shared.Dialogs;
using EnvDTE;
/// <summary>
///
/// </summary>
[ComVisible(false)]
public abstract class BaseProjectWizard : IDTWizard, IWin32Window, ICastleWizard
{
private static readonly object AddProjectsEventKey = new object();
private static readonly object SetupProjectsPropertiesEventKey = new object();
private static readonly object AddReferencesEventKey = new object();
private static readonly object SetupBuildEventsEventKey = new object();
private static readonly object PostProcessEventKey = new object();
private static readonly object AddPanelsEventKey = new object();
private int owner;
private DTE dteInstance;
private String projectName;
private String localProjectPath;
private String installationDirectory;
private String solutionName;
private String nameSpace;
private bool exclusive;
private ExtensionContext context;
private EventHandlerList eventList = new EventHandlerList();
#region ICastleWizard
public event WizardEventHandler OnAddProjects
{
add { eventList.AddHandler(AddProjectsEventKey, value); }
remove { eventList.RemoveHandler(AddProjectsEventKey, value); }
}
public event WizardEventHandler OnSetupProjectsProperties
{
add { eventList.AddHandler(SetupProjectsPropertiesEventKey, value); }
remove { eventList.RemoveHandler(SetupProjectsPropertiesEventKey, value); }
}
public event WizardEventHandler OnAddReferences
{
add { eventList.AddHandler(AddReferencesEventKey, value); }
remove { eventList.RemoveHandler(AddReferencesEventKey, value); }
}
public event WizardEventHandler OnSetupBuildEvents
{
add { eventList.AddHandler(SetupBuildEventsEventKey, value); }
remove { eventList.RemoveHandler(SetupBuildEventsEventKey, value); }
}
public event WizardEventHandler OnPostProcess
{
add { eventList.AddHandler(PostProcessEventKey, value); }
remove { eventList.RemoveHandler(PostProcessEventKey, value); }
}
public event WizardUIEventHandler OnAddPanels
{
add { eventList.AddHandler(AddPanelsEventKey, value); }
remove { eventList.RemoveHandler(AddPanelsEventKey, value); }
}
#endregion
public void Execute(object Application, int hwndOwner,
ref object[] ContextParams, ref object[] CustomParams, ref EnvDTE.wizardResult retval)
{
// TODO: Add magic here
IWizardExtension[] extensions = LoadExtensions(CustomParams);
foreach(IWizardExtension extension in extensions)
{
extension.Init(this);
}
try
{
dteInstance = (DTE) Application;
owner = hwndOwner;
projectName = (String) ContextParams[1];
localProjectPath = (String) ContextParams[2];
installationDirectory = (String) ContextParams[3];
exclusive = (bool) ContextParams[4];
solutionName = (String) ContextParams[5];
context = new ExtensionContext(dteInstance, projectName, localProjectPath, installationDirectory, solutionName);
if (exclusive)
{
vsPromptResult promptResult = dteInstance.ItemOperations.PromptToSave;
if (promptResult == vsPromptResult.vsPromptResultCancelled)
{
retval = wizardResult.wizardResultCancel;
return;
}
}
using(WizardDialog dlg = new WizardDialog(context))
{
dlg.WizardTitle = WizardTitle;
AddPanels(dlg);
WizardUIEventHandler eventHandler = (WizardUIEventHandler) eventList[AddPanelsEventKey];
if (eventHandler != null)
{
eventHandler(this, dlg, context);
}
dlg.ShowDialog(this);
retval = dlg.WizardResult;
if (retval == wizardResult.wizardResultSuccess)
{
CreateProject(dlg);
}
else
{
retval = wizardResult.wizardResultCancel;
return;
}
}
}
catch(Exception ex)
{
String message = ex.GetType().Name + "\r\n\r\n" + ex.Message + "\r\n\r\n" + ex.StackTrace;
MessageBox.Show(this, "Exception during project creation. \r\n" + message,
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw;
}
finally
{
foreach(IWizardExtension extension in extensions)
{
extension.Terminate(this);
}
}
}
protected void CreateProject(WizardDialog dlg)
{
AddProjects(context);
SetupProjectsProperties(context);
AddReferences(context);
SetupBuildEvents(context);
PostProcess(context);
}
protected virtual void PostProcess(ExtensionContext context)
{
WizardEventHandler eventHandler = (WizardEventHandler) eventList[PostProcessEventKey];
if (eventHandler != null)
{
eventHandler(this, context);
}
}
protected virtual void SetupBuildEvents(ExtensionContext context)
{
WizardEventHandler eventHandler = (WizardEventHandler) eventList[SetupBuildEventsEventKey];
if (eventHandler != null)
{
eventHandler(this, context);
}
}
protected virtual void AddReferences(ExtensionContext context)
{
WizardEventHandler eventHandler = (WizardEventHandler) eventList[AddReferencesEventKey];
if (eventHandler != null)
{
eventHandler(this, context);
}
}
protected virtual void SetupProjectsProperties(ExtensionContext context)
{
WizardEventHandler eventHandler = (WizardEventHandler) eventList[SetupProjectsPropertiesEventKey];
if (eventHandler != null)
{
eventHandler(this, context);
}
}
protected virtual void AddProjects(ExtensionContext context)
{
WizardEventHandler eventHandler = (WizardEventHandler) eventList[AddProjectsEventKey];
if (eventHandler != null)
{
eventHandler(this, context);
}
}
protected abstract void AddPanels(WizardDialog dlg);
protected abstract String WizardTitle { get; }
#region IWin32Window
public IntPtr Handle
{
get { return new IntPtr(owner); }
}
#endregion
#region Helper methods
public string ProjectName
{
get { return projectName; }
}
public string LocalProjectPath
{
get { return localProjectPath; }
}
public string InstallationDirectory
{
get { return installationDirectory; }
}
public string SolutionName
{
get { return solutionName; }
}
public bool Exclusive
{
get { return exclusive; }
}
public String NameSpace
{
get
{
if (nameSpace == null)
nameSpace = Utils.CreateValidIdentifierFromName(ProjectName);
return nameSpace;
}
}
#endregion
public ExtensionContext Context
{
get { return context; }
}
private IWizardExtension[] LoadExtensions(object[] customParams)
{
ArrayList extensions = new ArrayList();
AddExtensions(extensions);
try
{
foreach(String param in customParams)
{
if (param == String.Empty) continue;
String[] parts = param.Split('|');
String assemblyFile = parts[0];
String typeName = parts[1];
// Assembly assembly = Assembly.LoadFile(assemblyFile, AppDomain.CurrentDomain.Evidence);
Assembly assembly = Assembly.LoadFrom(assemblyFile, AppDomain.CurrentDomain.Evidence);
Type type = assembly.GetType(typeName);
extensions.Add( Activator.CreateInstance(type) );
}
}
catch(Exception ex)
{
MessageBox.Show(String.Format("{0} {1}", ex.Message, ex.StackTrace));
}
return (IWizardExtension[]) extensions.ToArray(typeof(IWizardExtension));
}
protected virtual void AddExtensions(IList extensions)
{
}
}
}
| |
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All
// rights reserved. This work is licensed under the BSD open source license,
// available at https://www.movesinstitute.org/licenses/bsd.html
//
// Author: DMcG
// Modified for use with C#:
// - Peter Smith (Naval Air Warfare Center - Training Systems Division)
// - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Text;
using System.Xml.Serialization;
using OpenDis.Core;
namespace OpenDis.Dis1998
{
/// <summary>
/// Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU. COMPLETE
/// </summary>
[Serializable]
[XmlRoot]
public partial class AcknowledgePdu : SimulationManagementFamilyPdu, IEquatable<AcknowledgePdu>
{
/// <summary>
/// type of message being acknowledged
/// </summary>
private ushort _acknowledgeFlag;
/// <summary>
/// Whether or not the receiving entity was able to comply with the request
/// </summary>
private ushort _responseFlag;
/// <summary>
/// Request ID that is unique
/// </summary>
private uint _requestID;
/// <summary>
/// Initializes a new instance of the <see cref="AcknowledgePdu"/> class.
/// </summary>
public AcknowledgePdu()
{
PduType = (byte)15;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if operands are not equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator !=(AcknowledgePdu left, AcknowledgePdu right)
{
return !(left == right);
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left operand.</param>
/// <param name="right">The right operand.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public static bool operator ==(AcknowledgePdu left, AcknowledgePdu right)
{
if (object.ReferenceEquals(left, right))
{
return true;
}
if (((object)left == null) || ((object)right == null))
{
return false;
}
return left.Equals(right);
}
public override int GetMarshalledSize()
{
int marshalSize = 0;
marshalSize = base.GetMarshalledSize();
marshalSize += 2; // this._acknowledgeFlag
marshalSize += 2; // this._responseFlag
marshalSize += 4; // this._requestID
return marshalSize;
}
/// <summary>
/// Gets or sets the type of message being acknowledged
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "acknowledgeFlag")]
public ushort AcknowledgeFlag
{
get
{
return this._acknowledgeFlag;
}
set
{
this._acknowledgeFlag = value;
}
}
/// <summary>
/// Gets or sets the Whether or not the receiving entity was able to comply with the request
/// </summary>
[XmlElement(Type = typeof(ushort), ElementName = "responseFlag")]
public ushort ResponseFlag
{
get
{
return this._responseFlag;
}
set
{
this._responseFlag = value;
}
}
/// <summary>
/// Gets or sets the Request ID that is unique
/// </summary>
[XmlElement(Type = typeof(uint), ElementName = "requestID")]
public uint RequestID
{
get
{
return this._requestID;
}
set
{
this._requestID = value;
}
}
/// <summary>
/// Automatically sets the length of the marshalled data, then calls the marshal method.
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
public override void MarshalAutoLengthSet(DataOutputStream dos)
{
// Set the length prior to marshalling data
this.Length = (ushort)this.GetMarshalledSize();
this.Marshal(dos);
}
/// <summary>
/// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method
/// </summary>
/// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Marshal(DataOutputStream dos)
{
base.Marshal(dos);
if (dos != null)
{
try
{
dos.WriteUnsignedShort((ushort)this._acknowledgeFlag);
dos.WriteUnsignedShort((ushort)this._responseFlag);
dos.WriteUnsignedInt((uint)this._requestID);
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Unmarshal(DataInputStream dis)
{
base.Unmarshal(dis);
if (dis != null)
{
try
{
this._acknowledgeFlag = dis.ReadUnsignedShort();
this._responseFlag = dis.ReadUnsignedShort();
this._requestID = dis.ReadUnsignedInt();
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
}
/// <summary>
/// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging.
/// This will be modified in the future to provide a better display. Usage:
/// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb });
/// where pdu is an object representing a single pdu and sb is a StringBuilder.
/// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality
/// </summary>
/// <param name="sb">The StringBuilder instance to which the PDU is written to.</param>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")]
public override void Reflection(StringBuilder sb)
{
sb.AppendLine("<AcknowledgePdu>");
base.Reflection(sb);
try
{
sb.AppendLine("<acknowledgeFlag type=\"ushort\">" + this._acknowledgeFlag.ToString(CultureInfo.InvariantCulture) + "</acknowledgeFlag>");
sb.AppendLine("<responseFlag type=\"ushort\">" + this._responseFlag.ToString(CultureInfo.InvariantCulture) + "</responseFlag>");
sb.AppendLine("<requestID type=\"uint\">" + this._requestID.ToString(CultureInfo.InvariantCulture) + "</requestID>");
sb.AppendLine("</AcknowledgePdu>");
}
catch (Exception e)
{
if (PduBase.TraceExceptions)
{
Trace.WriteLine(e);
Trace.Flush();
}
this.RaiseExceptionOccured(e);
if (PduBase.ThrowExceptions)
{
throw e;
}
}
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
public override bool Equals(object obj)
{
return this == obj as AcknowledgePdu;
}
/// <summary>
/// Compares for reference AND value equality.
/// </summary>
/// <param name="obj">The object to compare with this instance.</param>
/// <returns>
/// <c>true</c> if both operands are equal; otherwise, <c>false</c>.
/// </returns>
public bool Equals(AcknowledgePdu obj)
{
bool ivarsEqual = true;
if (obj.GetType() != this.GetType())
{
return false;
}
ivarsEqual = base.Equals(obj);
if (this._acknowledgeFlag != obj._acknowledgeFlag)
{
ivarsEqual = false;
}
if (this._responseFlag != obj._responseFlag)
{
ivarsEqual = false;
}
if (this._requestID != obj._requestID)
{
ivarsEqual = false;
}
return ivarsEqual;
}
/// <summary>
/// HashCode Helper
/// </summary>
/// <param name="hash">The hash value.</param>
/// <returns>The new hash value.</returns>
private static int GenerateHash(int hash)
{
hash = hash << (5 + hash);
return hash;
}
/// <summary>
/// Gets the hash code.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
int result = 0;
result = GenerateHash(result) ^ base.GetHashCode();
result = GenerateHash(result) ^ this._acknowledgeFlag.GetHashCode();
result = GenerateHash(result) ^ this._responseFlag.GetHashCode();
result = GenerateHash(result) ^ this._requestID.GetHashCode();
return result;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
namespace Orleans.Runtime.Scheduler
{
[DebuggerDisplay("OrleansTaskScheduler RunQueue={RunQueue.Length}")]
internal class OrleansTaskScheduler : TaskScheduler, ITaskScheduler, IHealthCheckParticipant
{
private readonly TraceLogger logger = TraceLogger.GetLogger("Scheduler.OrleansTaskScheduler", TraceLogger.LoggerType.Runtime);
private readonly ConcurrentDictionary<ISchedulingContext, WorkItemGroup> workgroupDirectory; // work group directory
private bool applicationTurnsStopped;
internal WorkQueue RunQueue { get; private set; }
internal WorkerPool Pool { get; private set; }
internal static TimeSpan TurnWarningLengthThreshold { get; set; }
internal TimeSpan DelayWarningThreshold { get; private set; }
public static OrleansTaskScheduler Instance { get; private set; }
public int RunQueueLength { get { return RunQueue.Length; } }
public OrleansTaskScheduler(int maxActiveThreads)
: this(maxActiveThreads, TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100), TimeSpan.FromMilliseconds(100),
NodeConfiguration.INJECT_MORE_WORKER_THREADS)
{
}
public OrleansTaskScheduler(GlobalConfiguration globalConfig, NodeConfiguration config)
: this(config.MaxActiveThreads, config.DelayWarningThreshold, config.ActivationSchedulingQuantum,
config.TurnWarningLengthThreshold, config.InjectMoreWorkerThreads)
{
}
private OrleansTaskScheduler(int maxActiveThreads, TimeSpan delayWarningThreshold, TimeSpan activationSchedulingQuantum,
TimeSpan turnWarningLengthThreshold, bool injectMoreWorkerThreads)
{
Instance = this;
DelayWarningThreshold = delayWarningThreshold;
WorkItemGroup.ActivationSchedulingQuantum = activationSchedulingQuantum;
TurnWarningLengthThreshold = turnWarningLengthThreshold;
applicationTurnsStopped = false;
workgroupDirectory = new ConcurrentDictionary<ISchedulingContext, WorkItemGroup>();
RunQueue = new WorkQueue();
logger.Info("Starting OrleansTaskScheduler with {0} Max Active application Threads and 1 system thread.", maxActiveThreads);
Pool = new WorkerPool(this, maxActiveThreads, injectMoreWorkerThreads);
IntValueStatistic.FindOrCreate(StatisticNames.SCHEDULER_WORKITEMGROUP_COUNT, () => WorkItemGroupCount);
IntValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_INSTANTANEOUS_PER_QUEUE, "Scheduler.LevelOne"), () => RunQueueLength);
if (!StatisticsCollector.CollectShedulerQueuesStats) return;
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Average"), () => AverageArrivalRateLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_QUEUE_SIZE_AVERAGE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumRunQueueLengthLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_ENQUEUED_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumEnqueuedLevelTwo);
FloatValueStatistic.FindOrCreate(new StatisticName(StatisticNames.QUEUES_AVERAGE_ARRIVAL_RATE_PER_QUEUE, "Scheduler.LevelTwo.Sum"), () => SumArrivalRateLevelTwo);
}
public int WorkItemGroupCount { get { return workgroupDirectory.Count; } }
private float AverageRunQueueLengthLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageEnqueuedLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests) / (float)workgroupDirectory.Values.Count;
}
}
private float AverageArrivalRateLevelTwo
{
get
{
if (workgroupDirectory.IsEmpty)
return 0;
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate) / (float)workgroupDirectory.Values.Count;
}
}
private float SumRunQueueLengthLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.AverageQueueLenght);
}
}
private float SumEnqueuedLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.NumEnqueuedRequests);
}
}
private float SumArrivalRateLevelTwo
{
get
{
return (float)workgroupDirectory.Values.Sum(workgroup => workgroup.ArrivalRate);
}
}
public void Start()
{
Pool.Start();
}
public void StopApplicationTurns()
{
#if DEBUG
if (logger.IsVerbose) logger.Verbose("StopApplicationTurns");
#endif
RunQueue.RunDownApplication();
applicationTurnsStopped = true;
foreach (var group in workgroupDirectory.Values)
{
if (!group.IsSystem)
group.Stop();
}
}
public void Stop()
{
RunQueue.RunDown();
Pool.Stop();
}
protected override IEnumerable<Task> GetScheduledTasks()
{
return new Task[0];
}
protected override void QueueTask(Task task)
{
var contextObj = task.AsyncState;
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = contextObj as ISchedulingContext;
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystem)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
logger.Warn(ErrorCode.SchedulerAppTurnsStopped, string.Format("Dropping Task {0} because applicaiton turns are stopped", task));
return;
}
if (workItemGroup == null)
{
var todo = new TaskWorkItem(this, task, context);
RunQueue.Add(todo);
}
else
{
var error = String.Format("QueueTask was called on OrleansTaskScheduler for task {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueTask with tasks on the null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerQueueTaskWrongCall, error);
throw new InvalidOperationException(error);
}
}
// Enqueue a work item to a given context
public void QueueWorkItem(IWorkItem workItem, ISchedulingContext context)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("QueueWorkItem " + context);
#endif
if (workItem is TaskWorkItem)
{
var error = String.Format("QueueWorkItem was called on OrleansTaskScheduler for TaskWorkItem {0} on Context {1}."
+ " Should only call OrleansTaskScheduler.QueueWorkItem on WorkItems that are NOT TaskWorkItem. Tasks should be queued to the scheduler via QueueTask call.",
workItem.ToString(), context);
logger.Error(ErrorCode.SchedulerQueueWorkItemWrongCall, error);
throw new InvalidOperationException(error);
}
var workItemGroup = GetWorkItemGroup(context);
if (applicationTurnsStopped && (workItemGroup != null) && !workItemGroup.IsSystem)
{
// Drop the task on the floor if it's an application work item and application turns are stopped
var msg = string.Format("Dropping work item {0} because applicaiton turns are stopped", workItem);
logger.Warn(ErrorCode.SchedulerAppTurnsStopped, msg);
return;
}
workItem.SchedulingContext = context;
// We must wrap any work item in Task and enqueue it as a task to the right scheduler via Task.Start.
// This will make sure the TaskScheduler.Current is set correctly on any task that is created implicitly in the execution of this workItem.
if (workItemGroup == null)
{
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, this);
t.Start(this);
}
else
{
// Create Task wrapper for this work item
Task t = TaskSchedulerUtils.WrapWorkItemAsTask(workItem, context, workItemGroup.TaskRunner);
t.Start(workItemGroup.TaskRunner);
}
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public WorkItemGroup RegisterWorkContext(ISchedulingContext context)
{
if (context == null) return null;
var wg = new WorkItemGroup(this, context);
workgroupDirectory.TryAdd(context, wg);
return wg;
}
// Only required if you have work groups flagged by a context that is not a WorkGroupingContext
public void UnregisterWorkContext(ISchedulingContext context)
{
if (context == null) return;
WorkItemGroup workGroup;
if (workgroupDirectory.TryRemove(context, out workGroup))
workGroup.Stop();
}
// public for testing only -- should be private, otherwise
public WorkItemGroup GetWorkItemGroup(ISchedulingContext context)
{
WorkItemGroup workGroup = null;
if (context != null)
workgroupDirectory.TryGetValue(context, out workGroup);
return workGroup;
}
public TaskScheduler GetTaskScheduler(ISchedulingContext context)
{
if (context == null)
return this;
WorkItemGroup workGroup;
return workgroupDirectory.TryGetValue(context, out workGroup) ? (TaskScheduler) workGroup.TaskRunner : this;
}
public override int MaximumConcurrencyLevel { get { return Pool.MaxActiveThreads; } }
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
//bool canExecuteInline = WorkerPoolThread.CurrentContext != null;
var ctx = RuntimeContext.Current;
bool canExecuteInline = ctx == null || ctx.ActivationContext==null;
#if DEBUG
if (logger.IsVerbose2)
{
logger.Verbose2("TryExecuteTaskInline Id={0} with Status={1} PreviouslyQueued={2} CanExecute={3}",
task.Id, task.Status, taskWasPreviouslyQueued, canExecuteInline);
}
#endif
if (!canExecuteInline) return false;
if (taskWasPreviouslyQueued)
canExecuteInline = TryDequeue(task);
if (!canExecuteInline) return false; // We can't execute tasks in-line on non-worker pool threads
// We are on a worker pool thread, so can execute this task
bool done = TryExecuteTask(task);
if (!done)
{
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete1, "TryExecuteTaskInline: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
return done;
}
/// <summary>
/// Run the specified task synchronously on the current thread
/// </summary>
/// <param name="task"><c>Task</c> to be executed</param>
public void RunTask(Task task)
{
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Id={0} with Status={1} AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
var context = RuntimeContext.CurrentActivationContext;
var workItemGroup = GetWorkItemGroup(context);
if (workItemGroup == null)
{
RuntimeContext.SetExecutionContext(null, this);
bool done = TryExecuteTask(task);
if (!done)
logger.Warn(ErrorCode.SchedulerTaskExecuteIncomplete2, "RunTask: Incomplete base.TryExecuteTask for Task Id={0} with Status={1}",
task.Id, task.Status);
}
else
{
var error = String.Format("RunTask was called on OrleansTaskScheduler for task {0} on Context {1}. Should only call OrleansTaskScheduler.RunTask on tasks queued on a null context.",
task.Id, context);
logger.Error(ErrorCode.SchedulerTaskRunningOnWrongScheduler1, error);
throw new InvalidOperationException(error);
}
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("RunTask: Completed Id={0} with Status={1} task.AsyncState={2} when TaskScheduler.Current={3}", task.Id, task.Status, task.AsyncState, Current);
#endif
}
// Returns true if healthy, false if not
public bool CheckHealth(DateTime lastCheckTime)
{
return Pool.DoHealthCheck();
}
/// <summary>
/// Action to be invoked when there is no more work for this scheduler
/// </summary>
internal Action OnIdle { get; set; }
/// <summary>
/// Invoked by WorkerPool when all threads go idle
/// </summary>
internal void OnAllWorkerThreadsIdle()
{
if (OnIdle == null || RunQueueLength != 0) return;
#if DEBUG
if (logger.IsVerbose2) logger.Verbose2("OnIdle");
#endif
OnIdle();
}
internal void PrintStatistics()
{
if (!logger.IsInfo) return;
var stats = Utils.EnumerableToString(workgroupDirectory.Values.OrderBy(wg => wg.Name), wg => string.Format("--{0}", wg.DumpStatus()), "\r\n");
if (stats.Length > 0)
logger.LogWithoutBulkingAndTruncating(Logger.Severity.Info, ErrorCode.SchedulerStatistics, "OrleansTaskScheduler.PrintStatistics(): RunQueue={0}, WorkItems={1}, Directory:\n{2}",
RunQueue.Length, WorkItemGroupCount, stats);
}
internal void DumpSchedulerStatus(bool alwaysOutput = true)
{
if (!logger.IsVerbose && !alwaysOutput) return;
PrintStatistics();
var sb = new StringBuilder();
sb.AppendLine("Dump of current OrleansTaskScheduler status:");
sb.AppendFormat("CPUs={0} RunQueue={1}, WorkItems={2} {3}",
Environment.ProcessorCount,
RunQueue.Length,
workgroupDirectory.Count,
applicationTurnsStopped ? "STOPPING" : "").AppendLine();
sb.AppendLine("RunQueue:");
RunQueue.DumpStatus(sb);
Pool.DumpStatus(sb);
foreach (var workgroup in workgroupDirectory.Values)
sb.AppendLine(workgroup.DumpStatus());
logger.LogWithoutBulkingAndTruncating(Logger.Severity.Info, ErrorCode.SchedulerStatus, sb.ToString());
}
}
}
| |
// 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.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http.Headers
{
public class ViaHeaderValue : ICloneable
{
private string _protocolName;
private string _protocolVersion;
private string _receivedBy;
private string _comment;
public string ProtocolName
{
get { return _protocolName; }
}
public string ProtocolVersion
{
get { return _protocolVersion; }
}
public string ReceivedBy
{
get { return _receivedBy; }
}
public string Comment
{
get { return _comment; }
}
public ViaHeaderValue(string protocolVersion, string receivedBy)
: this(protocolVersion, receivedBy, null, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName)
: this(protocolVersion, receivedBy, protocolName, null)
{
}
public ViaHeaderValue(string protocolVersion, string receivedBy, string protocolName, string comment)
{
HeaderUtilities.CheckValidToken(protocolVersion, "protocolVersion");
CheckReceivedBy(receivedBy);
if (!string.IsNullOrEmpty(protocolName))
{
HeaderUtilities.CheckValidToken(protocolName, "protocolName");
_protocolName = protocolName;
}
if (!string.IsNullOrEmpty(comment))
{
HeaderUtilities.CheckValidComment(comment, "comment");
_comment = comment;
}
_protocolVersion = protocolVersion;
_receivedBy = receivedBy;
}
private ViaHeaderValue()
{
}
private ViaHeaderValue(ViaHeaderValue source)
{
Contract.Requires(source != null);
_protocolName = source._protocolName;
_protocolVersion = source._protocolVersion;
_receivedBy = source._receivedBy;
_comment = source._comment;
}
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if (!string.IsNullOrEmpty(_protocolName))
{
sb.Append(_protocolName);
sb.Append('/');
}
sb.Append(_protocolVersion);
sb.Append(' ');
sb.Append(_receivedBy);
if (!string.IsNullOrEmpty(_comment))
{
sb.Append(' ');
sb.Append(_comment);
}
return sb.ToString();
}
public override bool Equals(object obj)
{
ViaHeaderValue other = obj as ViaHeaderValue;
if (other == null)
{
return false;
}
// Note that for token and host case-insensitive comparison is used. Comments are compared using case-
// sensitive comparison.
return string.Equals(_protocolVersion, other._protocolVersion, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_receivedBy, other._receivedBy, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_protocolName, other._protocolName, StringComparison.OrdinalIgnoreCase) &&
string.Equals(_comment, other._comment, StringComparison.Ordinal);
}
public override int GetHashCode()
{
int result = StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolVersion) ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_receivedBy);
if (!string.IsNullOrEmpty(_protocolName))
{
result = result ^ StringComparer.OrdinalIgnoreCase.GetHashCode(_protocolName);
}
if (!string.IsNullOrEmpty(_comment))
{
result = result ^ _comment.GetHashCode();
}
return result;
}
public static ViaHeaderValue Parse(string input)
{
int index = 0;
return (ViaHeaderValue)GenericHeaderParser.SingleValueViaParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out ViaHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueViaParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (ViaHeaderValue)output;
return true;
}
return false;
}
internal static int GetViaLength(string input, int startIndex, out object parsedValue)
{
Contract.Requires(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <protocolName> and <protocolVersion> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string protocolName = null;
string protocolVersion = null;
int current = GetProtocolEndIndex(input, startIndex, out protocolName, out protocolVersion);
// If we reached the end of the string after reading protocolName/Version we return (we expect at least
// <receivedBy> to follow). If reading protocolName/Version read 0 bytes, we return.
if ((current == startIndex) || (current == input.Length))
{
return 0;
}
Debug.Assert(protocolVersion != null);
// Read <receivedBy> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
string receivedBy = null;
int receivedByLength = HttpRuleParser.GetHostLength(input, current, true, out receivedBy);
if (receivedByLength == 0)
{
return 0;
}
current = current + receivedByLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
string comment = null;
if ((current < input.Length) && (input[current] == '('))
{
// We have a <comment> in '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'
int commentLength = 0;
if (HttpRuleParser.GetCommentLength(input, current, out commentLength) != HttpParseResult.Parsed)
{
return 0; // We found a '(' character but it wasn't a valid comment. Abort.
}
comment = input.Substring(current, commentLength);
current = current + commentLength;
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
ViaHeaderValue result = new ViaHeaderValue();
result._protocolVersion = protocolVersion;
result._protocolName = protocolName;
result._receivedBy = receivedBy;
result._comment = comment;
parsedValue = result;
return current - startIndex;
}
private static int GetProtocolEndIndex(string input, int startIndex, out string protocolName,
out string protocolVersion)
{
// We have a string of the form '[<protocolName>/]<protocolVersion> <receivedBy> [<comment>]'. The first
// token may either be the protocol name or protocol version. We'll only find out after reading the token
// and by looking at the following character: If it is a '/' we just parsed the protocol name, otherwise
// the protocol version.
protocolName = null;
protocolVersion = null;
int current = startIndex;
int protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0;
}
current = startIndex + protocolVersionOrNameLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
if (current == input.Length)
{
return 0;
}
if (input[current] == '/')
{
// We parsed the protocol name
protocolName = input.Substring(startIndex, protocolVersionOrNameLength);
current++; // skip the '/' delimiter
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
protocolVersionOrNameLength = HttpRuleParser.GetTokenLength(input, current);
if (protocolVersionOrNameLength == 0)
{
return 0; // We have a string "<token>/" followed by non-token chars. This is invalid.
}
protocolVersion = input.Substring(current, protocolVersionOrNameLength);
current = current + protocolVersionOrNameLength;
whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
}
else
{
protocolVersion = input.Substring(startIndex, protocolVersionOrNameLength);
}
if (whitespaceLength == 0)
{
return 0; // We were able to parse [<protocolName>/]<protocolVersion> but it wasn't followed by a WS
}
return current;
}
object ICloneable.Clone()
{
return new ViaHeaderValue(this);
}
private static void CheckReceivedBy(string receivedBy)
{
if (string.IsNullOrEmpty(receivedBy))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "receivedBy");
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(receivedBy, 0, true, out host) != receivedBy.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, receivedBy));
}
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// Scrollable Area Control. Can be actually by changing Value, external scrollbar or swipe gesture
/// </summary>
[ExecuteInEditMode]
[AddComponentMenu("2D Toolkit/UI/tk2dUIScrollableArea")]
public class tk2dUIScrollableArea : MonoBehaviour
{
/// <summary>
/// XAxis - horizontal, YAxis - vertical
/// </summary>
public enum Axes { XAxis, YAxis }
/// <summary>
/// Length of all the content in the scrollable area
/// </summary>
[SerializeField]
private float contentLength = 1;
public float ContentLength
{
get { return contentLength; }
set
{
ContentLengthVisibleAreaLengthChange(contentLength, value,visibleAreaLength,visibleAreaLength);
}
}
/// <summary>
/// Length of visible area of content, what can be seen
/// </summary>
[SerializeField]
private float visibleAreaLength = 1;
public float VisibleAreaLength
{
get { return visibleAreaLength; }
set
{
ContentLengthVisibleAreaLengthChange(contentLength, contentLength, visibleAreaLength, value);
}
}
/// <summary>
/// Transform the will be moved to scroll content. All content needs to be a child of this Transform
/// </summary>
public GameObject contentContainer;
/// <summary>
/// Scrollbar to be attached. Not required.
/// </summary>
public tk2dUIScrollbar scrollBar;
/// <summary>
/// Used to record swipe scrolling events
/// </summary>
public tk2dUIItem backgroundUIItem;
/// <summary>
/// Axes scrolling will happen on
/// </summary>
public Axes scrollAxes = Axes.YAxis;
/// <summary>
/// If swipe (gesture) scrolling is enabled
/// </summary>
public bool allowSwipeScrolling = true;
/// <summary>
/// If mouse will is enabled, hover needs to be active
/// </summary>
public bool allowScrollWheel = true;
[SerializeField]
[HideInInspector]
private tk2dUILayout backgroundLayoutItem = null;
public tk2dUILayout BackgroundLayoutItem {
get { return backgroundLayoutItem; }
set {
if (backgroundLayoutItem != value) {
if (backgroundLayoutItem != null) {
backgroundLayoutItem.OnReshape -= LayoutReshaped;
}
backgroundLayoutItem = value;
if (backgroundLayoutItem != null) {
backgroundLayoutItem.OnReshape += LayoutReshaped;
}
}
}
}
[SerializeField]
[HideInInspector]
private tk2dUILayoutContainer contentLayoutContainer = null;
public tk2dUILayoutContainer ContentLayoutContainer {
get { return contentLayoutContainer; }
set {
if (contentLayoutContainer != value) {
if (contentLayoutContainer != null) {
contentLayoutContainer.OnChangeContent -= ContentLayoutChangeCallback;
}
contentLayoutContainer = value;
if (contentLayoutContainer != null) {
contentLayoutContainer.OnChangeContent += ContentLayoutChangeCallback;
}
}
}
}
private bool isBackgroundButtonDown = false;
private bool isBackgroundButtonOver = false;
private Vector3 swipeScrollingPressDownStartLocalPos = Vector3.zero;
private Vector3 swipeScrollingContentStartLocalPos = Vector3.zero;
private Vector3 swipeScrollingContentDestLocalPos = Vector3.zero;
private bool isSwipeScrollingInProgress = false;
private const float SWIPE_SCROLLING_FIRST_SCROLL_THRESHOLD = .02f; //at what point swipe scrolling will start moving the list
private const float WITHOUT_SCROLLBAR_FIXED_SCROLL_WHEEL_PERCENT = .1f; //if not scrollbar attached how much scroll wheel will move list
private Vector3 swipePrevScrollingContentPressLocalPos = Vector3.zero;
private float swipeCurrVelocity = 0; //velocity of current frame (used for inertia swipe scrolling)
private float snapBackVelocity = 0;
public GameObject SendMessageTarget
{
get
{
if (backgroundUIItem != null)
{
return backgroundUIItem.sendMessageTarget;
}
else return null;
}
set
{
if (backgroundUIItem != null && backgroundUIItem.sendMessageTarget != value)
{
backgroundUIItem.sendMessageTarget = value;
#if UNITY_EDITOR
tk2dUtil.SetDirty(backgroundUIItem);
#endif
}
}
}
/// <summary>
/// If scrollable area is being scrolled
/// </summary>
public event System.Action<tk2dUIScrollableArea> OnScroll;
public string SendMessageOnScrollMethodName = "";
private float percent = 0; //0-1
/// <summary>
/// Scroll position percent 0-1
/// </summary>
public float Value
{
get { return Mathf.Clamp01( percent ); }
set
{
value = Mathf.Clamp(value, 0f, 1f);
if (value != percent)
{
UnpressAllUIItemChildren();
percent = value;
if (OnScroll != null) { OnScroll(this); }
if (isBackgroundButtonDown || isSwipeScrollingInProgress) {
if (tk2dUIManager.Instance__NoCreate != null) {
tk2dUIManager.Instance.OnInputUpdate -= BackgroundOverUpdate;
}
isBackgroundButtonDown = false;
isSwipeScrollingInProgress = false;
}
TargetOnScrollCallback();
}
if (scrollBar != null) { scrollBar.SetScrollPercentWithoutEvent(percent); }
SetContentPosition();
}
}
/// <summary>
/// Manually set scrolling percent without firing OnScroll event
/// </summary>
public void SetScrollPercentWithoutEvent(float newScrollPercent)
{
percent = Mathf.Clamp(newScrollPercent, 0f, 1f);
UnpressAllUIItemChildren();
if (scrollBar != null) { scrollBar.SetScrollPercentWithoutEvent(percent); }
SetContentPosition();
}
/// <summary>
/// Measures the content length. This isn't very fast, so if you know the content length
/// it is often more efficient to tell it rather than asking it to measure the content.
/// Returns the height in Unity units, of everything under the Content contentContainer.
/// </summary>
public float MeasureContentLength() {
Vector3 vector3Min = new Vector3(float.MinValue, float.MinValue, float.MinValue);
Vector3 vector3Max = new Vector3(float.MaxValue, float.MaxValue, float.MaxValue);
Vector3[] minMax = new Vector3[] {
vector3Max,
vector3Min
};
Transform t = contentContainer.transform;
GetRendererBoundsInChildren(t.worldToLocalMatrix, minMax, t);
if (minMax[0] != vector3Max && minMax[1] != vector3Min) {
minMax[0] = Vector3.Min(minMax[0], Vector3.zero);
minMax[1] = Vector3.Max(minMax[1], Vector3.zero);
return (scrollAxes == Axes.YAxis) ? (minMax[1].y - minMax[0].y) : (minMax[1].x - minMax[0].x);
}
else {
Debug.LogError("Unable to measure content length");
return VisibleAreaLength * 0.9f;
}
}
void OnEnable()
{
if (scrollBar != null)
{
scrollBar.OnScroll += ScrollBarMove;
}
if (backgroundUIItem != null)
{
backgroundUIItem.OnDown += BackgroundButtonDown;
backgroundUIItem.OnRelease += BackgroundButtonRelease;
backgroundUIItem.OnHoverOver += BackgroundButtonHoverOver;
backgroundUIItem.OnHoverOut += BackgroundButtonHoverOut;
}
if (backgroundLayoutItem != null)
{
backgroundLayoutItem.OnReshape += LayoutReshaped;
}
if (contentLayoutContainer != null)
{
contentLayoutContainer.OnChangeContent += ContentLayoutChangeCallback;
}
}
void OnDisable()
{
if (scrollBar != null)
{
scrollBar.OnScroll -= ScrollBarMove;
}
if (backgroundUIItem != null)
{
backgroundUIItem.OnDown -= BackgroundButtonDown;
backgroundUIItem.OnRelease -= BackgroundButtonRelease;
backgroundUIItem.OnHoverOver -= BackgroundButtonHoverOver;
backgroundUIItem.OnHoverOut -= BackgroundButtonHoverOut;
}
if (isBackgroundButtonOver)
{
if (tk2dUIManager.Instance__NoCreate != null)
{
tk2dUIManager.Instance.OnScrollWheelChange -= BackgroundHoverOverScrollWheelChange;
}
isBackgroundButtonOver = false;
}
if (isBackgroundButtonDown || isSwipeScrollingInProgress)
{
if (tk2dUIManager.Instance__NoCreate != null)
{
tk2dUIManager.Instance.OnInputUpdate -= BackgroundOverUpdate;
}
isBackgroundButtonDown = false;
isSwipeScrollingInProgress = false;
}
if (backgroundLayoutItem != null)
{
backgroundLayoutItem.OnReshape -= LayoutReshaped;
}
if (contentLayoutContainer != null)
{
contentLayoutContainer.OnChangeContent -= ContentLayoutChangeCallback;
}
swipeCurrVelocity = 0;
}
void Start()
{
UpdateScrollbarActiveState();
}
private void BackgroundHoverOverScrollWheelChange(float mouseWheelChange)
{
if (mouseWheelChange > 0)
{
if (scrollBar)
{
scrollBar.ScrollUpFixed();
}
else
{
Value -= WITHOUT_SCROLLBAR_FIXED_SCROLL_WHEEL_PERCENT;
}
}
else if (mouseWheelChange < 0)
{
if (scrollBar)
{
scrollBar.ScrollDownFixed();
}
else
{
Value += WITHOUT_SCROLLBAR_FIXED_SCROLL_WHEEL_PERCENT;
}
}
}
private void ScrollBarMove(tk2dUIScrollbar scrollBar)
{
Value = scrollBar.Value;
isSwipeScrollingInProgress = false;
if (isBackgroundButtonDown)
{
BackgroundButtonRelease();
}
}
Vector3 ContentContainerOffset {
get {
return Vector3.Scale(new Vector3(-1, 1, 1), contentContainer.transform.localPosition);
}
set {
contentContainer.transform.localPosition = Vector3.Scale(new Vector3(-1, 1, 1), value);
}
}
private void SetContentPosition()
{
Vector3 localPos = ContentContainerOffset;
float pos = (contentLength - visibleAreaLength) * Value;
if (pos < 0) { pos = 0; }
if (scrollAxes == Axes.XAxis)
{
localPos.x = pos;
}
else if (scrollAxes == Axes.YAxis)
{
localPos.y = pos;
}
ContentContainerOffset = localPos;
}
private void BackgroundButtonDown()
{
if (allowSwipeScrolling && contentLength > visibleAreaLength)
{
if (!isBackgroundButtonDown && !isSwipeScrollingInProgress)
{
tk2dUIManager.Instance.OnInputUpdate += BackgroundOverUpdate;
}
swipeScrollingPressDownStartLocalPos = transform.InverseTransformPoint(CalculateClickWorldPos(backgroundUIItem));
swipePrevScrollingContentPressLocalPos = swipeScrollingPressDownStartLocalPos;
swipeScrollingContentStartLocalPos = ContentContainerOffset;
swipeScrollingContentDestLocalPos = swipeScrollingContentStartLocalPos;
isBackgroundButtonDown = true;
swipeCurrVelocity = 0;
}
}
private void BackgroundOverUpdate()
{
if (isBackgroundButtonDown)
{
UpdateSwipeScrollDestintationPosition();
}
if (isSwipeScrollingInProgress)
{
float newPercent = percent;
float destValue = 0;
if (scrollAxes == Axes.XAxis)
{
destValue = swipeScrollingContentDestLocalPos.x;
}
else if (scrollAxes == Axes.YAxis)
{
destValue = swipeScrollingContentDestLocalPos.y;
}
float minDest = 0;
float maxDest = contentLength - visibleAreaLength;
if (isBackgroundButtonDown)
{
if (destValue < minDest)
{
destValue += (-destValue / visibleAreaLength) / 2;
if (destValue > minDest )
{
destValue =minDest;
}
}
else if (destValue > maxDest)
{
destValue-= ((destValue-maxDest)/visibleAreaLength)/2;
if (destValue< maxDest)
{
destValue=maxDest;
}
}
if (scrollAxes == Axes.XAxis)
{
swipeScrollingContentDestLocalPos.x = destValue;
}
else if (scrollAxes == Axes.YAxis)
{
swipeScrollingContentDestLocalPos.y = destValue;
}
if (contentLength - visibleAreaLength > Mathf.Epsilon)
{
newPercent = destValue / (contentLength - visibleAreaLength);
}
else
{
newPercent = 0;
}
}
else //background button not down
{
float velocityThreshold = visibleAreaLength * 0.001f;
if (destValue < minDest || destValue > maxDest)
{
float target = ( destValue < minDest ) ? minDest : maxDest;
destValue = Mathf.SmoothDamp( destValue, target, ref snapBackVelocity, 0.05f, Mathf.Infinity, tk2dUITime.deltaTime );
if (Mathf.Abs(snapBackVelocity) < velocityThreshold) {
destValue = target;
snapBackVelocity = 0;
}
swipeCurrVelocity = 0;
}
else if (swipeCurrVelocity != 0) //velocity scrolling
{
destValue += swipeCurrVelocity * tk2dUITime.deltaTime * 20; //swipe velocity multiplier
if (swipeCurrVelocity > velocityThreshold || swipeCurrVelocity < -velocityThreshold)
{
swipeCurrVelocity = Mathf.Lerp(swipeCurrVelocity, 0, tk2dUITime.deltaTime * 2.5f); //change multiplier to change slowdown velocity
}
else
{
swipeCurrVelocity = 0;
}
}
else
{
isSwipeScrollingInProgress = false;
tk2dUIManager.Instance.OnInputUpdate -= BackgroundOverUpdate;
}
if (scrollAxes == Axes.XAxis)
{
swipeScrollingContentDestLocalPos.x = destValue;
}
else if (scrollAxes == Axes.YAxis)
{
swipeScrollingContentDestLocalPos.y = destValue;
}
newPercent = destValue / (contentLength - visibleAreaLength);
}
if (newPercent != percent) {
percent = newPercent;
ContentContainerOffset = swipeScrollingContentDestLocalPos;
if (OnScroll != null) OnScroll(this);
TargetOnScrollCallback();
}
if (scrollBar != null)
{
float scrollBarPercent = percent;
if (scrollAxes == Axes.XAxis)
{
scrollBarPercent = (ContentContainerOffset.x / (contentLength - visibleAreaLength));
}
else if (scrollAxes == Axes.YAxis)
{
scrollBarPercent = (ContentContainerOffset.y / (contentLength - visibleAreaLength));
}
scrollBar.SetScrollPercentWithoutEvent(scrollBarPercent);
}
}
}
private void UpdateSwipeScrollDestintationPosition()
{
Vector3 currTouchPosLocal = transform.InverseTransformPoint(CalculateClickWorldPos(backgroundUIItem));
// X axis is inverted
Vector3 moveDiffVector = currTouchPosLocal - swipeScrollingPressDownStartLocalPos;
moveDiffVector.x *= -1;
float moveDiff = 0;
if (scrollAxes == Axes.XAxis)
{
moveDiff = moveDiffVector.x;
// Invert x axis
swipeCurrVelocity = -(currTouchPosLocal.x - swipePrevScrollingContentPressLocalPos.x);
}
else if (scrollAxes == Axes.YAxis)
{
moveDiff = moveDiffVector.y;
swipeCurrVelocity = currTouchPosLocal.y - swipePrevScrollingContentPressLocalPos.y;
}
if (!isSwipeScrollingInProgress)
{
if (Mathf.Abs(moveDiff) > SWIPE_SCROLLING_FIRST_SCROLL_THRESHOLD)
{
isSwipeScrollingInProgress = true;
//unpress anything currently pressed in list
tk2dUIManager.Instance.OverrideClearAllChildrenPresses(backgroundUIItem);
}
}
if (isSwipeScrollingInProgress)
{
Vector3 destContentPos = swipeScrollingContentStartLocalPos + moveDiffVector;
destContentPos.z = ContentContainerOffset.z;
if (scrollAxes == Axes.XAxis)
{
destContentPos.y = ContentContainerOffset.y;
}
else if (scrollAxes == Axes.YAxis)
{
destContentPos.x = ContentContainerOffset.x;
}
destContentPos.z = ContentContainerOffset.z;
swipeScrollingContentDestLocalPos = destContentPos;
swipePrevScrollingContentPressLocalPos = currTouchPosLocal;
}
}
private void BackgroundButtonRelease()
{
if (allowSwipeScrolling)
{
if (isBackgroundButtonDown)
{
if (!isSwipeScrollingInProgress)
{
tk2dUIManager.Instance.OnInputUpdate -= BackgroundOverUpdate;
}
}
isBackgroundButtonDown = false;
}
}
private void BackgroundButtonHoverOver()
{
if (allowScrollWheel)
{
if (!isBackgroundButtonOver)
{
tk2dUIManager.Instance.OnScrollWheelChange += BackgroundHoverOverScrollWheelChange;
}
isBackgroundButtonOver = true;
}
}
private void BackgroundButtonHoverOut()
{
if (isBackgroundButtonOver)
{
tk2dUIManager.Instance.OnScrollWheelChange -= BackgroundHoverOverScrollWheelChange;
}
isBackgroundButtonOver = false;
}
private Vector3 CalculateClickWorldPos(tk2dUIItem btn)
{
Vector2 pos = btn.Touch.position;
Camera viewingCamera = tk2dUIManager.Instance.GetUICameraForControl( gameObject );
Vector3 worldPos = viewingCamera.ScreenToWorldPoint(new Vector3(pos.x, pos.y, btn.transform.position.z - viewingCamera.transform.position.z));
worldPos.z = btn.transform.position.z;
return worldPos;
}
private void UpdateScrollbarActiveState()
{
bool scrollBarVisible = (contentLength > visibleAreaLength);
if (scrollBar != null)
{
#if UNITY_3_5
if (scrollBar.gameObject.active != scrollBarVisible)
#else
if (scrollBar.gameObject.activeSelf != scrollBarVisible)
#endif
{
tk2dUIBaseItemControl.ChangeGameObjectActiveState(scrollBar.gameObject, scrollBarVisible);
}
}
}
private void ContentLengthVisibleAreaLengthChange(float prevContentLength,float newContentLength,float prevVisibleAreaLength,float newVisibleAreaLength)
{
float newValue;
if (newContentLength-visibleAreaLength!=0)
{
newValue = ((prevContentLength - prevVisibleAreaLength) * Value) / (newContentLength - newVisibleAreaLength);
}
else
{
newValue = 0;
}
contentLength = newContentLength;
visibleAreaLength = newVisibleAreaLength;
UpdateScrollbarActiveState();
Value = newValue;
}
private void UnpressAllUIItemChildren()
{
}
private void TargetOnScrollCallback()
{
if (SendMessageTarget != null && SendMessageOnScrollMethodName.Length > 0)
{
SendMessageTarget.SendMessage( SendMessageOnScrollMethodName, this, SendMessageOptions.RequireReceiver );
}
}
private static readonly Vector3[] boxExtents = new Vector3[] {
new Vector3(-1, -1, -1), new Vector3( 1, -1, -1), new Vector3(-1, 1, -1), new Vector3( 1, 1, -1), new Vector3(-1, -1, 1), new Vector3( 1, -1, 1), new Vector3(-1, 1, 1), new Vector3( 1, 1, 1)
};
private static void GetRendererBoundsInChildren(Matrix4x4 rootWorldToLocal, Vector3[] minMax, Transform t) {
MeshFilter mf = t.GetComponent<MeshFilter>();
if (mf != null && mf.sharedMesh != null) {
Bounds b = mf.sharedMesh.bounds;
Matrix4x4 relativeMatrix = rootWorldToLocal * t.localToWorldMatrix;
for (int j = 0; j < 8; ++j) {
Vector3 localPoint = b.center + Vector3.Scale(b.extents, boxExtents[j]);
Vector3 pointRelativeToRoot = relativeMatrix.MultiplyPoint(localPoint);
minMax[0] = Vector3.Min(minMax[0], pointRelativeToRoot);
minMax[1] = Vector3.Max(minMax[1], pointRelativeToRoot);
}
}
int childCount = t.childCount;
for (int i = 0; i < childCount; ++i) {
Transform child = t.GetChild(i);
#if UNITY_3_5
if (t.gameObject.active) {
#else
if (t.gameObject.activeSelf) {
#endif
GetRendererBoundsInChildren(rootWorldToLocal, minMax, child);
}
}
}
private void LayoutReshaped(Vector3 dMin, Vector3 dMax)
{
VisibleAreaLength += (scrollAxes == Axes.XAxis) ? (dMax.x - dMin.x) : (dMax.y - dMin.y);
}
private void ContentLayoutChangeCallback()
{
if (contentLayoutContainer != null) {
Vector2 contentSize = contentLayoutContainer.GetInnerSize();
ContentLength = (scrollAxes == Axes.XAxis) ? contentSize.x : contentSize.y;
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections;
public class CreateVolumetricAssets : MonoBehaviour
{
public Texture3D tex3D;
public int n;
public Light _light;
public float absorption;
public float lightIntensityScale;
//public bool onlyGenerateTexture3D;
public string texture3DName = "pyroclasticNoise";
private Mesh m;
// Use this for initialization
public void Start() {
Debug.Log(SystemInfo.graphicsDeviceVersion);
if (SystemInfo.graphicsDeviceVersion.StartsWith("OpenGL") == false) {
Debug.LogError("The Volumetric Renderer Only Supports OpenGL!!!!");
}
else {
Debug.Log("OpenGL Renderer Detected");
}
CreateMesh();
//tex3D = Generate3DTexture();
Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint(
Camera.main.transform.position);
Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint(
_light.transform.position);
renderer.material.SetVector("g_eyePos", localEyePos);
renderer.material.SetVector("g_lightPos", localLightPos);
renderer.material.SetFloat("g_lightIntensity", _light.intensity);
renderer.material.SetFloat("g_absorption", absorption);
}
void OnWillRenderObject() {
Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint(
Camera.main.transform.position);
localEyePos += new Vector4(0.5f, 0.5f, 0.5f, 0.0f);
///localEyePos = new Vector3(0.0f, 0.0f, -1.3f);
renderer.material.SetVector("g_eyePos", localEyePos);
Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint(
_light.transform.position);
renderer.material.SetVector("g_lightPos", localLightPos);
renderer.material.SetFloat("g_lightIntensity", _light.intensity *
lightIntensityScale);
}
private Mesh CreateMesh() {
m = new Mesh();
CreateCube(m);
m.RecalculateBounds();
MeshFilter mf = (MeshFilter)transform.GetComponent(typeof(MeshFilter));
mf.mesh = m;
return m;
}
void CreateCube(Mesh m) {
Vector3[] vertices = new Vector3[24];
Vector2[] uv = new Vector2[24];
Color[] colors = new Color[24];
Vector3[] normals = new Vector3[24];
int[] triangles = new int[36];
int i = 0;
int ti = 0;
//Front
vertices[i] = new Vector3(-0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(0, 0, 0);
i++;
vertices[i] = new Vector3(0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(1, 0, 0);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(1, 1, 0);
i++;
vertices[i] = new Vector3(-0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(0, 1, 0);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 3;
triangles[ti++] = i - 4;
triangles[ti++] = i - 1;
triangles[ti++] = i - 2;
//Back
vertices[i] = new Vector3(-0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(0, 0, 1);
i++;
vertices[i] = new Vector3(0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(1, 0, 1);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(1, 1, 1);
i++;
vertices[i] = new Vector3(-0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 0, -1);
colors[i] = new Color(0, 1, 1);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 3;
triangles[ti++] = i - 2;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 1;
//Top
vertices[i] = new Vector3(-0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 1, 0);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 1, 0);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 1, 1);
i++;
vertices[i] = new Vector3(-0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 1, 1);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 3;
triangles[ti++] = i - 4;
triangles[ti++] = i - 1;
triangles[ti++] = i - 2;
//Bottom
vertices[i] = new Vector3(-0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 0, 0);
i++;
vertices[i] = new Vector3(0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 0, 0);
i++;
vertices[i] = new Vector3(0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 0, 1);
i++;
vertices[i] = new Vector3(-0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 0, 1);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 3;
triangles[ti++] = i - 2;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 1;
//Right
vertices[i] = new Vector3(0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 0, 0);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 1, 0);
i++;
vertices[i] = new Vector3(0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 1, 1);
i++;
vertices[i] = new Vector3(0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(1, 0, 1);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 3;
triangles[ti++] = i - 2;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 1;
//Left
vertices[i] = new Vector3(-0.5f, -0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 0, 0);
i++;
vertices[i] = new Vector3(-0.5f, 0.5f, -0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 1, 0);
i++;
vertices[i] = new Vector3(-0.5f, 0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 1, 1);
i++;
vertices[i] = new Vector3(-0.5f, -0.5f, 0.5f);
normals[i] = new Vector3(0, 1, 0);
colors[i] = new Color(0, 0, 1);
i++;
triangles[ti++] = i - 4;
triangles[ti++] = i - 2;
triangles[ti++] = i - 3;
triangles[ti++] = i - 4;
triangles[ti++] = i - 1;
triangles[ti++] = i - 2;
m.vertices = vertices;
m.colors = colors; //Putting uv's into the normal channel to get the
//Vector3 type
m.uv = uv;
m.normals = normals;
m.triangles = triangles;
}
public Texture3D Generate3DTexture() {
float r = 0.3f;
Texture3D texture3D = new Texture3D(n, n, n, TextureFormat.ARGB32, true);
int size = n * n * n;
Color[] cols = new Color[size];
int idx = 0;
Color c = Color.white;
float frequency = 0.01f / n;
float center = n / 2.0f + 0.5f;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++, ++idx) {
float dx = center - i;
float dy = center - j;
float dz = center - k;
float off = Mathf.Abs(Perlin.Turbulence(i * frequency,
j * frequency,
k * frequency,
6));
float d = Mathf.Sqrt(dx * dx + dy * dy + dz * dz) / (n);
//c.r = c.g = c.b = c.a = ((d-off) < r)?1.0f:0.0f;
float p = d - off;
c.r = c.g = c.b = c.a = Mathf.Clamp01(r - p);
cols[idx] = c;
}
}
}
//for(int i = 0; i < size; i++)
// Debug.Log (newC[i]);
texture3D.SetPixels(cols);
texture3D.Apply();
renderer.material.SetTexture("g_densityTex", texture3D);
texture3D.filterMode = FilterMode.Trilinear;
texture3D.wrapMode = TextureWrapMode.Clamp;
texture3D.anisoLevel = 1;
//Color[] cs = texture3D.GetPixels();
//for(int i = 0; i < 10; i++)
// Debug.Log (cs[i]);
return texture3D;
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using Glass.Mapper.Pipelines.ConfigurationResolver.Tasks.OnDemandResolver;
using Glass.Mapper.Sc.Configuration;
using Glass.Mapper.Sc.Fields;
using Glass.Mapper.Sc.Pipelines.GetChromeData;
using Glass.Mapper.Sc.RenderField;
using Glass.Mapper.Sc.Web.Ui;
using Sitecore.Collections;
using Sitecore.Data;
using Sitecore.Data.Events;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Pipelines;
using Sitecore.Pipelines.RenderField;
using Sitecore.SecurityModel;
using Sitecore.Text;
using Sitecore.Web;
namespace Glass.Mapper.Sc
{
/// <summary>
/// This class contains a set of helpers that make converting items mapped in Glass.Sitecore.Mapper to HTML
/// </summary>
public class GlassHtml : IGlassHtml
{
private static readonly Type ImageType = typeof(Image);
private static readonly Type LinkType = typeof(Link);
private static ConcurrentDictionary<string, object> _compileCache = new ConcurrentDictionary<string, object>();
public static string DisableEditable
{
get { return "DisableEditable"; }
}
private readonly Context _context;
static GlassHtml()
{
}
public const string Parameters = "Parameters";
/// <summary>
/// The image width
/// </summary>
public const string ImageWidth = "width";
/// <summary>
/// The image height
/// </summary>
public const string ImageHeight = "height";
/// <summary>
/// The image tag format
/// </summary>
public static string ImageTagFormat = "<img src={2}{0}{2} {1}/>";
public static string LinkTagFormat = "<a href={3}{0}{3} {1}>{2}";
public static string QuotationMark = "\"";
protected Func<T, string> GetCompiled<T>(Expression<Func<T, string>> expression)
{
if (!SitecoreContext.Config.UseGlassHtmlLambdaCache)
{
return expression.Compile();
}
var key = typeof(T).FullName + expression.Body;
if (_compileCache.ContainsKey(key))
{
try
{
return (Func<T, string>) _compileCache[key];
}
catch (Exception ex)
{
// Debugger.Launch();
}
}
var compiled = expression.Compile();
if (compiled is Func<T, string>)
{
_compileCache.TryAdd(key, compiled);
}
else
{
throw new MapperException("Failed to compile lambda to correct type.");
}
return compiled;
}
protected Func<T, object> GetCompiled<T>(Expression<Func<T, object>> expression)
{
if (SitecoreContext.Config == null || !SitecoreContext.Config.UseGlassHtmlLambdaCache)
{
return expression.Compile();
}
var key = typeof(T).FullName + expression.Body;
if (_compileCache.ContainsKey(key))
{
return (Func<T, object>)_compileCache[key];
}
var compiled = expression.Compile();
_compileCache.TryAdd(key, compiled);
return compiled;
}
/// <summary>
/// Gets the sitecore context.
/// </summary>
/// <value>
/// The sitecore context.
/// </value>
public ISitecoreContext SitecoreContext { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="GlassHtml"/> class.
/// </summary>
/// <param name="sitecoreContext">The service that will be used to load and save data</param>
public GlassHtml(ISitecoreContext sitecoreContext)
{
SitecoreContext = sitecoreContext;
_context = sitecoreContext.GlassContext;
}
/// <summary>
/// Edits the frame.
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="path">The path.</param>
/// <param name="output">The output text writer</param>
/// <param name="title">The title for the edit frame</param>
/// <returns>
/// GlassEditFrame.
/// </returns>
public GlassEditFrame EditFrame(string title, string buttons, string path = null, TextWriter output = null)
{
if (output == null)
{
output = HttpContext.Current.Response.Output;
}
var frame = new GlassEditFrame(title, buttons, output, path);
frame.RenderFirstPart();
return frame;
}
public GlassEditFrame EditFrame<T>(T model, string title = null, TextWriter output = null, params Expression<Func<T, object>>[] fields) where T : class
{
if (IsInEditingMode && Sitecore.Context.IsLoggedIn && model != null)
{
if (fields.Any())
{
var fieldIdsOrNames = fields.Select(x => Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(x, this.SitecoreContext.GlassContext, model))
.Cast<SitecoreFieldConfiguration>()
.Where(x => x != null)
.Select(x => x.FieldId != (ID)null ? x.FieldId.ToString() : x.FieldName);
var buttonPath = "{0}{1}".Formatted(
EditFrameBuilder.BuildToken,
string.Join("|", fieldIdsOrNames));
if (title.IsNotNullOrEmpty())
{
buttonPath += "<title>{0}<title>".Formatted(title);
}
var field = fields.FirstOrDefault();
var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, SitecoreContext.GlassContext, model);
var pathConfig = config.Properties
.OfType<SitecoreInfoConfiguration>()
.FirstOrDefault(x => x.Type == SitecoreInfoType.Path);
var path = string.Empty;
if (pathConfig == null)
{
var id = config.GetId(model);
if (id == ID.Null)
{
throw new MapperException(
"Failed to find ID. Ensure that you have an ID property on your model.");
}
var item = SitecoreContext.Database.GetItem(id);
path = item.Paths.Path;
}
else
{
path = pathConfig.PropertyGetter(model) as string;
}
return EditFrame(title, buttonPath, path, output);
}
}
return new GlassNullEditFrame();
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam>
/// <param name="target">The model object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public virtual string Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null)
{
return MakeEditable(field, null, target, parameters);
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam>
/// <param name="target">The model object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <param name="parameters">Additional rendering parameters, e.g. ImageParameters</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public virtual string Editable<T>(T target, Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, object parameters = null)
{
return MakeEditable(field, standardOutput, target, parameters);
}
public virtual string EditableIf<T>(T target, Func<bool> predicate, Expression<Func<T, object>> field, object parameters = null)
{
return EditableIf(target, predicate, field, null, parameters);
}
public virtual string EditableIf<T>(T target, Func<bool> predicate, Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput, object parameters = null)
{
if (predicate())
{
return MakeEditable(field, standardOutput, target, parameters);
}
else
{
var dictionary = ProcessParameters(parameters);
return NormalModeOutput(field, standardOutput, target, dictionary);
}
}
public virtual T GetRenderingParameters<T>(string parameters, ID renderParametersTemplateId) where T : class
{
var nameValueCollection = WebUtil.ParseUrlParameters(parameters);
return GetRenderingParameters<T>(nameValueCollection, renderParametersTemplateId);
}
public T GetRenderingParameters<T>(NameValueCollection parameters, ID renderParametersTemplateId) where T : class
{
var item = Utilities.CreateFakeItem(null, renderParametersTemplateId, SitecoreContext.Database, "renderingParameters");
using (new SecurityDisabler())
{
using (new EventDisabler())
{
using (new VersionCountDisabler())
{
if (parameters != null)
{
item.Editing.BeginEdit();
item.RuntimeSettings.Temporary = true;
foreach (var key in parameters.AllKeys)
{
var fld = item.Fields[key];
if (fld != null)
{
fld.SetValue(parameters[key], true);
}
}
}
T obj = SitecoreContext.Cast<T>(item);
item.Editing.CancelEdit();
item.Delete(); //added for clean up
return obj;
}
}
}
}
/// <summary>
/// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the
/// model configuration.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="parameters"></param>
/// <returns></returns>
public virtual T GetRenderingParameters<T>(string parameters) where T : class
{
if (String.IsNullOrEmpty(parameters))
{
return default(T);
}
var nameValueCollection = WebUtil.ParseUrlParameters(parameters);
return GetRenderingParameters<T>(nameValueCollection);
}
/// <summary>
/// Converts rendering parameters to a concrete type. Use this method if you have defined the template ID on the
/// model configuration.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="parameters"></param>
/// <returns></returns>
public virtual T GetRenderingParameters<T>(NameValueCollection parameters) where T : class
{
if (parameters == null)
{
return default(T);
}
var config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration;
if (config == null)
{
SitecoreContext.GlassContext.Load(new OnDemandLoader<SitecoreTypeConfiguration>(typeof(T)));
}
config = SitecoreContext.GlassContext[typeof(T)] as SitecoreTypeConfiguration;
return GetRenderingParameters<T>(parameters, config.TemplateId);
}
public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field, TextWriter writer, object parameters = null, bool isEditable = false)
{
NameValueCollection attrs;
if (parameters is NameValueCollection)
{
attrs = parameters as NameValueCollection;
}
else
{
attrs = Utilities.GetPropertiesCollection(parameters, true);
}
if (IsInEditingMode && isEditable)
{
if (attrs != null)
{
attrs.Add("haschildren", "true");
return MakeEditable(field, null, model, attrs, _context, SitecoreContext.Database, writer);
}
return MakeEditable(field, null, model, "haschildren=true", _context, SitecoreContext.Database, writer);
}
else
{
return BeginRenderLink(GetCompiled(field).Invoke(model) as Link, attrs, string.Empty, writer);
}
}
/// <summary>
/// Checks it and attribute is part of the NameValueCollection and updates it with the
/// default if it isn't.
/// </summary>
/// <param name="collection">The collection of parameters</param>
/// <param name="name">The name of the attribute in the collection</param>
/// <param name="defaultValue">The default value for the attribute</param>
public static void AttributeCheck(SafeDictionary<string> collection, string name, string defaultValue)
{
if (collection[name].IsNullOrEmpty() && !defaultValue.IsNullOrEmpty())
collection[name] = defaultValue;
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <param name="model">The model containing the link</param>
/// <param name="field">An expression that points to the link</param>
/// <param name="attributes">A collection of parameters to added to the link</param>
/// <param name="isEditable">Indicate if the link should be editable in the page editor</param>
/// <param name="contents">Content to go in the link</param>
/// <returns>An "a" HTML element</returns>
public virtual string RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
NameValueCollection attrs;
if (attributes is NameValueCollection)
{
attrs = attributes as NameValueCollection;
}
else
{
attrs = Utilities.GetPropertiesCollection(attributes, true);
}
var sb = new StringBuilder();
var writer = new StringWriter(sb);
RenderingResult result;
if (IsInEditingMode && isEditable)
{
if (contents.HasValue())
{
attrs.Add("haschildren", "true");
attrs.Add("text",contents);
}
result = MakeEditable(
field,
null,
model,
attrs,
_context, SitecoreContext.Database, writer);
if (contents.IsNotNullOrEmpty())
{
sb.Append(contents);
}
}
else
{
result = BeginRenderLink(
GetCompiled(field).Invoke(model) as Link, attrs, contents, writer
);
}
result.Dispose();
writer.Flush();
writer.Close();
return sb.ToString();
}
/// <summary>
/// Indicates if the site is in editing mode
/// </summary>
/// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value>
public static bool IsInEditingMode
{
get
{
return Utilities.IsPageEditorEditing;
}
}
private string MakeEditable<T>(Expression<Func<T, object>> field, Expression<Func<T, string>> standardOutput, T target, object parameters)
{
StringBuilder sb = new StringBuilder();
var writer = new StringWriter(sb);
var result = MakeEditable(field, standardOutput, target, parameters, _context, SitecoreContext.Database, writer);
result.Dispose();
writer.Flush();
writer.Close();
return sb.ToString();
}
#region Statics
/// <summary>
/// Render HTML for a link
/// </summary>
/// <param name="link">The link to render</param>
/// <param name="attributes">Addtiional parameters to add. Do not include href or title</param>
/// <param name="contents">Content to go in the link instead of the standard text</param>
/// <returns>An "a" HTML element</returns>
[Obsolete("Use the SafeDictionary Overload")]
public static RenderingResult BeginRenderLink(Link link, NameValueCollection attributes, string contents, TextWriter writer)
{
return BeginRenderLink(link, attributes.ToSafeDictionary(), contents, writer);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <param name="link">The link to render</param>
/// <param name="attributes">Addtiional parameters to add. Do not include href or title</param>
/// <param name="contents">Content to go in the link instead of the standard text</param>
/// <returns>An "a" HTML element</returns>
public static RenderingResult BeginRenderLink(Link link, SafeDictionary<string> attributes, string contents,
TextWriter writer)
{
if (link == null) return new RenderingResult(writer, string.Empty, string.Empty);
if (attributes == null) attributes = new SafeDictionary<string>();
contents = contents == null ? link.Text ?? link.Title : contents;
var url = link.BuildUrl(attributes);
url = HttpUtility.HtmlEncode(url);
//we decode and then encode the HTML to avoid a double encoding of HTML characters.
//some versions of Sitecore save '&' as '&' and others as '&'.
contents = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(contents));
var title = HttpUtility.HtmlEncode(HttpUtility.HtmlDecode(link.Title));
AttributeCheck(attributes, "class", link.Class);
AttributeCheck(attributes, "target", link.Target);
AttributeCheck(attributes, "title", title);
string firstPart = LinkTagFormat.Formatted(url, Utilities.ConvertAttributes(attributes, QuotationMark), contents, QuotationMark);
string lastPart = "</a>";
return new RenderingResult(writer, firstPart, lastPart);
}
/// <summary>
/// Makes the editable.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="field">The field.</param>
/// <param name="standardOutput">The standard output.</param>
/// <param name="model">The model.</param>
/// <param name="parameters">The parameters.</param>
/// <returns>System.String.</returns>
/// <exception cref="Glass.Mapper.MapperException">
/// To many parameters in linq expression {0}.Formatted(field.Body)
/// or
/// Expression doesn't evaluate to a member {0}.Formatted(field.Body)
/// or
/// Page editting error. Could not find property {0} on type {1}.Formatted(memberExpression.Member.Name, config.Type.FullName)
/// or
/// Page editting error. Could not find data handler for property {2} {0}.{1}.Formatted(
/// prop.DeclaringType, prop.Name, prop.MemberType)
/// </exception>
/// <exception cref="System.NullReferenceException">Context cannot be null</exception>
private RenderingResult MakeEditable<T>(
Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput,
T model,
object parameters,
Context context,
Database database,
TextWriter writer)
{
string firstPart = string.Empty;
string lastPart = string.Empty;
try
{
if (field == null) throw new NullReferenceException("No field set");
if (model == null) throw new NullReferenceException("No model set");
SafeDictionary<string> dictionary = ProcessParameters(parameters);
if (IsInEditingMode && !dictionary.ContainsKey(DisableEditable))
{
dictionary.Remove(DisableEditable);
MemberExpression memberExpression;
var finalTarget = Mapper.Utilities.GetTargetObjectOfLamba(field, model, out memberExpression);
var config = Mapper.Utilities.GetTypeConfig<T, SitecoreTypeConfiguration>(field, context, model);
var dataHandler = Mapper.Utilities.GetGlassProperty<T, SitecoreTypeConfiguration>(field, context, model);
var scClass = config.ResolveItem(finalTarget, database);
using (new ContextItemSwitcher(scClass))
{
RenderFieldArgs renderFieldArgs = new RenderFieldArgs();
renderFieldArgs.Item = scClass;
var fieldConfig = (SitecoreFieldConfiguration)dataHandler;
if (fieldConfig.FieldId != (ID)null && fieldConfig.FieldId != ID.Null)
{
renderFieldArgs.FieldName = fieldConfig.FieldId.ToString();
}
else
{
renderFieldArgs.FieldName = fieldConfig.FieldName;
}
renderFieldArgs.Parameters = dictionary;
renderFieldArgs.DisableWebEdit = false;
CorePipeline.Run("renderField", (PipelineArgs)renderFieldArgs);
firstPart = renderFieldArgs.Result.FirstPart;
lastPart = renderFieldArgs.Result.LastPart;
}
}
else
{
firstPart = NormalModeOutput(field, standardOutput, model, dictionary);
}
}
catch (Exception ex)
{
firstPart = "<p>{0}</p><pre>{1}</pre>".Formatted(ex.Message, ex.StackTrace);
Sitecore.Diagnostics.Log.Error("Failed to render field", ex, typeof(IGlassHtml));
}
return new RenderingResult(writer, firstPart, lastPart);
}
protected virtual string NormalModeOutput<T>(
Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput,
T model,
SafeDictionary<string> dictionary )
{
string firstPart;
if (standardOutput != null)
{
firstPart = GetCompiled(standardOutput)(model).ToString();
}
else
{
object target = (GetCompiled(field)(model) ?? string.Empty);
if (ImageType.IsInstanceOfType(target))
{
var image = target as Image;
firstPart = RenderImage(image, dictionary);
}
else if (LinkType.IsInstanceOfType(target))
{
var link = target as Link;
var sb = new StringBuilder();
var linkWriter = new StringWriter(sb);
var result = BeginRenderLink(link, dictionary, null, linkWriter);
result.Dispose();
linkWriter.Flush();
linkWriter.Close();
firstPart = sb.ToString();
}
else
{
firstPart = target.ToString();
}
}
return firstPart;
}
protected SafeDictionary<string> ProcessParameters(object parameters)
{
string parametersStringTemp = string.Empty;
SafeDictionary<string> dictionary = new SafeDictionary<string>();
if (parameters == null)
{
parametersStringTemp = string.Empty;
}
else if (parameters is string)
{
parametersStringTemp = parameters as string;
dictionary = WebUtil.ParseQueryString(parametersStringTemp ?? string.Empty);
}
else if (parameters is NameValueCollection)
{
var collection = (NameValueCollection)parameters;
foreach (var key in collection.AllKeys)
{
dictionary.Add(key, collection[key]);
}
}
else
{
var collection = Utilities.GetPropertiesCollection(parameters, true);
foreach (var key in collection.AllKeys)
{
dictionary.Add(key, collection[key]);
}
}
return dictionary;
}
#endregion
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param>
/// <returns></returns>
public virtual string RenderImage<T>(T model,
Expression<Func<T, object>> field,
object parameters = null,
bool isEditable = false,
bool outputHeightWidth = false)
{
var attrs = Utilities.GetPropertiesCollection(parameters, true).ToSafeDictionary();
if (IsInEditingMode && isEditable)
{
var url = new UrlString();
foreach (var pair in attrs)
{
url.Parameters.Add(pair.Key, pair.Value);
}
if (!outputHeightWidth)
{
url.Parameters.Add("width", "-1");
url.Parameters.Add("height", "-1");
}
return Editable(model, field, url.Query);
}
else
{
return RenderImage(GetCompiled(field).Invoke(model) as Image, parameters == null ? null : attrs, outputHeightWidth);
}
}
/// <summary>
/// Renders HTML for an image
/// </summary>
/// <param name="image">The image to render</param>
/// <param name="attributes">Additional parameters to add. Do not include alt or src</param>
/// <param name="outputHeightWidth">Indicates if the height and width attributes should be output when rendering the image</param>
/// <returns>An img HTML element</returns>
public virtual string RenderImage(
Image image,
SafeDictionary<string> attributes,
bool outputHeightWidth = false
)
{
if (image == null)
{
return string.Empty;
}
if (attributes == null)
{
attributes = new SafeDictionary<string>();
}
var origionalKeys = attributes.Keys.ToList();
//should there be some warning about these removals?
AttributeCheck(attributes, ImageParameterKeys.CLASS, image.Class);
if (!attributes.ContainsKey(ImageParameterKeys.ALT))
{
attributes[ImageParameterKeys.ALT] = image.Alt;
}
AttributeCheck(attributes, ImageParameterKeys.BORDER, image.Border);
if (image.HSpace > 0)
AttributeCheck(attributes, ImageParameterKeys.HSPACE, image.HSpace.ToString(CultureInfo.InvariantCulture));
if (image.VSpace > 0)
AttributeCheck(attributes, ImageParameterKeys.VSPACE, image.VSpace.ToString(CultureInfo.InvariantCulture));
if (image.Width > 0)
AttributeCheck(attributes, ImageParameterKeys.WIDTHHTML, image.Width.ToString(CultureInfo.InvariantCulture));
if (image.Height > 0)
AttributeCheck(attributes, ImageParameterKeys.HEIGHTHTML, image.Height.ToString(CultureInfo.InvariantCulture));
var urlParams = new SafeDictionary<string>();
var htmlParams = new SafeDictionary<string>();
/*
* ME - This method is used to render images rather than going back to the fieldrender
* because it stops another call having to be passed to Sitecore.
*/
if (image == null || image.Src.IsNullOrWhiteSpace()) return String.Empty;
if (attributes == null) attributes = new SafeDictionary<string>();
Action<string> remove = key => attributes.Remove(key);
Action<string> url = key =>
{
urlParams.Add(key, attributes[key]);
remove(key);
};
Action<string> html = key =>
{
htmlParams.Add(key, attributes[key]);
remove(key);
};
Action<string> both = key =>
{
htmlParams.Add(key, attributes[key]);
urlParams.Add(key, attributes[key]);
remove(key);
};
var keys = attributes.Keys.ToList();
foreach (var key in keys)
{
//if we have not config we just add it to both
if (SitecoreContext.Config == null)
{
both(key);
}
else
{
bool found = false;
if (SitecoreContext.Config.ImageAttributes.Contains(key))
{
html(key);
found = true;
}
if (SitecoreContext.Config.ImageQueryString.Contains(key))
{
url(key);
found = true;
}
if (!found)
{
html(key);
}
}
}
//copy width and height across to url
if (!urlParams.ContainsKey(ImageParameterKeys.WIDTH) && !urlParams.ContainsKey(ImageParameterKeys.HEIGHT))
{
if (origionalKeys.Contains(ImageParameterKeys.WIDTHHTML))
{
urlParams[ImageParameterKeys.WIDTH] = htmlParams[ImageParameterKeys.WIDTHHTML];
}
if (origionalKeys.Contains(ImageParameterKeys.HEIGHTHTML))
{
urlParams[ImageParameterKeys.HEIGHT] = htmlParams[ImageParameterKeys.HEIGHTHTML];
}
}
if (!urlParams.ContainsKey(ImageParameterKeys.LANGUAGE) && image.Language != null)
{
urlParams[ImageParameterKeys.LANGUAGE] = image.Language.Name;
}
//calculate size
var finalSize = Utilities.ResizeImage(
image.Width,
image.Height,
urlParams[ImageParameterKeys.SCALE].ToFloat(),
urlParams[ImageParameterKeys.WIDTH].ToInt(),
urlParams[ImageParameterKeys.HEIGHT].ToInt(),
urlParams[ImageParameterKeys.MAX_WIDTH].ToInt(),
urlParams[ImageParameterKeys.MAX_HEIGHT].ToInt());
if (finalSize.Height > 0)
{
urlParams[ImageParameterKeys.HEIGHT] = finalSize.Height.ToString();
}
if (finalSize.Width > 0)
{
urlParams[ImageParameterKeys.WIDTH] = finalSize.Width.ToString();
}
Action<string, string> originalAttributeClean = (exists, missing) =>
{
if (origionalKeys.Contains(exists) && !origionalKeys.Contains(missing))
{
urlParams.Remove(missing);
htmlParams.Remove(missing);
}
};
//we do some smart clean up
originalAttributeClean(ImageParameterKeys.WIDTHHTML, ImageParameterKeys.HEIGHTHTML);
originalAttributeClean(ImageParameterKeys.HEIGHTHTML, ImageParameterKeys.WIDTHHTML);
if (!outputHeightWidth)
{
htmlParams.Remove(ImageParameterKeys.WIDTHHTML);
htmlParams.Remove(ImageParameterKeys.HEIGHTHTML);
}
foreach (var key in htmlParams.Keys.ToArray())
{
htmlParams[key] = HttpUtility.HtmlAttributeEncode(htmlParams[key]);
}
var builder = new UrlBuilder(image.Src);
foreach (var key in urlParams.Keys)
{
builder.AddToQueryString(key, urlParams[key]);
}
string mediaUrl = builder.ToString();
#if (SC81 || SC80 || SC75 || SC82)
mediaUrl = ProtectMediaUrl(mediaUrl);
#endif
mediaUrl = HttpUtility.HtmlEncode(mediaUrl);
return ImageTagFormat.Formatted(mediaUrl, Utilities.ConvertAttributes(htmlParams, QuotationMark), QuotationMark);
}
#if (SC81 || SC80 || SC75 || SC82)
public virtual string ProtectMediaUrl(string url)
{
return Sitecore.Resources.Media.HashingUtils.ProtectAssetUrl(url);
}
#endif
}
}
| |
using EZOper.TechTester.DModels.Entities.WorksBigsail.Honor3Supervise;
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
namespace EZOper.TechTester.DataAccess.EZMssql.Works.Bigsail
{
public partial class Honor3SuperviseEntities : DbContext
{
public Honor3SuperviseEntities()
: base("name=WorksBigsailHonor3SuperviseEntities")
{
}
public virtual DbSet<BookEditions> BookEditions { get; set; }
public virtual DbSet<CatalogDimensionRelation> CatalogDimensionRelation { get; set; }
public virtual DbSet<CommandInfo> CommandInfo { get; set; }
public virtual DbSet<DatabaseDistribution> DatabaseDistribution { get; set; }
public virtual DbSet<EducationBureau_ExperimentSettings> EducationBureau_ExperimentSettings { get; set; }
public virtual DbSet<EducationBureauFilesControl> EducationBureauFilesControl { get; set; }
public virtual DbSet<EducationBureauRegistry> EducationBureauRegistry { get; set; }
public virtual DbSet<EducationBureauUsers> EducationBureauUsers { get; set; }
public virtual DbSet<EducationLockUnlockOperLog> EducationLockUnlockOperLog { get; set; }
public virtual DbSet<EducationUsersSchoolRange> EducationUsersSchoolRange { get; set; }
public virtual DbSet<EquipmentCatalogs> EquipmentCatalogs { get; set; }
public virtual DbSet<EquipmentItems> EquipmentItems { get; set; }
public virtual DbSet<EquipmentReferenceUnitPrice> EquipmentReferenceUnitPrice { get; set; }
public virtual DbSet<EquipmentStandardDimensions> EquipmentStandardDimensions { get; set; }
public virtual DbSet<EquipmentStandardRequirements> EquipmentStandardRequirements { get; set; }
public virtual DbSet<ExperimentItems> ExperimentItems { get; set; }
public virtual DbSet<GroupingExperimentEquipment> GroupingExperimentEquipment { get; set; }
public virtual DbSet<OperationLog> OperationLog { get; set; }
public virtual DbSet<ReferenceUnitPriceProject> ReferenceUnitPriceProject { get; set; }
public virtual DbSet<SchoolCatalogInit> SchoolCatalogInit { get; set; }
public virtual DbSet<SchoolNotices> SchoolNotices { get; set; }
public virtual DbSet<SchoolOrderInfo> SchoolOrderInfo { get; set; }
public virtual DbSet<SchoolRegistry> SchoolRegistry { get; set; }
public virtual DbSet<SchoolRenewFee> SchoolRenewFee { get; set; }
public virtual DbSet<SchoolUsers> SchoolUsers { get; set; }
public virtual DbSet<SchoolYearFilesRegistry> SchoolYearFilesRegistry { get; set; }
public virtual DbSet<StandardSchoolClassifications> StandardSchoolClassifications { get; set; }
public virtual DbSet<StandardVersions> StandardVersions { get; set; }
public virtual DbSet<SysSettingUser> SysSettingUser { get; set; }
public virtual DbSet<SchoolUserOperInfo> SchoolUserOperInfo { get; set; }
public virtual DbSet<VW_BookEdition> VW_BookEdition { get; set; }
public virtual DbSet<VW_Category> VW_Category { get; set; }
public virtual DbSet<VW_Experiment> VW_Experiment { get; set; }
public virtual DbSet<VW_ExperimentCategory> VW_ExperimentCategory { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<BookEditions>()
.HasMany(e => e.EducationBureau_ExperimentSettings)
.WithRequired(e => e.BookEditions)
.HasForeignKey(e => e.BookEditionId);
modelBuilder.Entity<BookEditions>()
.HasMany(e => e.ExperimentItems)
.WithRequired(e => e.BookEditions)
.HasForeignKey(e => e.EditionId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<CommandInfo>()
.Property(e => e.CommandType)
.IsUnicode(false);
modelBuilder.Entity<CommandInfo>()
.Property(e => e.CommandParams)
.IsUnicode(false);
modelBuilder.Entity<DatabaseDistribution>()
.Property(e => e.Password)
.IsUnicode(false);
modelBuilder.Entity<EducationBureauFilesControl>()
.HasMany(e => e.EducationBureau_ExperimentSettings)
.WithRequired(e => e.EducationBureauFilesControl)
.HasForeignKey(e => e.EducationFileID);
modelBuilder.Entity<EducationBureauFilesControl>()
.HasMany(e => e.SchoolYearFilesRegistry)
.WithRequired(e => e.EducationBureauFilesControl)
.HasForeignKey(e => e.FilesControlID);
modelBuilder.Entity<EducationBureauRegistry>()
.Property(e => e.RegionCode)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<EducationBureauRegistry>()
.HasOptional(e => e.DatabaseDistribution)
.WithRequired(e => e.EducationBureauRegistry)
.WillCascadeOnDelete();
modelBuilder.Entity<EducationBureauRegistry>()
.HasMany(e => e.EducationBureauFilesControl)
.WithRequired(e => e.EducationBureauRegistry)
.HasForeignKey(e => e.EducationBureauID);
modelBuilder.Entity<EducationBureauRegistry>()
.HasMany(e => e.EducationBureauUsers)
.WithRequired(e => e.EducationBureauRegistry)
.HasForeignKey(e => e.EducationBureauID);
modelBuilder.Entity<EducationBureauRegistry>()
.HasMany(e => e.SchoolRegistry)
.WithRequired(e => e.EducationBureauRegistry)
.HasForeignKey(e => e.EducationBureauID);
modelBuilder.Entity<EducationBureauUsers>()
.HasOptional(e => e.EducationUsersSchoolRange)
.WithRequired(e => e.EducationBureauUsers)
.WillCascadeOnDelete();
modelBuilder.Entity<EquipmentCatalogs>()
.HasMany(e => e.CatalogDimensionRelation)
.WithRequired(e => e.EquipmentCatalogs)
.HasForeignKey(e => e.CatalogId);
modelBuilder.Entity<EquipmentCatalogs>()
.HasMany(e => e.EducationBureau_ExperimentSettings)
.WithRequired(e => e.EquipmentCatalogs)
.HasForeignKey(e => e.CatalogID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EquipmentCatalogs>()
.HasMany(e => e.EquipmentItems)
.WithRequired(e => e.EquipmentCatalogs)
.HasForeignKey(e => e.EquipmentCatalogID);
modelBuilder.Entity<EquipmentCatalogs>()
.HasMany(e => e.ExperimentItems)
.WithRequired(e => e.EquipmentCatalogs)
.HasForeignKey(e => e.CatalogID);
modelBuilder.Entity<EquipmentCatalogs>()
.HasMany(e => e.SchoolCatalogInit)
.WithRequired(e => e.EquipmentCatalogs)
.HasForeignKey(e => e.CatalogID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EquipmentItems>()
.Property(e => e.ReferenceUnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<EquipmentItems>()
.HasMany(e => e.EquipmentStandardRequirements)
.WithRequired(e => e.EquipmentItems)
.HasForeignKey(e => e.EquipmentItemID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EquipmentItems>()
.HasOptional(e => e.GroupingExperimentEquipment)
.WithRequired(e => e.EquipmentItems)
.WillCascadeOnDelete();
modelBuilder.Entity<EquipmentReferenceUnitPrice>()
.Property(e => e.ReferenceUnitPrice)
.HasPrecision(19, 4);
modelBuilder.Entity<EquipmentStandardDimensions>()
.HasMany(e => e.CatalogDimensionRelation)
.WithRequired(e => e.EquipmentStandardDimensions)
.HasForeignKey(e => e.DimensionId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<EquipmentStandardDimensions>()
.HasMany(e => e.EquipmentStandardRequirements)
.WithRequired(e => e.EquipmentStandardDimensions)
.HasForeignKey(e => e.DimensionID);
modelBuilder.Entity<ReferenceUnitPriceProject>()
.Property(e => e.FromRegionCode)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<ReferenceUnitPriceProject>()
.HasMany(e => e.EducationBureauFilesControl)
.WithRequired(e => e.ReferenceUnitPriceProject)
.WillCascadeOnDelete(false);
modelBuilder.Entity<ReferenceUnitPriceProject>()
.HasMany(e => e.EquipmentReferenceUnitPrice)
.WithRequired(e => e.ReferenceUnitPriceProject)
.HasForeignKey(e => e.ProjectID);
modelBuilder.Entity<SchoolNotices>()
.Property(e => e.NoticeTitle)
.IsUnicode(false);
modelBuilder.Entity<SchoolNotices>()
.Property(e => e.NoticeContent)
.IsUnicode(false);
modelBuilder.Entity<SchoolNotices>()
.Property(e => e.Remark)
.IsUnicode(false);
modelBuilder.Entity<SchoolOrderInfo>()
.Property(e => e.TotalMoney)
.HasPrecision(19, 4);
modelBuilder.Entity<SchoolOrderInfo>()
.Property(e => e.Remark)
.IsUnicode(false);
modelBuilder.Entity<SchoolRegistry>()
.HasMany(e => e.SchoolCatalogInit)
.WithRequired(e => e.SchoolRegistry)
.HasForeignKey(e => e.SchoolID);
modelBuilder.Entity<SchoolRegistry>()
.HasMany(e => e.SchoolYearFilesRegistry)
.WithRequired(e => e.SchoolRegistry)
.WillCascadeOnDelete(false);
modelBuilder.Entity<SchoolYearFilesRegistry>()
.Property(e => e.ContainedGrades)
.IsUnicode(false);
modelBuilder.Entity<SchoolYearFilesRegistry>()
.Property(e => e.ApproveQuota)
.HasPrecision(19, 4);
modelBuilder.Entity<SchoolYearFilesRegistry>()
.Property(e => e.MaxQuota)
.HasPrecision(19, 4);
modelBuilder.Entity<StandardSchoolClassifications>()
.HasMany(e => e.EquipmentCatalogs)
.WithRequired(e => e.StandardSchoolClassifications)
.HasForeignKey(e => e.SchoolClassificationID);
modelBuilder.Entity<StandardSchoolClassifications>()
.HasMany(e => e.EquipmentStandardDimensions)
.WithRequired(e => e.StandardSchoolClassifications)
.HasForeignKey(e => e.SchoolClassificationID);
modelBuilder.Entity<StandardSchoolClassifications>()
.HasMany(e => e.OperationLog)
.WithRequired(e => e.StandardSchoolClassifications)
.HasForeignKey(e => e.SchoolClassificationID);
modelBuilder.Entity<StandardVersions>()
.HasMany(e => e.EducationBureauFilesControl)
.WithRequired(e => e.StandardVersions)
.HasForeignKey(e => e.StandardVersionID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<StandardVersions>()
.HasMany(e => e.StandardSchoolClassifications)
.WithRequired(e => e.StandardVersions)
.HasForeignKey(e => e.VersionID);
modelBuilder.Entity<VW_Category>()
.Property(e => e.RegionCode)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<VW_Experiment>()
.Property(e => e.RegionCode)
.IsFixedLength()
.IsUnicode(false);
modelBuilder.Entity<VW_ExperimentCategory>()
.Property(e => e.RegionCode)
.IsFixedLength()
.IsUnicode(false);
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.DeviceModels.Chipset.LPC3180
{
using System;
using System.Runtime.CompilerServices;
using Microsoft.Zelig.Runtime;
[MemoryMappedPeripheral(Base=0x31000000U,Length=0x00000200U)]
public class GPDMA
{
[MemoryMappedPeripheral(Base=0x0000U,Length=0x0020U)]
public class Channel
{
[BitFieldPeripheral(PhysicalType=typeof(uint))]
public struct LLI_bitfield
{
[BitFieldRegister(Position=0)] public bool UseM1; // AHB master select for loading the next LLI:
//
// 0 - AHB Master 0.
// 1 - AHB Master 1.
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(uint))]
public struct Control_bitfield
{
public enum Width
{
Byte = 0, // 000 - Byte (8-bit)
Halfword = 1, // 001 - Halfword (16-bit)
Word = 2, // 010 - Word (32-bit)
// 011 to 111 - Reserved
}
public enum BurstSize
{
Len1 = 0, // 000 - 1
Len4 = 1, // 001 - 4
Len8 = 2, // 010 - 8
Len16 = 3, // 011 - 16
Len32 = 4, // 100 - 32
Len64 = 5, // 101 - 64
Len128 = 6, // 110 - 128
Len256 = 7, // 111 - 256
}
[BitFieldRegister(Position=31 )] public bool InterruptEnable; // Terminal count interrupt enable bit.
//
// 0 - the terminal count interrupt is disabled.
// 1 - the terminal count interrupt is enabled.
//
//
[BitFieldRegister(Position=30 )] public bool Cacheable; // Indicates that the access is cacheable or not cacheable:
//
// 0 - access is not cacheable.
// 1 - access is cacheable.
//
//
[BitFieldRegister(Position=29 )] public bool Bufferable; // Indicates that the access is bufferable or not bufferable:
//
// 0 - access is not bufferable.
// 1 - access is bufferable.
//
//
[BitFieldRegister(Position=28 )] public bool PrivilegedMode; // Indicates that the access is in user mode or privileged mode:
//
// 0 - access is in user mode.
// 1 - access is in privileged mode.
//
//
[BitFieldRegister(Position=27 )] public bool DestinationIncrement; // Destination increment:
//
// 0 - the destination address is not incremented after each transfer.
// 1 - the destination address is incremented after each transfer.
//
//
[BitFieldRegister(Position=26 )] public bool SourceIncrement; // Source increment:
//
// 0 - the source address is not incremented after each transfer.
// 1 - the source address is incremented after each transfer.
//
//
[BitFieldRegister(Position=25 )] public bool DestinationUsesM1; // Destination AHB master select:
//
// 0 - AHB Master 0 selected for destination transfer.
// 1 - AHB Master 1 selected for destination transfer.
//
//
[BitFieldRegister(Position=24 )] public bool SourceUsesM1; // Source AHB master select:
//
// 0 - AHB Master 0 selected for source transfer.
// 1 - AHB Master 1 selected for source transfer.
//
//
[BitFieldRegister(Position=21,Size=3)] public Width DWidth; // Destination transfer width.
//
// Transfers wider than the AHB master bus width are illegal.
// The source and destination widths can be different from each other.
// The hardware automatically packs and unpacks the data as required.
//
//
[BitFieldRegister(Position=18,Size=3)] public Width SWidth; // Source transfer width.
//
// Transfers wider than the AHB master bus width are illegal.
// The source and destination widths can be different from each other.
// The hardware automatically packs and unpacks the data as required.
//
//
[BitFieldRegister(Position=15,Size=3)] public BurstSize DBSize; // Destination burst size.
//
// Indicates the number of transfers that make up a destination burst request.
// This value must be set to the burst size of the destination peripheral, or if the destination is memory, to the memory boundary size.
// The burst size is the amount of data that is transferred when the DMACBREQ signal goes active in the destination peripheral.
//
//
[BitFieldRegister(Position=12,Size=3)] public BurstSize SBSize; // Source burst size.
//
// Indicates the number of transfers that make up a source burst.
// This value must be set to the burst size of the source peripheral, or if the source is memory, to the memory boundary size.
// The burst size is the amount of data that is transferred when the DMACBREQ signal goes active in the source peripheral.
//
//
[BitFieldRegister(Position= 0,Size=12)] public uint TransferSize; // Transfer size.
//
// A write to this field sets the size of the transfer when the DMA Controller is the flow controller.
// The transfer size value must be set before the channel is enabled.
// Transfer size is updated as data transfers are completed.
// A read from this field indicates the number of transfers completed on the destination bus.
// Reading the register when the channel is active does not give useful information because by the time
// that the software has processed the value read, the channel might have progressed.
// It is intended to be used only when a channel is enabled and then disabled.
// The transfer size value is not used if the DMA Controller is not the flow controller.
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(uint))]
public struct Config_bitfield
{
public enum FlowControl
{
M2M_D = 0, // 000 Memory to memory DMA
M2P_D = 1, // 001 Memory to peripheral DMA
P2M_D = 2, // 010 Peripheral to memory DMA
P2P_D = 3, // 011 Source peripheral to destination peripheral DMA
P2P_DP = 4, // 100 Source peripheral to destination peripheral Destination peripheral
M2P_P = 5, // 101 Memory to peripheral Peripheral
P2M_P = 6, // 110 Peripheral to memory Peripheral
P2P_SP = 7, // 111 Source peripheral to destination peripheral Source peripheral
}
public enum Peripheral
{
SPI1 = 11, // SPI1 receive and transmit
Uart7__Rx = 10, // HS-Uart7 receive
Uart7__Tx = 9, // HS-Uart7 transmit
Uart2__Rx = 8, // HS-Uart2 receive
Uart2__Tx = 7, // HS-Uart2 transmit
Uart1__Rx = 6, // HS-Uart1 receive
Uart1__Tx = 5, // HS-Uart1 transmit
SD_Card = 4, // SD Card interface receive and transmit
SPI2 = 3, // SPI2 receive and transmit
NAND_Flash = 1, // NAND Flash (same as channel 12)
}
[BitFieldRegister(Position=18 )] public bool H; // Halt:
//
// 0 = enable DMA requests.
// 1 = ignore further source DMA requests.
//
// The contents of the channel FIFO are drained.
// This value can be used with the Active and Channel Enable bits to cleanly disable a DMA channel.
//
//
[BitFieldRegister(Position=17 )] public bool A; // Active:
//
// 0 = there is no data in the FIFO of the channel.
// 1 = the channel FIFO has data.
//
// This value can be used with the Halt and Channel Enable bits to cleanly disable a DMA channel.
// This is a read-only bit.
//
//
[BitFieldRegister(Position=16 )] public bool L; // Lock.
//
// When set, this bit enables locked transfers.
//
//
[BitFieldRegister(Position=15 )] public bool ITC; // Terminal count interrupt mask.
//
// When cleared, this bit masks out the terminal count interrupt of the relevant channel.
//
//
[BitFieldRegister(Position=14 )] public bool IE; // Interrupt error mask.
//
// When cleared, this bit masks out the error interrupt of the relevant channel.
//
//
[BitFieldRegister(Position=11,Size=3)] public FlowControl FlowCntrl; // Flow control and transfer type.
//
// This value indicates the flow controller and transfer type.
// The flow controller can be the DMA Controller, the source peripheral, or the destination peripheral.
// The transfer type can be memory-to-memory, memory-to-peripheral, peripheral-to-memory, or peripheral-to-peripheral.
//
//
[BitFieldRegister(Position= 6,Size=5)] public Peripheral DestPeripheral; // Source peripheral.
//
// This value selects the DMA source request peripheral. This field is ignored if the source of the transfer is from memory.
//
//
[BitFieldRegister(Position= 1,Size=5)] public Peripheral SrcPeripheral; // Source peripheral.
//
// This value selects the DMA source request peripheral. This field is ignored if the source of the transfer is from memory.
//
//
[BitFieldRegister(Position= 0 )] public bool E; // Channel enable.
//
// Reading this bit indicates whether a channel is currently enabled or disabled:
//
// 0 = channel disabled.
// 1 = channel enabled.
//
// The Channel Enable bit status can also be found by reading the DMACEnbldChns Register.
// A channel is enabled by setting this bit.
// A channel can be disabled by clearing the Enable bit.
// This causes the current AHB transfer (if one is in progress) to complete and the channel is then disabled.
// Any data in the FIFO of the relevant channel is lost.
// Restarting the channel by setting the Channel Enable bit has unpredictable effects, the channel must be fully re-initialized.
// The channel is also disabled, and Channel Enable bit cleared, when the last LLI is reached, the DMA transfer is completed, or if a channel error is encountered.
// If a channel must be disabled without losing data in the FIFO, the Halt bit must be set so that further DMA requests are ignored.
// The Active bit must then be polled until it reaches 0, indicating that there is no data left in the FIFO.
// Finally, the Channel Enable bit can be cleared.
//
}
//--//
[Register(Offset=0x00U)] public uint SrcAddr; // Source Address Register 0 R/W
[Register(Offset=0x04U)] public uint DestAddr; // Destination Address Register 0 R/W
[Register(Offset=0x08U)] public LLI_bitfield LLI; // Linked List Item Register 0 R/W
[Register(Offset=0x0CU)] public Control_bitfield Control; // Control Register 0 R/W
[Register(Offset=0x10U)] public Config_bitfield Config; // Configuration Register 0[1] R/W
//
// Helper Methods
//
[Inline]
public void WaitForCompletion()
{
while(this.IsActive)
{
}
}
[Inline]
public unsafe void CopyMemory( uint* src ,
uint* dst ,
uint numOfWords ,
uint burstSize ,
bool fSrcIncrement ,
bool fDstIncrement ,
bool fUseSameMaster )
{
#if USE_CPU
Memory.CopyNonOverlapping( new UIntPtr( src ), new UIntPtr( &src[numOfWords] ), new UIntPtr( dst ) );
#else
WaitForCompletion();
//--//
var ctrl = new Control_bitfield();
ctrl.Cacheable = false;
ctrl.Bufferable = false;
ctrl.PrivilegedMode = true;
ctrl.SWidth = Control_bitfield.Width.Word;
ctrl.DWidth = Control_bitfield.Width.Word;
if(fUseSameMaster)
{
ctrl.SourceUsesM1 = false;
ctrl.DestinationUsesM1 = false;
}
else
{
ctrl.SourceUsesM1 = false;
ctrl.DestinationUsesM1 = true;
}
ctrl.SourceIncrement = fSrcIncrement;
ctrl.DestinationIncrement = fDstIncrement;
switch(burstSize)
{
case 1:
ctrl.SBSize = Control_bitfield.BurstSize.Len1;
ctrl.DBSize = Control_bitfield.BurstSize.Len1;
break;
case 4:
ctrl.SBSize = Control_bitfield.BurstSize.Len4;
ctrl.DBSize = Control_bitfield.BurstSize.Len4;
break;
case 8:
ctrl.SBSize = Control_bitfield.BurstSize.Len8;
ctrl.DBSize = Control_bitfield.BurstSize.Len8;
break;
case 16:
ctrl.SBSize = Control_bitfield.BurstSize.Len16;
ctrl.DBSize = Control_bitfield.BurstSize.Len16;
break;
case 32:
ctrl.SBSize = Control_bitfield.BurstSize.Len32;
ctrl.DBSize = Control_bitfield.BurstSize.Len32;
break;
case 64:
ctrl.SBSize = Control_bitfield.BurstSize.Len64;
ctrl.DBSize = Control_bitfield.BurstSize.Len64;
break;
case 128:
ctrl.SBSize = Control_bitfield.BurstSize.Len128;
ctrl.DBSize = Control_bitfield.BurstSize.Len128;
break;
case 256:
ctrl.SBSize = Control_bitfield.BurstSize.Len256;
ctrl.DBSize = Control_bitfield.BurstSize.Len256;
break;
}
ctrl.TransferSize = numOfWords;
//--//
var config = new Config_bitfield();
config.L = true;
config.FlowCntrl = Config_bitfield.FlowControl.M2M_D;
config.E = true;
//--//
this.SrcAddr = (uint)src;
this.DestAddr = (uint)dst;
this.LLI = new LLI_bitfield();
this.Control = ctrl;
this.Config = config;
#endif
}
//
// Access Methods
//
public bool IsActive
{
[Inline]
get
{
return this.Config.E;
}
}
//
// Debug Methods
//
}
//--//
[BitFieldPeripheral(PhysicalType=typeof(uint))]
public struct DMACConfig_bitfield
{
[BitFieldRegister(Position=2)] public bool M1_BigEndian; // AHB Master 1 endianness configuration:
//
// 0 = little-endian mode (default).
// 1 = big-endian mode.
//
//
[BitFieldRegister(Position=1)] public bool M0_BigEndian; // AHB Master 0 endianness configuration:
//
// 0 = little-endian mode (default).
// 1 = big-endian mode.
//
//
[BitFieldRegister(Position=0)] public bool E; // DMA Controller enable:
//
// 0 = disabled (default). Disabling the DMA Controller reduces power consumption.
// 1 = enabled.
//
}
//--//
[Register(Offset=0x00U)] public uint DMACIntStat; // DMA Interrupt Status Register 0 RO
[Register(Offset=0x04U)] public uint DMACIntTCStat; // DMA Interrupt Terminal Count Request Status Register 0 RO
[Register(Offset=0x08U)] public uint DMACIntTCClear; // DMA Interrupt Terminal Count Request Clear Register - WO
[Register(Offset=0x0CU)] public uint DMACIntErrStat; // DMA Interrupt Error Status Register 0 RO
[Register(Offset=0x10U)] public uint DMACIntErrClr; // DMA Interrupt Error Clear Register - WO
[Register(Offset=0x14U)] public uint DMACRawIntTCStat; // DMA Raw Interrupt Terminal Count Status Register 0 RO
[Register(Offset=0x18U)] public uint DMACRawIntErrStat; // DMA Raw Error Interrupt Status Register 0 RO
[Register(Offset=0x1CU)] public uint DMACEnbldChns; // DMA Enabled Channel Register 0 RO
[Register(Offset=0x20U)] public uint DMACSoftBReq; // DMA Software Burst Request Register 0 R/W
[Register(Offset=0x24U)] public uint DMACSoftSReq; // DMA Software Single Request Register 0 R/W
[Register(Offset=0x28U)] public uint DMACSoftLBReq; // DMA Software Last Burst Request Register 0 R/W
[Register(Offset=0x2CU)] public uint DMACSoftLSReq; // DMA Software Last Single Request Register 0 R/W
[Register(Offset=0x30U)] public DMACConfig_bitfield DMACConfig; // DMA Configuration Register 0 R/W
[Register(Offset=0x34U)] public uint DMACSync; // DMA Synchronization Register 0 R/W
[Register(Offset=0x00000100U,Instances=8)] public Channel[] Channels;
//--//
//
// Helper Methods
//
[Inline]
public void Enable()
{
SystemControl.Instance.DMACLK_CTRL.Enable = true;
this.DMACConfig.E = true;
}
[Inline]
public void Disable()
{
this.DMACConfig.E = false;
SystemControl.Instance.DMACLK_CTRL.Enable = false;
}
//
// Access Methods
//
public static extern GPDMA Instance
{
[SingletonFactory()]
[MethodImpl( MethodImplOptions.InternalCall )]
get;
}
}
}
| |
#region Copyright notice and license
// Copyright 2015, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Runtime.InteropServices;
using System.Text;
using Grpc.Core.Utils;
namespace Grpc.Core
{
/// <summary>
/// Provides access to read and write metadata values to be exchanged during a call.
/// </summary>
public sealed class Metadata : IList<Metadata.Entry>
{
/// <summary>
/// An read-only instance of metadata containing no entries.
/// </summary>
public static readonly Metadata Empty = new Metadata().Freeze();
readonly List<Entry> entries;
bool readOnly;
public Metadata()
{
this.entries = new List<Entry>();
}
public Metadata(ICollection<Entry> entries)
{
this.entries = new List<Entry>(entries);
}
/// <summary>
/// Makes this object read-only.
/// </summary>
/// <returns>this object</returns>
public Metadata Freeze()
{
this.readOnly = true;
return this;
}
// TODO: add support for access by key
#region IList members
public int IndexOf(Metadata.Entry item)
{
return entries.IndexOf(item);
}
public void Insert(int index, Metadata.Entry item)
{
CheckWriteable();
entries.Insert(index, item);
}
public void RemoveAt(int index)
{
CheckWriteable();
entries.RemoveAt(index);
}
public Metadata.Entry this[int index]
{
get
{
return entries[index];
}
set
{
CheckWriteable();
entries[index] = value;
}
}
public void Add(Metadata.Entry item)
{
CheckWriteable();
entries.Add(item);
}
public void Add(string key, string value)
{
Add(new Entry(key, value));
}
public void Add(string key, byte[] valueBytes)
{
Add(new Entry(key, valueBytes));
}
public void Clear()
{
CheckWriteable();
entries.Clear();
}
public bool Contains(Metadata.Entry item)
{
return entries.Contains(item);
}
public void CopyTo(Metadata.Entry[] array, int arrayIndex)
{
entries.CopyTo(array, arrayIndex);
}
public int Count
{
get { return entries.Count; }
}
public bool IsReadOnly
{
get { return readOnly; }
}
public bool Remove(Metadata.Entry item)
{
CheckWriteable();
return entries.Remove(item);
}
public IEnumerator<Metadata.Entry> GetEnumerator()
{
return entries.GetEnumerator();
}
IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return entries.GetEnumerator();
}
private void CheckWriteable()
{
Preconditions.CheckState(!readOnly, "Object is read only");
}
#endregion
/// <summary>
/// Metadata entry
/// </summary>
public struct Entry
{
private static readonly Encoding Encoding = Encoding.ASCII;
readonly string key;
string value;
byte[] valueBytes;
public Entry(string key, byte[] valueBytes)
{
this.key = Preconditions.CheckNotNull(key, "key");
this.value = null;
this.valueBytes = Preconditions.CheckNotNull(valueBytes, "valueBytes");
}
public Entry(string key, string value)
{
this.key = Preconditions.CheckNotNull(key, "key");
this.value = Preconditions.CheckNotNull(value, "value");
this.valueBytes = null;
}
public string Key
{
get
{
return this.key;
}
}
public byte[] ValueBytes
{
get
{
if (valueBytes == null)
{
valueBytes = Encoding.GetBytes(value);
}
return valueBytes;
}
}
public string Value
{
get
{
if (value == null)
{
value = Encoding.GetString(valueBytes);
}
return value;
}
}
public override string ToString()
{
return string.Format("[Entry: key={0}, value={1}]", Key, Value);
}
}
}
}
| |
using System;
using System.Globalization;
using Newtonsoft.Json;
namespace iSukces.UnitedValues
{
partial struct Irradiance
{
public static Irradiance FromWattPerSquareMeter(decimal value)
{
return new Irradiance(value, PowerUnits.Watt, AreaUnits.SquareMeter);
}
}
}
// -----===== autogenerated code =====-----
// ReSharper disable All
// generator: FractionValuesGenerator, UnitJsonConverterGenerator
namespace iSukces.UnitedValues
{
[Serializable]
[JsonConverter(typeof(IrradianceJsonConverter))]
public partial struct Irradiance : IUnitedValue<IrradianceUnit>, IEquatable<Irradiance>, IFormattable
{
/// <summary>
/// creates instance of Irradiance
/// </summary>
/// <param name="value">value</param>
/// <param name="unit">unit</param>
public Irradiance(decimal value, IrradianceUnit unit)
{
Value = value;
Unit = unit;
}
public Irradiance(decimal value, PowerUnit counterUnit, AreaUnit denominatorUnit)
{
Value = value;
Unit = new IrradianceUnit(counterUnit, denominatorUnit);
}
public Irradiance ConvertTo(IrradianceUnit newUnit)
{
// generator : FractionValuesGenerator.Add_ConvertTo
if (Unit.Equals(newUnit))
return this;
var a = new Power(Value, Unit.CounterUnit);
var b = new Area(1, Unit.DenominatorUnit);
a = a.ConvertTo(newUnit.CounterUnit);
b = b.ConvertTo(newUnit.DenominatorUnit);
return new Irradiance(a.Value / b.Value, newUnit);
}
public bool Equals(Irradiance other)
{
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public bool Equals(IUnitedValue<IrradianceUnit> other)
{
if (other is null)
return false;
return Value == other.Value && !(Unit is null) && Unit.Equals(other.Unit);
}
public override bool Equals(object other)
{
return other is IUnitedValue<IrradianceUnit> unitedValue ? Equals(unitedValue) : false;
}
public decimal GetBaseUnitValue()
{
// generator : BasicUnitValuesGenerator.Add_GetBaseUnitValue
var factor1 = GlobalUnitRegistry.Factors.Get(Unit.CounterUnit);
var factor2 = GlobalUnitRegistry.Factors.Get(Unit.DenominatorUnit);
if ((factor1.HasValue && factor2.HasValue))
return Value * factor1.Value / factor2.Value;
throw new Exception("Unable to find multiplication for unit " + Unit);
}
public override int GetHashCode()
{
unchecked
{
return (Value.GetHashCode() * 397) ^ Unit?.GetHashCode() ?? 0;
}
}
public Irradiance Round(int decimalPlaces)
{
return new Irradiance(Math.Round(Value, decimalPlaces), Unit);
}
/// <summary>
/// Returns unit name
/// </summary>
public override string ToString()
{
return Value.ToString(CultureInfo.InvariantCulture) + Unit.UnitName;
}
/// <summary>
/// Returns unit name
/// </summary>
/// <param name="format"></param>
/// <param name="provider"></param>
public string ToString(string format, IFormatProvider provider = null)
{
return this.ToStringFormat(format, provider);
}
public Irradiance WithCounterUnit(PowerUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithCounterUnit
var oldUnit = Unit.CounterUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithCounterUnit(newUnit);
return new Irradiance(oldFactor / newFactor * Value, resultUnit);
}
public Irradiance WithDenominatorUnit(AreaUnit newUnit)
{
// generator : FractionValuesGenerator.Add_WithDenominatorUnit
var oldUnit = Unit.DenominatorUnit;
if (oldUnit == newUnit)
return this;
var oldFactor = GlobalUnitRegistry.Factors.GetThrow(oldUnit);
var newFactor = GlobalUnitRegistry.Factors.GetThrow(newUnit);
var resultUnit = Unit.WithDenominatorUnit(newUnit);
return new Irradiance(newFactor / oldFactor * Value, resultUnit);
}
/// <summary>
/// Inequality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator !=(Irradiance left, Irradiance right)
{
return !left.Equals(right);
}
/// <summary>
/// Equality operator
/// </summary>
/// <param name="left">first value to compare</param>
/// <param name="right">second value to compare</param>
public static bool operator ==(Irradiance left, Irradiance right)
{
return left.Equals(right);
}
public static Irradiance Parse(string value)
{
// generator : FractionValuesGenerator.Add_Parse
if (string.IsNullOrEmpty(value))
throw new ArgumentNullException(nameof(value));
var r = CommonParse.Parse(value, typeof(Irradiance));
var units = Common.SplitUnitNameBySlash(r.UnitName);
if (units.Length != 2)
throw new Exception($"{r.UnitName} is not valid Irradiance unit");
var counterUnit = new PowerUnit(units[0]);
var denominatorUnit = new AreaUnit(units[1]);
return new Irradiance(r.Value, counterUnit, denominatorUnit);
}
/// <summary>
/// value
/// </summary>
public decimal Value { get; }
/// <summary>
/// unit
/// </summary>
public IrradianceUnit Unit { get; }
}
public partial class IrradianceJsonConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(IrradianceUnit);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The JsonReader to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.ValueType == typeof(string))
{
if (objectType == typeof(Irradiance))
return Irradiance.Parse((string)reader.Value);
}
throw new NotImplementedException();
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is null)
writer.WriteNull();
else
writer.WriteValue(value.ToString());
}
}
}
| |
using System;
using System.Collections.Generic;
namespace Procedurality
{
/// <summary>
/// Implements a generalized Dijkstra's algorithm to calculate
/// both minimum distance and minimum path.
/// </summary>
/// <remarks>
/// For this algorithm, all nodes should be provided, and handled
/// in the delegate methods, including the start and finish nodes.
/// </remarks>
public class Dijkstra
{
/// <summary>
/// An optional delegate that can help optimize the algorithm
/// by showing it a subset of nodes to consider. Very useful
/// for limited connectivity graphs. (like pixels on a screen!)
/// </summary>
/// <param name="startingNode">
/// The node that is being traveled away FROM.
/// </param>
/// <returns>
/// An array of nodes that might be reached from the
/// <paramref name="startingNode"/>.
/// </returns>
public delegate IEnumerable<int> NearbyNodesHint(int startingNode);
/// <summary>
/// Determines the cost of moving from a given node to another given node.
/// </summary>
/// <param name="start">
/// The node being moved away from.
/// </param>
/// <param name="finish">
/// The node that may be moved to.
/// </param>
/// <returns>
/// The cost of the transition from <paramref name="start"/> to
/// <paramref name="finish"/>, or <see cref="Int32.MaxValue"/>
/// if the transition is impossible (i.e. there is no edge between
/// the two nodes).
/// </returns>
public delegate int InternodeTraversalCost(int start, int finish);
/// <summary>
/// Creates an instance of the <see cref="Dijkstra"/> class.
/// </summary>
/// <param name="totalNodeCount">
/// The total number of nodes in the graph.
/// </param>
/// <param name="traversalCost">
/// The delegate that can provide the cost of a transition between
/// any two nodes.
/// </param>
/// <param name="hint">
/// An optional delegate that can provide a small subset of nodes
/// that a given node may be connected to.
/// </param>
public Dijkstra(int totalNodeCount, InternodeTraversalCost traversalCost, NearbyNodesHint hint)
{
if (totalNodeCount < 3)
throw new ArgumentOutOfRangeException("totalNodeCount", totalNodeCount, "Expected a minimum of 3.");
if (traversalCost == null)
throw new ArgumentNullException("traversalCost");
Hint = hint;
TraversalCost = traversalCost;
TotalNodeCount = totalNodeCount;
}
protected readonly NearbyNodesHint Hint;
protected readonly InternodeTraversalCost TraversalCost;
protected readonly int TotalNodeCount;
/// <summary>
/// The composite product of a Dijkstra algorithm.
/// </summary>
public struct Results
{
/// <summary>
/// Prepares a Dijkstra results package.
/// </summary>
/// <param name="minimumPath">
/// The minimum path array, where each array element index corresponds
/// to a node designation, and the array element value is a pointer to
/// the node that should be used to travel to this one.
/// </param>
/// <param name="minimumDistance">
/// The minimum distance from the starting node to the given node.
/// </param>
public Results(int[] minimumPath, int[] minimumDistance)
{
MinimumDistance = minimumDistance;
MinimumPath = minimumPath;
}
/// <summary>
/// The minimum path array, where each array element index corresponds
/// to a node designation, and the array element value is a pointer to
/// the node that should be used to travel to this one.
/// </summary>
public readonly int[] MinimumPath;
/// <summary>
/// The minimum distance from the starting node to the given node.
/// </summary>
public readonly int[] MinimumDistance;
}
/// <summary>
/// Performs the Dijkstra algorithm on the data provided when the
/// <see cref="Dijkstra"/> object was instantiated.
/// </summary>
/// <param name="start">
/// The node to use as a starting location.
/// </param>
/// <returns>
/// A struct containing both the minimum distance and minimum path
/// to every node from the given <paramref name="start"/> node.
/// </returns>
public virtual Results Perform(int start)
{
// Initialize the distance to every node from the starting node.
int[] d = GetStartingTraversalCost(start);
// Initialize best path to every node as from the starting node.
int[] p = GetStartingBestPath(start);
ICollection<int> c = GetChoices();
c.Remove(start); // take starting node out of the list of choices
//Debug.WriteLine("Step v C D P");
//Debug.WriteLine(string.Format("init - {{{0}}} [{1}] [{2}]",
// ArrayToString<int>(",", c), ArrayToString<int>(",", d), ArrayToString<int>(",", p)));
//int step = 0;
// begin greedy loop
while (c.Count > 1)
{
// Find element v in c, that minimizes d[v]
int v = FindMinimizingDinC(d, c);
c.Remove(v); // remove v from the list of future solutions
// Consider all unselected nodes and consider their cost from v.
foreach (int w in (Hint != null ? Hint(v) : c))
{
if (!c.Contains(w)) continue; // discard pixels not in c
// At this point, relative(Index) points to a candidate pixel,
// that has not yet been selected, and lies within our area of interest.
// Consider whether it is now within closer reach.
int cost = TraversalCost(v, w);
if (cost < int.MaxValue && d[v] + cost < d[w]) // don't let wrap-around negatives slip by
{
// We have found a better way to get at relative
d[w] = d[v] + cost; // record new distance
// Record how we came to this new pixel
p[w] = v;
}
}
//Debug.WriteLine(string.Format("{4} {3} {{{0}}} [{1}] [{2}]",
// ArrayToString<int>(",", c), ArrayToString<int>(",", d), ArrayToString<int>(",", p), v + 1, ++step));
}
return new Results(p, d);
}
/// <summary>
/// Uses the Dijkstra algorithhm to find the minimum path
/// from one node to another.
/// </summary>
/// <param name="start">
/// The node to use as a starting location.
/// </param>
/// <param name="finish">
/// The node to use as a finishing location.
/// </param>
/// <returns>
/// A struct containing both the minimum distance and minimum path
/// to every node from the given <paramref name="start"/> node.
/// </returns>
public virtual int[] GetMinimumPath(int start, int finish)
{
Results results = Perform(start);
return GetMinimumPath(start, finish, results.MinimumPath);
}
/// <summary>
/// Finds an array of nodes that provide the shortest path
/// from one given node to another.
/// </summary>
/// <param name="start">
/// The starting node.
/// </param>
/// <param name="finish">
/// The finishing node.
/// </param>
/// <param name="shortestPath">
/// The P array of the completed algorithm.
/// </param>
/// <returns>
/// The list of nodes that provide the one step at a time path
/// from <paramref name="start"/> to <paramref name="finish"/> nodes.
/// </returns>
protected virtual int[] GetMinimumPath(int start, int finish, int[] shortestPath)
{
Stack<int> path = new Stack<int>();
do
{
path.Push(finish);
finish = shortestPath[finish]; // step back one step toward the start point
}
while (finish != start);
return path.ToArray();
}
/// <summary>
/// Initializes the P array for the algorithm.
/// </summary>
/// <param name="startingNode">
/// The node that has been designated the starting node for the entire algorithm.
/// </param>
/// <returns>
/// The new P array.
/// </returns>
/// <remarks>
/// A fresh P array will set every single node's source node to be
/// the starting node, including the starting node itself.
/// </remarks>
protected virtual int[] GetStartingBestPath(int startingNode)
{
int[] p = new int[TotalNodeCount];
for (int i = 0; i < p.Length; i++)
p[i] = startingNode;
return p;
}
/// <summary>
/// Finds the yet-unconsidered node that has the least cost to reach.
/// </summary>
/// <param name="d">
/// The cost of reaching any node.
/// </param>
/// <param name="c">
/// The nodes that are still available for picking.
/// </param>
/// <returns>
/// The node that is closest (has the shortest special path).
/// </returns>
protected virtual int FindMinimizingDinC(int[] d, ICollection<int> c)
{
int bestIndex = -1;
foreach (int ci in c)
if (bestIndex == -1 || d[ci] < d[bestIndex])
bestIndex = ci;
return bestIndex;
}
/// <summary>
/// Initializes an collection of all nodes not yet considered.
/// </summary>
/// <returns>
/// The initialized collection.
/// </returns>
protected virtual ICollection<int> GetChoices()
{
ICollection<int> choices = new List<int>(TotalNodeCount);
for (int i = 0; i < TotalNodeCount; i++)
choices.Add(i);
return choices;
}
/// <summary>
/// Initializes the D array for the start of the algorithm.
/// </summary>
/// <param name="start">
/// The starting node.
/// </param>
/// <returns>
/// The contents of the new D array.
/// </returns>
/// <remarks>
/// The traversal cost for every node will be set to impossible
/// (int.MaxValue) unless a connecting edge is found between the
/// <paramref name="start"/>ing node and the node in question.
/// </remarks>
protected virtual int[] GetStartingTraversalCost(int start)
{
int[] subset = new int[TotalNodeCount];
for (int i = 0; i < subset.Length; i++)
{
subset[i] = int.MaxValue; // all are unreachable
}
Console.WriteLine(" * Start={0}",start);
subset[start] = 0; // zero cost from start to start
foreach (int nearby in Hint(start))
subset[nearby] = TraversalCost(start, nearby);
return subset;
}
/// <summary>
/// Joins the elements of an array into a string, using
/// a given separator.
/// </summary>
/// <typeparam name="T">The type of element in the array.</typeparam>
/// <param name="separator">The seperator to insert between each element.</param>
/// <param name="array">The array.</param>
/// <returns>The resulting string.</returns>
/// <remarks>
/// This is very much like <see cref="string.Join"/>, except
/// that it works on arrays of non-strings.
/// </remarks>
protected string ArrayToString<T>(string separator, IEnumerable<int> array)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (int t in array)
sb.AppendFormat("{0}{1}", t < int.MaxValue ? t + 1 : t, separator);
sb.Length -= separator.Length;
return sb.ToString();
}
}
}
| |
// 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.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Implementation.Outlining;
using Microsoft.CodeAnalysis.Editor.Shared.Options;
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Text.Tagging;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Tagging
{
public class AsynchronousTaggerTests : TestBase
{
/// <summary>
/// This hits a special codepath in the product that is optimized for more than 100 spans.
/// I'm leaving this test here because it covers that code path (as shown by code coverage)
/// </summary>
[Fact]
[WorkItem(530368)]
public void LargeNumberOfSpans()
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile(@"class Program
{
void M()
{
int z = 0;
z = z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z +
z + z + z + z + z + z + z + z + z + z;
}
}"))
{
var tagProducer = new TestTagProducer(
(span, cancellationToken) =>
{
return new List<ITagSpan<TestTag>>() { new TagSpan<TestTag>(span, new TestTag()) };
});
var asyncListener = new TaggerOperationListener();
var notificationService = workspace.GetService<IForegroundNotificationService>();
var eventSource = CreateEventSource();
var taggerProvider = new TestTaggerProvider(
tagProducer,
eventSource,
workspace,
asyncListener,
notificationService);
var document = workspace.Documents.First();
var textBuffer = document.TextBuffer;
var snapshot = textBuffer.CurrentSnapshot;
var tagger = taggerProvider.CreateTagger<TestTag>(textBuffer);
using (IDisposable disposable = (IDisposable)tagger)
{
var spans = Enumerable.Range(0, 101).Select(i => new Span(i * 4, 1));
var snapshotSpans = new NormalizedSnapshotSpanCollection(snapshot, spans);
eventSource.SendUpdateEvent();
asyncListener.CreateWaitTask().PumpingWait();
var tags = tagger.GetTags(snapshotSpans);
Assert.Equal(1, tags.Count());
}
}
}
[Fact]
public void TestSynchronousOutlining()
{
using (var workspace = CSharpWorkspaceFactory.CreateWorkspaceFromFile("class Program {\r\n\r\n}"))
{
var tagProvider = new OutliningTaggerProvider(
workspace.GetService<IForegroundNotificationService>(),
workspace.GetService<ITextEditorFactoryService>(),
workspace.GetService<IEditorOptionsFactoryService>(),
workspace.GetService<IProjectionBufferFactoryService>(),
(IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>>)workspace.ExportProvider.GetExports<IAsynchronousOperationListener, FeatureMetadata>());
var document = workspace.Documents.First();
var textBuffer = document.TextBuffer;
var tagger = tagProvider.CreateTagger<IOutliningRegionTag>(textBuffer);
using (var disposable = (IDisposable)tagger)
{
ProducerPopulatedTagSource<IOutliningRegionTag> tagSource = null;
tagProvider.TryRetrieveTagSource(null, textBuffer, out tagSource);
tagSource.ComputeTagsSynchronouslyIfNoAsynchronousComputationHasCompleted = true;
// The very first all to get tags should return the single outlining span.
var tags = tagger.GetTags(new NormalizedSnapshotSpanCollection(textBuffer.CurrentSnapshot.GetFullSpan()));
Assert.Equal(1, tags.Count());
}
}
}
private static TestTaggerEventSource CreateEventSource()
{
return new TestTaggerEventSource();
}
private static Mock<IOptionService> CreateFeatureOptionsMock()
{
var featureOptions = new Mock<IOptionService>(MockBehavior.Strict);
featureOptions.Setup(s => s.GetOption(EditorComponentOnOffOptions.Tagger)).Returns(true);
return featureOptions;
}
private sealed class TaggerOperationListener : AsynchronousOperationListener
{
}
private sealed class TestTag : TextMarkerTag
{
public TestTag() :
base("Test")
{
}
}
private sealed class TestTagProducer : AbstractSingleDocumentTagProducer<TestTag>
{
public delegate List<ITagSpan<TestTag>> Callback(SnapshotSpan span, CancellationToken cancellationToken);
private readonly Callback _produceTags;
public TestTagProducer(Callback produceTags)
{
_produceTags = produceTags;
}
public override Task<IEnumerable<ITagSpan<TestTag>>> ProduceTagsAsync(Document document, SnapshotSpan snapshotSpan, int? caretPosition, CancellationToken cancellationToken)
{
return Task.FromResult<IEnumerable<ITagSpan<TestTag>>>(_produceTags(snapshotSpan, cancellationToken));
}
}
private sealed class TestTaggerProvider : AbstractAsynchronousBufferTaggerProvider<TestTag>
{
private readonly TestTagProducer _tagProducer;
private readonly ITaggerEventSource _eventSource;
private readonly Workspace _workspace;
private readonly bool _disableCancellation;
public TestTaggerProvider(
TestTagProducer tagProducer,
ITaggerEventSource eventSource,
Workspace workspace,
IAsynchronousOperationListener asyncListener,
IForegroundNotificationService notificationService,
bool disableCancellation = false)
: base(asyncListener, notificationService)
{
_tagProducer = tagProducer;
_eventSource = eventSource;
_workspace = workspace;
_disableCancellation = disableCancellation;
}
protected override bool RemoveTagsThatIntersectEdits => true;
protected override SpanTrackingMode SpanTrackingMode => SpanTrackingMode.EdgeExclusive;
protected override ITaggerEventSource CreateEventSource(ITextView textViewOpt, ITextBuffer subjectBuffer)
{
return _eventSource;
}
protected override ITagProducer<TestTag> CreateTagProducer()
{
return _tagProducer;
}
}
private sealed class TestTaggerEventSource : AbstractTaggerEventSource
{
public TestTaggerEventSource() :
base(delay: TaggerDelay.NearImmediate)
{
}
public override string EventKind
{
get
{
return "Test";
}
}
public void SendUpdateEvent()
{
this.RaiseChanged();
}
public override void Connect()
{
}
public override void Disconnect()
{
}
}
}
}
| |
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 sep20v1.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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;
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the ""Software""), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Data.Services.Common;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.Runtime;
namespace Orleans.AzureUtils
{
internal class SiloInstanceTableEntry : TableEntity
{
public string DeploymentId { get; set; } // PartitionKey
public string Address { get; set; } // RowKey
public string Port { get; set; } // RowKey
public string Generation { get; set; } // RowKey
public string HostName { get; set; } // Mandatory
public string Status { get; set; } // Mandatory
public string ProxyPort { get; set; } // Optional
public string RoleName { get; set; } // Optional - only for Azure role
public string InstanceName { get; set; } // Optional - only for Azure role
public string UpdateZone { get; set; } // Optional - only for Azure role
public string FaultZone { get; set; } // Optional - only for Azure role
public string SuspectingSilos { get; set; } // For liveness
public string SuspectingTimes { get; set; } // For liveness
public string StartTime { get; set; } // Time this silo was started. For diagnostics.
public string IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics.
public string MembershipVersion { get; set; } // Special version row (for serializing table updates). // We'll have a designated row with only MembershipVersion column.
internal const string TABLE_VERSION_ROW = "VersionRow"; // Row key for version row.
internal const char Seperator = '-';
public static string ConstructRowKey(SiloAddress silo)
{
return String.Format("{0}-{1}-{2}", silo.Endpoint.Address, silo.Endpoint.Port, silo.Generation);
}
internal static SiloAddress UnpackRowKey(string rowKey)
{
var debugInfo = "UnpackRowKey";
try
{
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0}", rowKey);
Trace.TraceInformation(debugInfo);
#endif
int idx1 = rowKey.IndexOf(Seperator);
int idx2 = rowKey.LastIndexOf(Seperator);
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0} Idx1={1} Idx2={2}", rowKey, idx1, idx2);
#endif
var addressStr = rowKey.Substring(0, idx1);
var portStr = rowKey.Substring(idx1 + 1, idx2 - idx1 - 1);
var genStr = rowKey.Substring(idx2 + 1);
#if DEBUG
debugInfo = String.Format("UnpackRowKey: RowKey={0} -> Address={1} Port={2} Generation={3}", rowKey, addressStr, portStr, genStr);
Trace.TraceInformation(debugInfo);
#endif
IPAddress address = IPAddress.Parse(addressStr);
int port = Int32.Parse(portStr);
int generation = Int32.Parse(genStr);
return SiloAddress.New(new IPEndPoint(address, port), generation);
}
catch (Exception exc)
{
throw new AggregateException("Error from " + debugInfo, exc);
}
}
public override string ToString()
{
var sb = new StringBuilder();
if (RowKey.Equals(TABLE_VERSION_ROW))
{
sb.Append("VersionRow [").Append(DeploymentId);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" MembershipVersion=").Append(MembershipVersion);
sb.Append("]");
}
else
{
sb.Append("OrleansSilo [");
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" LocalEndpoint=").Append(Address);
sb.Append(" LocalPort=").Append(Port);
sb.Append(" Generation=").Append(Generation);
sb.Append(" Host=").Append(HostName);
sb.Append(" Status=").Append(Status);
sb.Append(" ProxyPort=").Append(ProxyPort);
if (!string.IsNullOrEmpty(RoleName)) sb.Append(" RoleName=").Append(RoleName);
sb.Append(" Instance=").Append(InstanceName);
sb.Append(" UpgradeZone=").Append(UpdateZone);
sb.Append(" FaultZone=").Append(FaultZone);
if (!string.IsNullOrEmpty(SuspectingSilos)) sb.Append(" SuspectingSilos=").Append(SuspectingSilos);
if (!string.IsNullOrEmpty(SuspectingTimes)) sb.Append(" SuspectingTimes=").Append(SuspectingTimes);
sb.Append(" StartTime=").Append(StartTime);
sb.Append(" IAmAliveTime=").Append(IAmAliveTime);
sb.Append("]");
}
return sb.ToString();
}
}
internal class OrleansSiloInstanceManager
{
public string TableName { get { return INSTANCE_TABLE_NAME; } }
private const string INSTANCE_TABLE_NAME = "OrleansSiloInstances";
private readonly string INSTANCE_STATUS_CREATED = SiloStatus.Created.ToString(); //"Created";
private readonly string INSTANCE_STATUS_ACTIVE = SiloStatus.Active.ToString(); //"Active";
private readonly string INSTANCE_STATUS_DEAD = SiloStatus.Dead.ToString(); //"Dead";
private readonly AzureTableDataManager<SiloInstanceTableEntry> storage;
private readonly TraceLogger logger;
internal static TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public string DeploymentId { get; private set; }
private OrleansSiloInstanceManager(string deploymentId, string storageConnectionString)
{
DeploymentId = deploymentId;
logger = TraceLogger.GetLogger(this.GetType().Name, TraceLogger.LoggerType.Runtime);
storage = new AzureTableDataManager<SiloInstanceTableEntry>(
INSTANCE_TABLE_NAME, storageConnectionString, logger);
}
public static async Task<OrleansSiloInstanceManager> GetManager(string deploymentId, string storageConnectionString)
{
var instance = new OrleansSiloInstanceManager(deploymentId, storageConnectionString);
try
{
await instance.storage.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = String.Format("Unable to create or connect to the Azure table in {0}", initTimeout);
instance.logger.Error(ErrorCode.AzureTable_32, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = String.Format("Exception trying to create or connect to the Azure table: {0}", ex.Message);
instance.logger.Error(ErrorCode.AzureTable_33, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return instance;
}
public SiloInstanceTableEntry CreateTableVersionEntry(int tableVersion)
{
return new SiloInstanceTableEntry
{
DeploymentId = DeploymentId,
PartitionKey = DeploymentId,
RowKey = SiloInstanceTableEntry.TABLE_VERSION_ROW,
MembershipVersion = tableVersion.ToString(CultureInfo.InvariantCulture)
};
}
public void RegisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_CREATED;
logger.Info(ErrorCode.Runtime_Error_100270, "Registering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void UnregisterSiloInstance(SiloInstanceTableEntry entry)
{
entry.Status = INSTANCE_STATUS_DEAD;
logger.Info(ErrorCode.Runtime_Error_100271, "Unregistering silo instance: {0}", entry.ToString());
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public void ActivateSiloInstance(SiloInstanceTableEntry entry)
{
logger.Info(ErrorCode.Runtime_Error_100272, "Activating silo instance: {0}", entry.ToString());
entry.Status = INSTANCE_STATUS_ACTIVE;
storage.UpsertTableEntryAsync(entry)
.WaitWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
}
public List<Uri> FindAllGatewayProxyEndpoints()
{
IEnumerable<SiloInstanceTableEntry> gatewaySiloInstances = FindAllGatewaySilos();
return gatewaySiloInstances.Select(ToGatewayUri).ToList();
}
/// <summary>
/// Represent a silo instance entry in the gateway URI format.
/// </summary>
/// <param name="gateway">The input silo instance</param>
/// <returns></returns>
private static Uri ToGatewayUri(SiloInstanceTableEntry gateway)
{
int proxyPort = 0;
if (!string.IsNullOrEmpty(gateway.ProxyPort))
int.TryParse(gateway.ProxyPort, out proxyPort);
return new Uri(string.Format("gwy.tcp://{0}:{1}/{2}", gateway.Address, proxyPort, gateway.Generation));
}
private IEnumerable<SiloInstanceTableEntry> FindAllGatewaySilos()
{
if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100277, "Searching for active gateway silos for deployment {0}.", this.DeploymentId);
const string zeroPort = "0";
try
{
Expression<Func<SiloInstanceTableEntry, bool>> query = instance =>
instance.PartitionKey == this.DeploymentId
&& instance.Status == INSTANCE_STATUS_ACTIVE
&& instance.ProxyPort != zeroPort;
var queryResults = storage.ReadTableEntriesAndEtagsAsync(query)
.WaitForResultWithThrow(AzureTableDefaultPolicies.TableOperationTimeout);
List<SiloInstanceTableEntry> gatewaySiloInstances = queryResults.Select(entity => entity.Item1).ToList();
logger.Info(ErrorCode.Runtime_Error_100278, "Found {0} active Gateway Silos for deployment {1}.", gatewaySiloInstances.Count, this.DeploymentId);
return gatewaySiloInstances;
}catch(Exception exc)
{
logger.Error(ErrorCode.Runtime_Error_100331, string.Format("Error searching for active gateway silos for deployment {0} ", this.DeploymentId), exc);
throw;
}
}
public async Task<string> DumpSiloInstanceTable()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
SiloInstanceTableEntry[] entries = queryResults.Select(entry => entry.Item1).ToArray();
var sb = new StringBuilder();
sb.Append(String.Format("Deployment {0}. Silos: ", DeploymentId));
// Loop through the results, displaying information about the entity
Array.Sort(entries,
(e1, e2) =>
{
if (e1 == null) return (e2 == null) ? 0 : -1;
if (e2 == null) return (e1 == null) ? 0 : 1;
if (e1.InstanceName == null) return (e2.InstanceName == null) ? 0 : -1;
if (e2.InstanceName == null) return (e1.InstanceName == null) ? 0 : 1;
return String.CompareOrdinal(e1.InstanceName, e2.InstanceName);
});
foreach (SiloInstanceTableEntry entry in entries)
{
sb.AppendLine(String.Format("[IP {0}:{1}:{2}, {3}, Instance={4}, Status={5}]", entry.Address, entry.Port, entry.Generation,
entry.HostName, entry.InstanceName, entry.Status));
}
return sb.ToString();
}
#region Silo instance table storage operations
internal Task<string> MergeTableEntryAsync(SiloInstanceTableEntry data)
{
return storage.MergeTableEntryAsync(data, AzureStorageUtils.ANY_ETAG); // we merge this without checking eTags.
}
internal Task<Tuple<SiloInstanceTableEntry, string>> ReadSingleTableEntryAsync(string partitionKey, string rowKey)
{
return storage.ReadSingleTableEntryAsync(partitionKey, rowKey);
}
internal async Task<int> DeleteTableEntries(string deploymentId)
{
if (deploymentId == null) throw new ArgumentNullException("deploymentId");
var entries = await storage.ReadAllTableEntriesForPartitionAsync(deploymentId);
var entriesList = new List<Tuple<SiloInstanceTableEntry, string>>(entries);
if (entriesList.Count <= AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS)
{
await storage.DeleteTableEntriesAsync(entriesList);
}else
{
List<Task> tasks = new List<Task>();
foreach (var batch in entriesList.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(storage.DeleteTableEntriesAsync(batch));
}
await Task.WhenAll(tasks);
}
return entriesList.Count();
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindSiloEntryAndTableVersionRow(SiloAddress siloAddress)
{
string rowKey = SiloInstanceTableEntry.ConstructRowKey(siloAddress);
Expression<Func<SiloInstanceTableEntry, bool>> query = instance =>
instance.PartitionKey == DeploymentId
&& (instance.RowKey == rowKey || instance.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
var queryResults = await storage.ReadTableEntriesAndEtagsAsync(query);
var asList = queryResults.ToList();
if (asList.Count < 1 || asList.Count > 2)
throw new KeyNotFoundException(string.Format("Could not find table version row or found too many entries. Was looking for key {0}, found = {1}", siloAddress.ToLongString(), Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not read table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
internal async Task<List<Tuple<SiloInstanceTableEntry, string>>> FindAllSiloEntries()
{
var queryResults = await storage.ReadAllTableEntriesForPartitionAsync(this.DeploymentId);
var asList = queryResults.ToList();
if (asList.Count < 1)
throw new KeyNotFoundException(string.Format("Could not find enough rows in the FindAllSiloEntries call. Found = {0}", Utils.EnumerableToString(asList)));
int numTableVersionRows = asList.Count(tuple => tuple.Item1.RowKey == SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (numTableVersionRows < 1)
throw new KeyNotFoundException(string.Format("Did not find table version row. Read = {0}", Utils.EnumerableToString(asList)));
if (numTableVersionRows > 1)
throw new KeyNotFoundException(string.Format("Read {0} table version rows, while was expecting only 1. Read = {1}", numTableVersionRows, Utils.EnumerableToString(asList)));
return asList;
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
internal async Task<bool> TryCreateTableVersionEntryAsync()
{
try
{
var versionRow = await storage.ReadSingleTableEntryAsync(DeploymentId, SiloInstanceTableEntry.TABLE_VERSION_ROW);
if (versionRow != null && versionRow.Item1 != null)
{
return false;
}
SiloInstanceTableEntry entry = CreateTableVersionEntry(0);
await storage.CreateTableEntryAsync(entry);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Insert (create new) row entry
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="tableVersionEtag">Version row eTag</param>
internal async Task<bool> InsertSiloEntryConditionally(SiloInstanceTableEntry siloEntry, SiloInstanceTableEntry tableVersionEntry, string tableVersionEtag)
{
try
{
await storage.InsertTwoTableEntriesConditionallyAsync(siloEntry, tableVersionEntry, tableVersionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("InsertSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
/// <summary>
/// Conditionally update the row for this entry, but only if the eTag matches with the current record in data store
/// </summary>
/// <param name="siloEntry">Silo Entry to be written</param>
/// <param name="entryEtag">ETag value for the entry being updated</param>
/// <param name="tableVersionEntry">Version row to update</param>
/// <param name="versionEtag">ETag value for the version row</param>
/// <returns></returns>
internal async Task<bool> UpdateSiloEntryConditionally(SiloInstanceTableEntry siloEntry, string entryEtag, SiloInstanceTableEntry tableVersionEntry, string versionEtag)
{
try
{
await storage.UpdateTwoTableEntriesConditionallyAsync(siloEntry, entryEtag, tableVersionEntry, versionEtag);
return true;
}
catch (Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (!AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus)) throw;
if (logger.IsVerbose2) logger.Verbose2("UpdateSiloEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
throw;
}
}
#endregion
}
}
| |
using System;
using NSec.Cryptography;
namespace NSec.Experimental.PasswordBased
{
public static class PasswordBasedKeyExporter
{
public static byte[] Export(
Key key,
PasswordBasedEncryptionScheme scheme,
ReadOnlySpan<byte> password,
ReadOnlySpan<byte> salt,
ReadOnlySpan<byte> nonce)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
KeyBlobFormat format = GetKeyBlobFormat(key.Algorithm);
byte[] plaintext = key.Export(format);
return Encrypt(plaintext, scheme, password, salt, nonce);
}
public static Key Import(
Algorithm algorithm,
ReadOnlySpan<byte> blob,
PasswordBasedEncryptionScheme scheme,
ReadOnlySpan<byte> password,
in KeyCreationParameters creationParameters = default)
{
if (algorithm == null)
{
throw new ArgumentNullException(nameof(algorithm));
}
KeyBlobFormat format = GetKeyBlobFormat(algorithm);
byte[]? plaintext = Decrypt(blob, scheme, password);
return Key.Import(algorithm, plaintext, format, in creationParameters);
}
internal static byte[]? Decrypt(
ReadOnlySpan<byte> blob,
PasswordBasedEncryptionScheme scheme,
ReadOnlySpan<byte> password)
{
if (scheme == null)
{
throw new ArgumentNullException(nameof(scheme));
}
Reader reader = new(blob);
Read(ref reader, 0x0000);
ReadPasswordParameters(ref reader, scheme.KeyDerivationAlgorithm, out ReadOnlySpan<byte> salt);
ReadEncryptionParameters(ref reader, scheme.EncryptionAlgorithm, out ReadOnlySpan<byte> nonce);
Read(ref reader, out ReadOnlySpan<byte> ciphertext);
return scheme.Decrypt(password, salt, nonce, ciphertext);
}
internal static byte[] Encrypt(
ReadOnlySpan<byte> plaintext,
PasswordBasedEncryptionScheme scheme,
ReadOnlySpan<byte> password,
ReadOnlySpan<byte> salt,
ReadOnlySpan<byte> nonce)
{
if (scheme == null)
{
throw new ArgumentNullException(nameof(scheme));
}
Writer writer = new(new byte[1000]);
Write(ref writer, 0x0000);
WritePasswordParameters(ref writer, scheme.KeyDerivationAlgorithm, salt);
WriteEncryptionParameters(ref writer, scheme.EncryptionAlgorithm, nonce);
byte[] ciphertext = scheme.Encrypt(password, salt, nonce, plaintext);
Write(ref writer, ciphertext);
return writer.ToArray();
}
private static KeyBlobFormat GetKeyBlobFormat(
Algorithm algorithm)
{
return algorithm switch
{
AeadAlgorithm _ or MacAlgorithm _ or StreamCipherAlgorithm _ => KeyBlobFormat.NSecSymmetricKey,
KeyAgreementAlgorithm _ or SignatureAlgorithm _ => KeyBlobFormat.NSecPrivateKey,
_ => throw new NotSupportedException(),
};
}
private static void ReadEncryptionParameters(
ref Reader reader,
AeadAlgorithm algorithm,
out ReadOnlySpan<byte> nonce)
{
switch (algorithm)
{
case Aes256Gcm _:
Read(ref reader, 0x2001);
Read(ref reader, out nonce);
break;
case ChaCha20Poly1305 _:
Read(ref reader, 0x2002);
Read(ref reader, out nonce);
break;
case XChaCha20Poly1305 _:
Read(ref reader, 0x2003);
Read(ref reader, out nonce);
break;
default:
throw new NotSupportedException();
}
}
private static void ReadPasswordParameters(
ref Reader reader,
PasswordBasedKeyDerivationAlgorithm algorithm,
out ReadOnlySpan<byte> salt)
{
switch (algorithm)
{
case Argon2i argon2i:
argon2i.GetParameters(out Argon2Parameters argon2iParameters);
Read(ref reader, 0x1001);
Read(ref reader, out salt);
Read(ref reader, argon2iParameters.DegreeOfParallelism);
Read(ref reader, argon2iParameters.MemorySize);
Read(ref reader, argon2iParameters.NumberOfPasses);
break;
case Argon2id argon2id:
argon2id.GetParameters(out Argon2Parameters argon2idParameters);
Read(ref reader, 0x1002);
Read(ref reader, out salt);
Read(ref reader, argon2idParameters.DegreeOfParallelism);
Read(ref reader, argon2idParameters.MemorySize);
Read(ref reader, argon2idParameters.NumberOfPasses);
break;
case Pbkdf2HmacSha256 pbkdf2HmacSha256:
pbkdf2HmacSha256.GetParameters(out Pbkdf2Parameters pbkdf2HmacSha256Parameters);
Read(ref reader, 0x1003);
Read(ref reader, out salt);
Read(ref reader, pbkdf2HmacSha256Parameters.IterationCount);
break;
case Scrypt scrypt:
scrypt.GetParameters(out ScryptParameters scryptParameters);
Read(ref reader, 0x1004);
Read(ref reader, out salt);
Read(ref reader, scryptParameters.Cost);
Read(ref reader, scryptParameters.BlockSize);
Read(ref reader, scryptParameters.Parallelization);
break;
default:
throw new NotSupportedException();
};
}
private static void WriteEncryptionParameters(
ref Writer writer,
AeadAlgorithm algorithm,
ReadOnlySpan<byte> nonce)
{
switch (algorithm)
{
case Aes256Gcm _:
Write(ref writer, 0x2001);
Write(ref writer, nonce);
break;
case ChaCha20Poly1305 _:
Write(ref writer, 0x2002);
Write(ref writer, nonce);
break;
case XChaCha20Poly1305 _:
Write(ref writer, 0x2003);
Write(ref writer, nonce);
break;
default:
throw new NotSupportedException();
}
}
private static void WritePasswordParameters(
ref Writer writer,
PasswordBasedKeyDerivationAlgorithm algorithm,
ReadOnlySpan<byte> salt)
{
switch (algorithm)
{
case Argon2i argon2i:
argon2i.GetParameters(out Argon2Parameters argon2iParameters);
Write(ref writer, 0x1001);
Write(ref writer, salt);
Write(ref writer, argon2iParameters.DegreeOfParallelism);
Write(ref writer, argon2iParameters.MemorySize);
Write(ref writer, argon2iParameters.NumberOfPasses);
break;
case Argon2id argon2id:
argon2id.GetParameters(out Argon2Parameters argon2idParameters);
Write(ref writer, 0x1002);
Write(ref writer, salt);
Write(ref writer, argon2idParameters.DegreeOfParallelism);
Write(ref writer, argon2idParameters.MemorySize);
Write(ref writer, argon2idParameters.NumberOfPasses);
break;
case Pbkdf2HmacSha256 pbkdf2HmacSha256:
pbkdf2HmacSha256.GetParameters(out Pbkdf2Parameters pbkdf2HmacSha256Parameters);
Write(ref writer, 0x1003);
Write(ref writer, salt);
Write(ref writer, pbkdf2HmacSha256Parameters.IterationCount);
break;
case Scrypt scrypt:
scrypt.GetParameters(out ScryptParameters scryptParameters);
Write(ref writer, 0x1004);
Write(ref writer, salt);
Write(ref writer, scryptParameters.Cost);
Write(ref writer, scryptParameters.BlockSize);
Write(ref writer, scryptParameters.Parallelization);
break;
default:
throw new NotSupportedException();
};
}
private static void Read(
ref Reader reader,
int value)
{
if (value != System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(reader[4]))
{
throw new InvalidOperationException();
}
}
private static void Read(
ref Reader reader,
long value)
{
if (value != System.Buffers.Binary.BinaryPrimitives.ReadInt64LittleEndian(reader[8]))
{
throw new InvalidOperationException();
}
}
private static void Read(
ref Reader reader,
out ReadOnlySpan<byte> value)
{
int length = System.Buffers.Binary.BinaryPrimitives.ReadInt32LittleEndian(reader[4]);
value = reader[length];
}
private static void Write(
ref Writer writer,
int value)
{
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(writer[4], value);
}
private static void Write(
ref Writer writer,
long value)
{
System.Buffers.Binary.BinaryPrimitives.WriteInt64LittleEndian(writer[8], value);
}
private static void Write(
ref Writer writer,
ReadOnlySpan<byte> value)
{
System.Buffers.Binary.BinaryPrimitives.WriteInt32LittleEndian(writer[4], value.Length);
value.CopyTo(writer[value.Length]);
}
private ref struct Reader
{
private readonly ReadOnlySpan<byte> _bytes;
private int _pos;
public Reader(
ReadOnlySpan<byte> bytes)
{
_bytes = bytes;
_pos = 0;
}
public ReadOnlySpan<byte> this[
int length]
{
get
{
ReadOnlySpan<byte> span = _bytes.Slice(_pos, length);
_pos += length;
return span;
}
}
}
private ref struct Writer
{
private readonly Span<byte> _bytes;
private int _pos;
public Writer(
Span<byte> bytes)
{
_bytes = bytes;
_pos = 0;
}
public Span<byte> this[
int length]
{
get
{
Span<byte> span = _bytes.Slice(_pos, length);
_pos += length;
return span;
}
}
public byte[] ToArray()
{
return _bytes.Slice(0, _pos).ToArray();
}
}
}
}
| |
using CSScriptLibrary;
using System;
using System.Linq;
using System.IO;
using csscript;
using System.CodeDom.Compiler;
// Read in more details about all aspects of CS-Script hosting in applications
// here: http://www.csscript.net/help/Script_hosting_guideline_.html
//
// This file contains samples for the script hosting scenarios relying on CS-Script Native interface (API).
// This API is a compiler specific interface, which relies solely on CodeDom compiler. In most of the cases
// CS-Script Native model is the most flexible and natural choice
//
// Apart from Native API CS-Script offers alternative hosting model: CS-Script Evaluator, which provides
// a unified generic interface allowing dynamic switch the underlying compiling services (Mono, Roslyn, CodeDom)
// without the need for changing the hosting code.
//
// The Native interface is the original API that was designed to take maximum advantage of the dynamic C# code
// execution with CodeDom. The original implementation of this API was developed even before any compiler-as-service
// solution became available. Being based solely on CodeDOM the API doesn't utilize neither Mono nor Roslyn
// scripting solutions. Despite that CS-Script Native is the most mature, powerful and flexible API available with CS-Script.
//
// Native interface allows some unique features that are not available with CS-Script Evaluator:
// - Debugging scripts
// - Script caching
// - Script unloading
namespace CSScriptNativeApi
{
public class HostApp
{
public static void Test()
{
var host = new HostApp();
host.Log("Testing compiling services CS-Script Native API");
Console.WriteLine("---------------------------------------------");
CodeDomSamples.LoadMethod_Instance();
CodeDomSamples.LoadMethod_Static();
CodeDomSamples.LoadDelegate();
CodeDomSamples.CreateAction();
CodeDomSamples.CreateFunc();
CodeDomSamples.LoadCode();
CodeDomSamples.LoadCode_WithInterface(host);
CodeDomSamples.LoadCode_WithDuckTypedInterface(host);
CodeDomSamples.ExecuteAndUnload();
//CodeDomSamples.DebugTest(); //uncomment if want to fire an assertion during the script execution
}
public class CodeDomSamples
{
public static void LoadMethod_Instance()
{
// 1- LoadMethod wraps method into a class definition, compiles it and returns loaded assembly
// 2 - CreateObject creates instance of a first class in the assembly
dynamic script = CSScript.LoadMethod(@"int Sqr(int data)
{
return data * data;
}")
.CreateObject("*");
var result = script.Sqr(7);
}
public static void LoadMethod_Static()
{
// 1 - LoadMethod wraps method into a class definition, compiles it and returns loaded assembly
// 2 - GetStaticMethod returns first found static method as a duck-typed delegate that
// accepts 'params object[]' arguments
//
// Note: you can use GetStaticMethodWithArgs for higher precision method search: GetStaticMethodWithArgs("*.SayHello", typeof(string));
var sayHello = CSScript.LoadMethod(@"static void SayHello(string greeting)
{
Console.WriteLine(greeting);
}")
.GetStaticMethod();
sayHello("Hello World!");
}
public static void LoadDelegate()
{
// LoadDelegate wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns the method delegate for the method, which matches the delegate specified
// as the type parameter of LoadDelegate
// The 'using System;' is optional; it demonstrates how to specify 'using' in the method-only syntax
var sayHello = CSScript.LoadDelegate<Action<string>>(
@"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
sayHello("Hello World!");
}
public static void CreateAction()
{
// Wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns duck-typed delegate. A delegate with 'params object[]' arguments and
// without any specific return type.
var sayHello = CSScript.CreateAction(@"void SayHello(string greeting)
{
Console.WriteLine(greeting);
}");
sayHello("Hello World!");
}
public static void CreateFunc()
{
// Wraps method into a class definition, compiles it and loads the compiled assembly.
// It returns duck-typed delegate. A delegate with 'params object[]' arguments and
// int as a return type.
var Sqr = CSScript.CreateFunc<int>(@"int Sqr(int a)
{
return a * a;
}");
int r = Sqr(3);
}
public static void LoadCode()
{
// LoadCode compiles code and returns instance of a first class
// in the compiled assembly
dynamic script = CSScript.LoadCode(@"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}")
.CreateObject("*");
int result = script.Sum(1, 2);
}
public static void LoadCodeWithConfig()
{
// LoadCode compiles code and returns instance of a first class
// in the compiled assembly
string file = Path.GetTempFileName();
try
{
File.WriteAllText(file, @"using System;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
var settings = new Settings();
//settings = null; // set to null to foll back to defaults
dynamic script = CSScript.LoadWithConfig(file, null, false, settings, "/define:TEST")
.CreateObject("*");
int result = script.Sum(1, 2);
}
finally
{
if (File.Exists(file))
File.Delete(file);
}
}
public static void LoadCode_WithInterface(HostApp host)
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly.
// 2 - The script class implements host app interface so the returned object can be type casted into it.
// 3 - In this sample host object is passed into script routine.
var calc = (ICalc) CSScript.LoadCode(@"using CSScriptNativeApi;
public class Script : ICalc
{
public int Sum(int a, int b)
{
if(Host != null)
Host.Log(""Sum is invoked"");
return a + b;
}
public HostApp Host { get; set; }
}")
.CreateObject("*");
calc.Host = host;
int result = calc.Sum(1, 2);
}
public static void LoadCode_WithDuckTypedInterface(HostApp host)
{
// 1 - LoadCode compiles code and returns instance of a first class in the compiled assembly
// 2- The script class doesn't implement host app interface but it can still be aligned to
// one as long at it implements the interface members
// 3 - In this sample host object is passed into script routine.
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
ICalc calc = CSScript.LoadCode(@"using CSScriptNativeApi;
public class Script
{
public int Sum(int a, int b)
{
if(Host != null)
Host.Log(""Sum is invoked"");
return a + b;
}
public HostApp Host { get; set; }
}")
.CreateObject("*")
.AlignToInterface<ICalc>();
calc.Host = host;
int result = calc.Sum(1, 2);
}
public static void ExecuteAndUnload()
{
// The script will be loaded into a temporary AppDomain and unloaded after the execution.
// Note: remote execution is a subject of some restrictions associated with the nature of the
// CLR cross-AppDomain interaction model:
// * the script class must be serializable or derived from MarshalByRefObject.
//
// * any object (call arguments, return objects) that crosses ApPDomain boundaries
// must be serializable or derived from MarshalByRefObject.
//
// * long living script class instances may get disposed in remote domain even if they are
// being referenced in the current AppDomain. You need to use the usual .NET techniques
// to prevent that. See LifetimeManagement.cs sample for details.
//This use-case uses Interface Alignment and this requires all assemblies involved to have
//non-empty Assembly.Location
CSScript.GlobalSettings.InMemoryAssembly = false;
var code = @"using System;
public class Script : MarshalByRefObject
{
public void Hello(string greeting)
{
Console.WriteLine(greeting);
}
}";
//Note: usage of helper.CreateAndAlignToInterface<IScript>("Script") is also acceptable
using (var helper = new AsmHelper(CSScript.CompileCode(code), null, deleteOnExit: true))
{
IScript script = helper.CreateAndAlignToInterface<IScript>("*");
script.Hello("Hi there...");
}
//from this point AsmHelper is disposed and the temp AppDomain is unloaded
}
public static void DebugTest()
{
//pops up an assertion dialog
dynamic script = CSScript.LoadCode(@"using System;
using System.Diagnostics;
public class Script
{
public int Sum(int a, int b)
{
Debug.Assert(false,""Testing CS-Script debugging..."");
return a+b;
}
}", null, debugBuild: true).CreateObject("*");
int result = script.Sum(1, 2);
}
}
public void Log(string message)
{
Console.WriteLine(message);
}
}
public interface IScript
{
void Hello(string greeting);
}
public interface ICalc
{
HostApp Host { get; set; }
int Sum(int a, int b);
}
public class Samples
{
static public void CompilingHistory()
{
string script = Path.GetTempFileName();
string scriptAsm = script + ".dll";
CSScript.KeepCompilingHistory = true;
try
{
File.WriteAllText(script, @"using System;
using System.Windows.Forms;
public class Script
{
public int Sum(int a, int b)
{
return a+b;
}
}");
CSScript.CompileFile(script, scriptAsm, false, null);
CompilingInfo info = CSScript.CompilingHistory
.Values
.FirstOrDefault(item => item.ScriptFile == script);
if (info != null)
{
Console.WriteLine("Script: " + info.ScriptFile);
Console.WriteLine("Referenced assemblies:");
foreach (string asm in info.Input.ReferencedAssemblies)
Console.WriteLine(asm);
if (info.Result.Errors.HasErrors)
{
foreach (CompilerError err in info.Result.Errors)
if (!err.IsWarning)
Console.WriteLine("Error: " + err.ErrorText);
}
}
CSScript.CompilingHistory.Clear();
}
finally
{
CSScript.KeepCompilingHistory = false;
}
}
}
}
| |
/*
* MindTouch Dream - a distributed REST framework
* Copyright (C) 2006-2011 MindTouch, Inc.
* www.mindtouch.com oss@mindtouch.com
*
* For community documentation and downloads visit wiki.developer.mindtouch.com;
* please review the licensing section.
*
* 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.IO;
using System.Text;
using log4net;
using MindTouch.Dream.Test;
using MindTouch.Tasking;
using MindTouch.Xml;
using NUnit.Framework;
namespace MindTouch.Dream.Storage.Test {
using Yield = IEnumerator<IYield>;
[TestFixture]
public class PrivateStorageTests {
//--- Constants ---
private const string TEST_PATH = "private-storage-proxy";
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
//--- Fields ---
private Plug testService;
private DreamHostInfo _hostInfo;
private string _folder;
private string _storageFolder;
[TestFixtureSetUp]
public void Init() {
_folder = Path.GetTempPath();
Directory.CreateDirectory(_folder);
_storageFolder = Path.Combine(Path.GetTempPath(), StringUtil.CreateAlphaNumericKey(6));
Directory.CreateDirectory(_storageFolder);
XDoc config = new XDoc("config").Elem("service-dir", _folder);
_hostInfo = DreamTestHelper.CreateRandomPortHost(config);
CreatePrivateStorageServiceProxy();
}
[TearDown]
public void DeinitTest() {
System.GC.Collect();
}
[TestFixtureTearDown]
public void TearDown() {
_hostInfo.Dispose();
Directory.Delete(_storageFolder, true);
}
[Test]
public void Can_init() {
}
[Test]
public void Can_create_two_services_with_private_storage() {
_log.Debug("start test");
CreateSecondPrivateStorageServiceProxy();
}
[Test]
public void Service_can_store_and_retrieve_file() {
DreamMessage response = testService.AtPath("create-retrieve-delete").PostAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
}
[Test]
public void Service_can_store_and_retrieve_head() {
DreamMessage response = testService.AtPath("create-retrievehead-delete").PostAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
}
[Test]
public void Service_storage_will_expire_file() {
DreamMessage response = testService.AtPath("create-expire").PostAsync().Wait();
Assert.IsTrue(response.IsSuccessful, response.ToText());
}
private void CreatePrivateStorageServiceProxy() {
_hostInfo.Host.Self.At("load").With("name", "test.mindtouch.storage").Post(DreamMessage.Ok());
_hostInfo.Host.Self.At("services").Post(
new XDoc("config")
.Elem("class", typeof(TestServiceWithPrivateStorage).FullName)
.Elem("path", TEST_PATH));
testService = Plug.New(_hostInfo.Host.LocalMachineUri).At(TEST_PATH);
}
private void CreateSecondPrivateStorageServiceProxy() {
_hostInfo.Host.Self.At("services").Post(
new XDoc("config")
.Elem("class", typeof(TestServiceWithPrivateStorage).FullName)
.Elem("path", TEST_PATH + "2"));
_log.Debug("created second storage service");
testService = Plug.New(_hostInfo.Host.LocalMachineUri).At(TEST_PATH + "2");
}
}
[DreamService("TestServiceWithPrivateStorage", "Copyright (c) 2008 MindTouch, Inc.",
Info = "",
SID = new[] { "sid://mindtouch.com/TestServiceWithPrivateStorage" }
)]
[DreamServiceBlueprint("setup/private-storage")]
public class TestServiceWithPrivateStorage : DreamService {
//--- Constants ---
private const string TEST_CONTENTS = "Sample content";
private const string TEST_FILE_URI = "testfile";
//--- Class Fields ---
private static readonly ILog _log = LogUtils.CreateLog();
[DreamFeature("POST:create-retrieve-delete", "Create and retrieve test")]
public Yield TestCreateRetrieveDelete(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
string filename = Path.GetTempFileName();
using(Stream s = File.OpenWrite(filename)) {
byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
s.Write(data, 0, data.Length);
}
_log.Debug("created file");
// add a file
Storage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false));
File.Delete(filename);
_log.Debug("put file");
// get file and compare contents
string contents = Storage.AtPath(TEST_FILE_URI).Get().ToText();
Assert.AreEqual(TEST_CONTENTS, contents);
_log.Debug("got file");
// delete file
Storage.AtPath(TEST_FILE_URI).Delete();
_log.Debug("deleted file");
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("POST:create-retrievehead-delete", "Create and retrieve head test")]
public Yield TestCreateRetrieveHeadDelete(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
string filename = Path.GetTempFileName();
using(Stream s = File.OpenWrite(filename)) {
byte[] data = Encoding.UTF8.GetBytes(TEST_CONTENTS);
s.Write(data, 0, data.Length);
}
_log.Debug("created file");
// add a file
Storage.AtPath(TEST_FILE_URI).Put(DreamMessage.FromFile(filename, false));
File.Delete(filename);
_log.Debug("put file");
// get file and compare contents
DreamMessage headResponse = Storage.AtPath(TEST_FILE_URI).Invoke(Verb.HEAD, DreamMessage.Ok());
Assert.AreEqual(TEST_CONTENTS.Length, headResponse.ContentLength);
_log.Debug("got content length");
// delete file
Storage.AtPath(TEST_FILE_URI).Delete();
_log.Debug("deleted file");
response.Return(DreamMessage.Ok());
yield break;
}
[DreamFeature("POST:create-expire", "Create and expire test")]
public Yield TestCreateTtlExpire(DreamContext context, DreamMessage request, Result<DreamMessage> response) {
// add a file
Storage.AtPath(TEST_FILE_URI).With("ttl", "2").Put(DreamMessage.Ok(MimeType.TEXT, TEST_CONTENTS));
_log.DebugFormat("File stored at: {0}", DateTime.UtcNow);
// get file and compare contents
string contents = Storage.AtPath(TEST_FILE_URI).Get().ToText();
Assert.AreEqual(TEST_CONTENTS, contents);
_log.DebugFormat("check file at: {0}", DateTime.UtcNow);
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));
// get file and compare contents
_log.DebugFormat("Checking for expired file at: {0}", DateTime.UtcNow);
DreamMessage getResponse = Storage.AtPath(TEST_FILE_URI).GetAsync().Wait();
Assert.AreEqual(DreamStatus.NotFound, getResponse.Status);
response.Return(DreamMessage.Ok());
yield break;
}
protected override Yield Start(XDoc config, Result result) {
yield return Coroutine.Invoke(base.Start, config, new Result());
result.Return();
}
}
}
| |
//
// ChangeTracker.cs
//
// Author:
// Zachary Gramana <zack@xamarin.com>
//
// Copyright (c) 2014 Xamarin Inc
// Copyright (c) 2014 .NET Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
// Copyright (c) 2014 Couchbase, Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Couchbase.Lite;
using Couchbase.Lite.Auth;
using Couchbase.Lite.Replicator;
using Couchbase.Lite.Util;
using Sharpen;
namespace Couchbase.Lite.Replicator
{
internal enum ChangeTrackerMode
{
OneShot,
LongPoll
}
/// <summary>
/// Reads the continuous-mode _changes feed of a database, and sends the
/// individual change entries to its client's changeTrackerReceivedChange()
/// </summary>
internal class ChangeTracker
{
const String Tag = "ChangeTracker";
const Int32 LongPollModeLimit = 5000;
private Int32 _heartbeatMilliseconds = 300000;
private Uri databaseURL;
private IChangeTrackerClient client;
private ChangeTrackerMode mode;
private Object lastSequenceID;
private Boolean includeConflicts;
private TaskFactory WorkExecutor;
private DateTime _startTime;
private ManualResetEventSlim _pauseWait = new ManualResetEventSlim(true);
private readonly object stopMutex = new object();
private HttpRequestMessage Request;
private String filterName;
private IDictionary<String, Object> filterParams;
private IList<String> docIDs;
internal ChangeTrackerBackoff backoff;
protected internal IDictionary<string, object> RequestHeaders;
private CancellationTokenSource tokenSource;
CancellationTokenSource changesFeedRequestTokenSource;
public bool Paused
{
get { return !_pauseWait.IsSet; }
set
{
if(value != Paused) {
if(value) {
_pauseWait.Reset();
} else {
_pauseWait.Set();
}
}
}
}
/// <summary>Set Authenticator for BASIC Authentication</summary>
public IAuthenticator Authenticator { get; set; }
public bool UsePost { get; set; }
public Exception Error { get; private set; }
public ChangeTracker(Uri databaseURL, ChangeTrackerMode mode, object lastSequenceID,
Boolean includeConflicts, IChangeTrackerClient client, TaskFactory workExecutor = null)
{
// does not work, do not use it.
this.databaseURL = databaseURL;
this.mode = mode;
this.includeConflicts = includeConflicts;
this.lastSequenceID = lastSequenceID;
this.client = client;
this.RequestHeaders = new Dictionary<string, object>();
this.tokenSource = new CancellationTokenSource();
WorkExecutor = workExecutor ?? Task.Factory;
}
public void SetFilterName(string filterName)
{
this.filterName = filterName;
}
public void SetFilterParams(IDictionary<String, Object> filterParams)
{
this.filterParams = filterParams;
}
public void SetClient(IChangeTrackerClient client)
{
this.client = client;
}
public string GetDatabaseName()
{
string result = null;
if (databaseURL != null)
{
result = databaseURL.AbsolutePath;
if (result != null)
{
int pathLastSlashPos = result.LastIndexOf('/');
if (pathLastSlashPos > 0)
{
result = result.Substring(pathLastSlashPos);
}
}
}
return result;
}
public string GetChangesFeedPath()
{
if (UsePost)
{
return "_changes";
}
var path = new StringBuilder("_changes?feed=");
path.Append(GetFeed());
if (mode == ChangeTrackerMode.LongPoll)
{
path.Append(string.Format("&limit={0}", LongPollModeLimit));
}
path.Append(string.Format("&heartbeat={0}", _heartbeatMilliseconds));
if (includeConflicts)
{
path.Append("&style=all_docs");
}
if (lastSequenceID != null)
{
path.Append("&since=");
path.Append(Uri.EscapeUriString(lastSequenceID.ToString()));
}
if (docIDs != null && docIDs.Count > 0)
{
filterName = "_doc_ids";
filterParams = new Dictionary<string, object>();
filterParams.Put("doc_ids", docIDs);
}
if (filterName != null)
{
path.Append("&filter=");
path.Append(Uri.EscapeUriString(filterName));
if (filterParams != null)
{
foreach (string filterParamKey in filterParams.Keys)
{
var value = filterParams.Get(filterParamKey);
if (!(value is string))
{
try
{
value = Manager.GetObjectMapper().WriteValueAsString(value);
}
catch (IOException e)
{
throw new InvalidOperationException("Unable to JSON-serialize a filter parameter value.", e);
}
}
path.Append("&");
path.Append(Uri.EscapeUriString(filterParamKey));
path.Append("=");
path.Append(Uri.EscapeUriString(value.ToString()));
}
}
}
return path.ToString();
}
public Uri GetChangesFeedURL()
{
var dbURLString = databaseURL.ToString();
if (!dbURLString.EndsWith ("/", StringComparison.Ordinal))
{
dbURLString += "/";
}
dbURLString += GetChangesFeedPath();
Uri result = null;
try
{
result = new Uri(dbURLString);
}
catch (UriFormatException e)
{
Log.E(Tag, "Changes feed ULR is malformed", e);
}
return result;
}
// TODO: Needs to refactored into smaller calls. Each continuation could be its own method, for example.
public void Run()
{
IsRunning = true;
var clientCopy = client;
if (clientCopy == null)
{
// This is a race condition that can be reproduced by calling cbpuller.start() and cbpuller.stop()
// directly afterwards. What happens is that by the time the Changetracker thread fires up,
// the cbpuller has already set this.client to null. See issue #109
Log.W(Tag, "ChangeTracker run() loop aborting because client == null");
return;
}
if (tokenSource.IsCancellationRequested) {
tokenSource.Dispose();
tokenSource = new CancellationTokenSource();
}
backoff = new ChangeTrackerBackoff();
while (IsRunning && !tokenSource.Token.IsCancellationRequested)
{
_startTime = DateTime.Now;
if (Request != null)
{
Request.Dispose();
Request = null;
}
var url = GetChangesFeedURL();
if (UsePost)
{
Request = new HttpRequestMessage(HttpMethod.Post, url);
var body = GetChangesFeedPostBody();
Request.Content = new StringContent(body);
Request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
else
{
Request = new HttpRequestMessage(HttpMethod.Get, url);
}
AddRequestHeaders(Request);
var maskedRemoteWithoutCredentials = url.ToString();
maskedRemoteWithoutCredentials = maskedRemoteWithoutCredentials.ReplaceAll("://.*:.*@", "://---:---@");
Log.V(Tag, "Making request to " + maskedRemoteWithoutCredentials);
if (tokenSource.Token.IsCancellationRequested)
{
break;
}
Task<HttpResponseMessage> changesRequestTask = null;
Task successHandler;
Task errorHandler;
HttpClient httpClient = null;
try {
httpClient = clientCopy.GetHttpClient(mode == ChangeTrackerMode.LongPoll);
var challengeResponseAuth = Authenticator as IChallengeResponseAuthenticator;
if(challengeResponseAuth != null) {
challengeResponseAuth.PrepareWithRequest(Request);
}
var authHeader = AuthUtils.GetAuthenticationHeaderValue(Authenticator, Request.RequestUri);
if (authHeader != null)
{
httpClient.DefaultRequestHeaders.Authorization = authHeader;
}
changesFeedRequestTokenSource = CancellationTokenSource.CreateLinkedTokenSource(tokenSource.Token);
var option = mode == ChangeTrackerMode.LongPoll ? HttpCompletionOption.ResponseHeadersRead : HttpCompletionOption.ResponseContentRead;
var info = httpClient.SendAsync(
Request,
option,
changesFeedRequestTokenSource.Token
);
successHandler = info.ContinueWith(
ChangeFeedResponseHandler,
changesFeedRequestTokenSource.Token,
TaskContinuationOptions.LongRunning | TaskContinuationOptions.OnlyOnRanToCompletion,
WorkExecutor.Scheduler
);
errorHandler = info.ContinueWith(t =>
{
if (t.IsCanceled)
{
return; // Not a real error.
}
var err = t.Exception.Flatten();
Log.D(Tag, "ChangeFeedResponseHandler faulted.", err.InnerException ?? err);
Error = err.InnerException ?? err;
backoff.SleepAppropriateAmountOfTime();
}, changesFeedRequestTokenSource.Token, TaskContinuationOptions.NotOnRanToCompletion, WorkExecutor.Scheduler);
try
{
Task.WaitAll(successHandler, errorHandler);
Log.D(Tag, "Finished processing changes feed.");
}
catch (Exception ex) {
// Swallow TaskCancelledExceptions, which will always happen
// if either errorHandler or successHandler don't need to fire.
if (!(ex is OperationCanceledException) && !(ex.InnerException is OperationCanceledException)) {
throw ex;
}
}
finally
{
if (changesRequestTask != null)
{
if(changesRequestTask.IsCompleted)
{
changesRequestTask.Dispose();
}
changesRequestTask = null;
}
if (successHandler != null)
{
if(successHandler.IsCompleted)
{
successHandler.Dispose();
}
successHandler = null;
}
if (errorHandler != null)
{
if(errorHandler.IsCompleted)
{
errorHandler.Dispose();
}
errorHandler = null;
}
if(Request != null)
{
Request.Dispose();
Request = null;
}
if(changesFeedRequestTokenSource != null)
{
changesFeedRequestTokenSource.Dispose();
changesFeedRequestTokenSource = null;
}
}
}
catch (Exception e)
{
if (!IsRunning && e.InnerException is IOException)
{
// swallow
}
else
{
// in this case, just silently absorb the exception because it
// frequently happens when we're shutting down and have to
// close the socket underneath our read.
Log.E(Tag, "Exception in change tracker", e);
}
backoff.SleepAppropriateAmountOfTime();
}
finally
{
if (httpClient != null)
{
httpClient.Dispose();
}
}
}
}
void ChangeFeedResponseHandler(Task<HttpResponseMessage> responseTask)
{
var response = responseTask.Result;
if (response == null)
return;
var status = response.StatusCode;
if ((Int32)status >= 300 && !Misc.IsTransientError(status))
{
var msg = response.Content != null
? String.Format("Change tracker got error with status code: {0}", status)
: String.Format("Change tracker got error with status code: {0} and null response content", status);
Log.E(Tag, msg);
Error = new CouchbaseLiteException (msg, new Status (status.GetStatusCode ()));
Stop();
return;
}
switch (mode)
{
case ChangeTrackerMode.LongPoll:
{
if (response.Content == null) {
throw new CouchbaseLiteException("Got empty change tracker response", status.GetStatusCode());
}
var stream = response.Content.ReadAsStreamAsync().Result;
bool beforeFirstItem = true;
bool responseOK = false;
using (var jsonReader = Manager.GetObjectMapper().StartIncrementalParse(stream)) {
responseOK = ReceivedPollResponse(jsonReader, ref beforeFirstItem);
}
if (responseOK) {
Log.V(Tag, "Starting new longpoll");
backoff.ResetBackoff();
} else {
backoff.SleepAppropriateAmountOfTime();
var elapsed = DateTime.Now - _startTime;
Log.W(Tag, "Longpoll connection closed (by proxy?) after {0} sec", elapsed.TotalSeconds);
if (elapsed.TotalSeconds >= 30) {
// Looks like the connection got closed by a proxy (like AWS' load balancer) while the
// server was waiting for a change to send, due to lack of activity.
// Lower the heartbeat time to work around this, and reconnect:
_heartbeatMilliseconds = (int)(elapsed.TotalMilliseconds * 0.75f);
Log.V(Tag, " Starting new longpoll");
backoff.ResetBackoff();
} else {
Log.W(Tag, "Change tracker calling stop");
Stop();
}
}
}
break;
default:
{
var content = response.Content.ReadAsStreamAsync().Result;
using (var jsonReader = Manager.GetObjectMapper().StartIncrementalParse(content)) {
bool timedOut = false;
ReceivedPollResponse(jsonReader, ref timedOut);
}
WorkExecutor.StartNew(Stop);
}
break;
}
backoff.ResetBackoff();
}
public bool ReceivedChange(IDictionary<string, object> change)
{
var seq = change.Get("seq");
if (seq == null) {
return false;
}
//pass the change to the client on the thread that created this change tracker
if (client != null) {
Log.D(Tag, "changed tracker posting change");
client.ChangeTrackerReceivedChange(change);
}
lastSequenceID = seq;
return true;
}
public bool ReceivedPollResponse(IJsonSerializer jsonReader, ref bool timedOut)
{
bool started = false;
timedOut = true;
while (jsonReader.Read()) {
_pauseWait.Wait();
if (jsonReader.CurrentToken == JsonToken.StartArray) {
started = true;
} else if (jsonReader.CurrentToken == JsonToken.EndArray) {
started = false;
} else if (started) {
IDictionary<string, object> change;
try {
change = jsonReader.DeserializeNextObject();
} catch(Exception e) {
var ex = e as CouchbaseLiteException;
if (ex == null || ex.Code != StatusCode.BadJson) {
Log.E(Tag, "Failure during change tracker JSON parsing", e);
throw;
}
return false;
}
if (!ReceivedChange(change)) {
Log.W(Tag, String.Format("Received unparseable change line from server: {0}", change));
return false;
}
timedOut = false;
}
}
return true;
}
public void SetUpstreamError(string message)
{
Log.W(Tag, this + string.Format(": Server error: {0}", message));
this.Error = new Exception(message);
}
Thread thread;
public bool Start()
{
if (IsRunning)
{
return false;
}
this.Error = null;
this.thread = new Thread(Run) { IsBackground = true, Name = "Change Tracker Thread" };
thread.Start();
return true;
}
public void Stop()
{
// Lock to prevent multiple calls to Stop() method from different
// threads (eg. one from ChangeTracker itself and one from any other
// consumers).
lock(stopMutex)
{
if (!IsRunning)
{
return;
}
Log.D(Tag, "changed tracker asked to stop");
IsRunning = false;
var feedTokenSource = changesFeedRequestTokenSource;
if (feedTokenSource != null && !feedTokenSource.IsCancellationRequested)
{
try {
feedTokenSource.Cancel();
}catch(ObjectDisposedException) {
//FIXME Run() will often dispose this token source right out from under us since it
//is running on a separate thread.
Log.W(Tag, "Race condition on changesFeedRequestTokenSource detected");
}catch(AggregateException e) {
if (e.InnerException is ObjectDisposedException) {
Log.W(Tag, "Race condition on changesFeedRequestTokenSource detected");
} else {
throw;
}
}
}
Stopped();
}
}
public void Stopped()
{
Log.D(Tag, "change tracker in stopped");
if (client != null)
{
Log.D(Tag, "posting stopped");
client.ChangeTrackerStopped(this);
}
client = null;
Log.D(Tag, "change tracker client should be null now");
}
public void SetDocIDs(IList<string> docIDs)
{
this.docIDs = docIDs;
}
public bool IsRunning
{
get; private set;
}
internal void SetRequestHeaders(IDictionary<String, Object> requestHeaders)
{
RequestHeaders = requestHeaders;
}
private void AddRequestHeaders(HttpRequestMessage request)
{
foreach (string requestHeaderKey in RequestHeaders.Keys)
{
request.Headers.Add(requestHeaderKey, RequestHeaders.Get(requestHeaderKey).ToString());
}
}
private string GetFeed()
{
switch (mode)
{
case ChangeTrackerMode.LongPoll:
return "longpoll";
default:
return "normal";
}
}
internal IDictionary<string, object> GetChangesFeedParams()
{
if (!UsePost)
{
return null;
}
if (docIDs != null && docIDs.Count > 0)
{
filterName = "_doc_ids";
filterParams = new Dictionary<string, object>();
filterParams.Put("doc_ids", docIDs);
}
var bodyParams = new Dictionary<string, object>();
bodyParams["feed"] = GetFeed();
bodyParams["heartbeat"] = _heartbeatMilliseconds;
if (includeConflicts)
{
bodyParams["style"] = "all_docs";
}
else
{
bodyParams["style"] = null;
}
if (lastSequenceID != null)
{
Int64 sequenceAsLong;
var success = Int64.TryParse(lastSequenceID.ToString(), out sequenceAsLong);
bodyParams["since"] = success ? sequenceAsLong : lastSequenceID;
}
if (mode == ChangeTrackerMode.LongPoll)
{
bodyParams["limit"] = LongPollModeLimit;
}
if (filterName != null)
{
bodyParams["filter"] = filterName;
bodyParams.PutAll(filterParams);
}
return bodyParams;
}
internal string GetChangesFeedPostBody()
{
var parameters = GetChangesFeedParams();
var mapper = Manager.GetObjectMapper();
var body = mapper.WriteValueAsString(parameters);
return body;
}
}
}
| |
// 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 gaxgrpc = Google.Api.Gax.Grpc;
using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore;
using proto = Google.Protobuf;
using grpccore = Grpc.Core;
using grpcinter = Grpc.Core.Interceptors;
using sys = System;
using scg = System.Collections.Generic;
using sco = System.Collections.ObjectModel;
using st = System.Threading;
using stt = System.Threading.Tasks;
namespace Google.Ads.GoogleAds.V9.Services
{
/// <summary>Settings for <see cref="UserDataServiceClient"/> instances.</summary>
public sealed partial class UserDataServiceSettings : gaxgrpc::ServiceSettingsBase
{
/// <summary>Get a new instance of the default <see cref="UserDataServiceSettings"/>.</summary>
/// <returns>A new instance of the default <see cref="UserDataServiceSettings"/>.</returns>
public static UserDataServiceSettings GetDefault() => new UserDataServiceSettings();
/// <summary>Constructs a new <see cref="UserDataServiceSettings"/> object with default settings.</summary>
public UserDataServiceSettings()
{
}
private UserDataServiceSettings(UserDataServiceSettings existing) : base(existing)
{
gax::GaxPreconditions.CheckNotNull(existing, nameof(existing));
UploadUserDataSettings = existing.UploadUserDataSettings;
OnCopy(existing);
}
partial void OnCopy(UserDataServiceSettings existing);
/// <summary>
/// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to
/// <c>UserDataServiceClient.UploadUserData</c> and <c>UserDataServiceClient.UploadUserDataAsync</c>.
/// </summary>
/// <remarks>
/// <list type="bullet">
/// <item><description>Initial retry delay: 5000 milliseconds.</description></item>
/// <item><description>Retry delay multiplier: 1.3</description></item>
/// <item><description>Retry maximum delay: 60000 milliseconds.</description></item>
/// <item><description>Maximum attempts: Unlimited</description></item>
/// <item>
/// <description>
/// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>,
/// <see cref="grpccore::StatusCode.DeadlineExceeded"/>.
/// </description>
/// </item>
/// <item><description>Timeout: 3600 seconds.</description></item>
/// </list>
/// </remarks>
public gaxgrpc::CallSettings UploadUserDataSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded)));
/// <summary>Creates a deep clone of this object, with all the same property values.</summary>
/// <returns>A deep clone of this <see cref="UserDataServiceSettings"/> object.</returns>
public UserDataServiceSettings Clone() => new UserDataServiceSettings(this);
}
/// <summary>
/// Builder class for <see cref="UserDataServiceClient"/> to provide simple configuration of credentials, endpoint
/// etc.
/// </summary>
internal sealed partial class UserDataServiceClientBuilder : gaxgrpc::ClientBuilderBase<UserDataServiceClient>
{
/// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary>
public UserDataServiceSettings Settings { get; set; }
/// <summary>Creates a new builder with default settings.</summary>
public UserDataServiceClientBuilder()
{
UseJwtAccessWithScopes = UserDataServiceClient.UseJwtAccessWithScopes;
}
partial void InterceptBuild(ref UserDataServiceClient client);
partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<UserDataServiceClient> task);
/// <summary>Builds the resulting client.</summary>
public override UserDataServiceClient Build()
{
UserDataServiceClient client = null;
InterceptBuild(ref client);
return client ?? BuildImpl();
}
/// <summary>Builds the resulting client asynchronously.</summary>
public override stt::Task<UserDataServiceClient> BuildAsync(st::CancellationToken cancellationToken = default)
{
stt::Task<UserDataServiceClient> task = null;
InterceptBuildAsync(cancellationToken, ref task);
return task ?? BuildAsyncImpl(cancellationToken);
}
private UserDataServiceClient BuildImpl()
{
Validate();
grpccore::CallInvoker callInvoker = CreateCallInvoker();
return UserDataServiceClient.Create(callInvoker, Settings);
}
private async stt::Task<UserDataServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken)
{
Validate();
grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false);
return UserDataServiceClient.Create(callInvoker, Settings);
}
/// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary>
protected override string GetDefaultEndpoint() => UserDataServiceClient.DefaultEndpoint;
/// <summary>
/// Returns the default scopes for this builder type, used if no scopes are otherwise specified.
/// </summary>
protected override scg::IReadOnlyList<string> GetDefaultScopes() => UserDataServiceClient.DefaultScopes;
/// <summary>Returns the channel pool to use when no other options are specified.</summary>
protected override gaxgrpc::ChannelPool GetChannelPool() => UserDataServiceClient.ChannelPool;
/// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary>
protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance;
}
/// <summary>UserDataService client wrapper, for convenient use.</summary>
/// <remarks>
/// Service to manage user data uploads.
/// </remarks>
public abstract partial class UserDataServiceClient
{
/// <summary>
/// The default endpoint for the UserDataService service, which is a host of "googleads.googleapis.com" and a
/// port of 443.
/// </summary>
public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443";
/// <summary>The default UserDataService scopes.</summary>
/// <remarks>
/// The default UserDataService scopes are:
/// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list>
/// </remarks>
public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[]
{
"https://www.googleapis.com/auth/adwords",
});
internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes);
internal static bool UseJwtAccessWithScopes
{
get
{
bool useJwtAccessWithScopes = true;
MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes);
return useJwtAccessWithScopes;
}
}
static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes);
/// <summary>
/// Asynchronously creates a <see cref="UserDataServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="UserDataServiceClientBuilder"/>.
/// </summary>
/// <param name="cancellationToken">
/// The <see cref="st::CancellationToken"/> to use while creating the client.
/// </param>
/// <returns>The task representing the created <see cref="UserDataServiceClient"/>.</returns>
public static stt::Task<UserDataServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) =>
new UserDataServiceClientBuilder().BuildAsync(cancellationToken);
/// <summary>
/// Synchronously creates a <see cref="UserDataServiceClient"/> using the default credentials, endpoint and
/// settings. To specify custom credentials or other settings, use <see cref="UserDataServiceClientBuilder"/>.
/// </summary>
/// <returns>The created <see cref="UserDataServiceClient"/>.</returns>
public static UserDataServiceClient Create() => new UserDataServiceClientBuilder().Build();
/// <summary>
/// Creates a <see cref="UserDataServiceClient"/> which uses the specified call invoker for remote operations.
/// </summary>
/// <param name="callInvoker">
/// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.
/// </param>
/// <param name="settings">Optional <see cref="UserDataServiceSettings"/>.</param>
/// <returns>The created <see cref="UserDataServiceClient"/>.</returns>
internal static UserDataServiceClient Create(grpccore::CallInvoker callInvoker, UserDataServiceSettings settings = null)
{
gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker));
grpcinter::Interceptor interceptor = settings?.Interceptor;
if (interceptor != null)
{
callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor);
}
UserDataService.UserDataServiceClient grpcClient = new UserDataService.UserDataServiceClient(callInvoker);
return new UserDataServiceClientImpl(grpcClient, settings);
}
/// <summary>
/// Shuts down any channels automatically created by <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not
/// affected.
/// </summary>
/// <remarks>
/// After calling this method, further calls to <see cref="Create()"/> and
/// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down
/// by another call to this method.
/// </remarks>
/// <returns>A task representing the asynchronous shutdown operation.</returns>
public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync();
/// <summary>The underlying gRPC UserDataService client</summary>
public virtual UserDataService.UserDataServiceClient GrpcClient => throw new sys::NotImplementedException();
/// <summary>
/// Uploads the given user data.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// [UserDataError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public virtual UploadUserDataResponse UploadUserData(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Uploads the given user data.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// [UserDataError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null) =>
throw new sys::NotImplementedException();
/// <summary>
/// Uploads the given user data.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// [UserDataError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param>
/// <returns>A Task containing the RPC response.</returns>
public virtual stt::Task<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, st::CancellationToken cancellationToken) =>
UploadUserDataAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken));
}
/// <summary>UserDataService client wrapper implementation, for convenient use.</summary>
/// <remarks>
/// Service to manage user data uploads.
/// </remarks>
public sealed partial class UserDataServiceClientImpl : UserDataServiceClient
{
private readonly gaxgrpc::ApiCall<UploadUserDataRequest, UploadUserDataResponse> _callUploadUserData;
/// <summary>
/// Constructs a client wrapper for the UserDataService service, with the specified gRPC client and settings.
/// </summary>
/// <param name="grpcClient">The underlying gRPC client.</param>
/// <param name="settings">The base <see cref="UserDataServiceSettings"/> used within this client.</param>
public UserDataServiceClientImpl(UserDataService.UserDataServiceClient grpcClient, UserDataServiceSettings settings)
{
GrpcClient = grpcClient;
UserDataServiceSettings effectiveSettings = settings ?? UserDataServiceSettings.GetDefault();
gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings);
_callUploadUserData = clientHelper.BuildApiCall<UploadUserDataRequest, UploadUserDataResponse>(grpcClient.UploadUserDataAsync, grpcClient.UploadUserData, effectiveSettings.UploadUserDataSettings).WithGoogleRequestParam("customer_id", request => request.CustomerId);
Modify_ApiCall(ref _callUploadUserData);
Modify_UploadUserDataApiCall(ref _callUploadUserData);
OnConstruction(grpcClient, effectiveSettings, clientHelper);
}
partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>;
partial void Modify_UploadUserDataApiCall(ref gaxgrpc::ApiCall<UploadUserDataRequest, UploadUserDataResponse> call);
partial void OnConstruction(UserDataService.UserDataServiceClient grpcClient, UserDataServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper);
/// <summary>The underlying gRPC UserDataService client</summary>
public override UserDataService.UserDataServiceClient GrpcClient { get; }
partial void Modify_UploadUserDataRequest(ref UploadUserDataRequest request, ref gaxgrpc::CallSettings settings);
/// <summary>
/// Uploads the given user data.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// [UserDataError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>The RPC response.</returns>
public override UploadUserDataResponse UploadUserData(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadUserDataRequest(ref request, ref callSettings);
return _callUploadUserData.Sync(request, callSettings);
}
/// <summary>
/// Uploads the given user data.
///
/// List of thrown errors:
/// [AuthenticationError]()
/// [AuthorizationError]()
/// [CollectionSizeError]()
/// [FieldError]()
/// [HeaderError]()
/// [InternalError]()
/// [MutateError]()
/// [OfflineUserDataJobError]()
/// [QuotaError]()
/// [RequestError]()
/// [UserDataError]()
/// </summary>
/// <param name="request">The request object containing all of the parameters for the API call.</param>
/// <param name="callSettings">If not null, applies overrides to this RPC call.</param>
/// <returns>A Task containing the RPC response.</returns>
public override stt::Task<UploadUserDataResponse> UploadUserDataAsync(UploadUserDataRequest request, gaxgrpc::CallSettings callSettings = null)
{
Modify_UploadUserDataRequest(ref request, ref callSettings);
return _callUploadUserData.Async(request, callSettings);
}
}
}
| |
// 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.
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by google-apis-code-generator 1.5.1
// C# generator version: 1.27.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
/**
* \brief
* Admin Reports API Version reports_v1
*
* \section ApiInfo API Version Information
* <table>
* <tr><th>API
* <td><a href='https://developers.google.com/admin-sdk/reports/'>Admin Reports API</a>
* <tr><th>API Version<td>reports_v1
* <tr><th>API Rev<td>20170622 (903)
* <tr><th>API Docs
* <td><a href='https://developers.google.com/admin-sdk/reports/'>
* https://developers.google.com/admin-sdk/reports/</a>
* <tr><th>Discovery Name<td>admin
* </table>
*
* \section ForMoreInfo For More Information
*
* The complete API documentation for using Admin Reports API can be found at
* <a href='https://developers.google.com/admin-sdk/reports/'>https://developers.google.com/admin-sdk/reports/</a>.
*
* For more information about the Google APIs Client Library for .NET, see
* <a href='https://developers.google.com/api-client-library/dotnet/get_started'>
* https://developers.google.com/api-client-library/dotnet/get_started</a>
*/
namespace Google.Apis.Admin.Reports.reports_v1
{
/// <summary>The Reports Service.</summary>
public class ReportsService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "reports_v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed =
Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public ReportsService() :
this(new Google.Apis.Services.BaseClientService.Initializer()) {}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public ReportsService(Google.Apis.Services.BaseClientService.Initializer initializer)
: base(initializer)
{
activities = new ActivitiesResource(this);
channels = new ChannelsResource(this);
customerUsageReports = new CustomerUsageReportsResource(this);
userUsageReport = new UserUsageReportResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features
{
get { return new string[0]; }
}
/// <summary>Gets the service name.</summary>
public override string Name
{
get { return "admin"; }
}
/// <summary>Gets the service base URI.</summary>
public override string BaseUri
{
get { return "https://www.googleapis.com/admin/reports/v1/"; }
}
/// <summary>Gets the service base path.</summary>
public override string BasePath
{
get { return "admin/reports/v1/"; }
}
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri
{
get { return "https://www.googleapis.com/batch"; }
}
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath
{
get { return "batch"; }
}
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Admin Reports API.</summary>
public class Scope
{
/// <summary>View audit reports for your G Suite domain</summary>
public static string AdminReportsAuditReadonly = "https://www.googleapis.com/auth/admin.reports.audit.readonly";
/// <summary>View usage reports for your G Suite domain</summary>
public static string AdminReportsUsageReadonly = "https://www.googleapis.com/auth/admin.reports.usage.readonly";
}
private readonly ActivitiesResource activities;
/// <summary>Gets the Activities resource.</summary>
public virtual ActivitiesResource Activities
{
get { return activities; }
}
private readonly ChannelsResource channels;
/// <summary>Gets the Channels resource.</summary>
public virtual ChannelsResource Channels
{
get { return channels; }
}
private readonly CustomerUsageReportsResource customerUsageReports;
/// <summary>Gets the CustomerUsageReports resource.</summary>
public virtual CustomerUsageReportsResource CustomerUsageReports
{
get { return customerUsageReports; }
}
private readonly UserUsageReportResource userUsageReport;
/// <summary>Gets the UserUsageReport resource.</summary>
public virtual UserUsageReportResource UserUsageReport
{
get { return userUsageReport; }
}
}
///<summary>A base abstract class for Reports requests.</summary>
public abstract class ReportsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
///<summary>Constructs a new ReportsBaseServiceRequest instance.</summary>
protected ReportsBaseServiceRequest(Google.Apis.Services.IClientService service)
: base(service)
{
}
/// <summary>Data format for the response.</summary>
/// [default: json]
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports.
/// Required unless you provide an OAuth 2.0 token.</summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
/// [default: true]
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string
/// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user
/// limits.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Reports parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add(
"fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add(
"quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "activities" collection of methods.</summary>
public class ActivitiesResource
{
private const string Resource = "activities";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ActivitiesResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves a list of activities for a specific customer and application.</summary>
/// <param name="userKey">Represents the profile id or the user email for which the data should be filtered. When 'all'
/// is specified as the userKey, it returns usageReports for all users.</param>
/// <param
/// name="applicationName">Application name for which the events are to be retrieved.</param>
public virtual ListRequest List(string userKey, string applicationName)
{
return new ListRequest(service, userKey, applicationName);
}
/// <summary>Retrieves a list of activities for a specific customer and application.</summary>
public class ListRequest : ReportsBaseServiceRequest<Google.Apis.Admin.Reports.reports_v1.Data.Activities>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string userKey, string applicationName)
: base(service)
{
UserKey = userKey;
ApplicationName = applicationName;
InitParameters();
}
/// <summary>Represents the profile id or the user email for which the data should be filtered. When 'all'
/// is specified as the userKey, it returns usageReports for all users.</summary>
[Google.Apis.Util.RequestParameterAttribute("userKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserKey { get; private set; }
/// <summary>Application name for which the events are to be retrieved.</summary>
[Google.Apis.Util.RequestParameterAttribute("applicationName", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ApplicationName { get; private set; }
/// <summary>IP Address of host where the event was performed. Supports both IPv4 and IPv6
/// addresses.</summary>
[Google.Apis.Util.RequestParameterAttribute("actorIpAddress", Google.Apis.Util.RequestParameterType.Query)]
public virtual string ActorIpAddress { get; set; }
/// <summary>Represents the customer for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Return events which occurred at or before this time.</summary>
[Google.Apis.Util.RequestParameterAttribute("endTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EndTime { get; set; }
/// <summary>Name of the event being queried.</summary>
[Google.Apis.Util.RequestParameterAttribute("eventName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EventName { get; set; }
/// <summary>Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2
/// name][operator][parameter2 value],...</summary>
[Google.Apis.Util.RequestParameterAttribute("filters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filters { get; set; }
/// <summary>Number of activity records to be shown in each page.</summary>
/// [minimum: 1]
/// [maximum: 1000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>Token to specify next page.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Return events which occurred at or after this time.</summary>
[Google.Apis.Util.RequestParameterAttribute("startTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual string StartTime { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "list"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "activity/users/{userKey}/applications/{applicationName}"; }
}
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"userKey", new Google.Apis.Discovery.Parameter
{
Name = "userKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"applicationName", new Google.Apis.Discovery.Parameter
{
Name = "applicationName",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"(admin)|(calendar)|(drive)|(login)|(mobile)|(token)|(groups)|(saml)|(chat)|(gplus)|(rules)",
});
RequestParameters.Add(
"actorIpAddress", new Google.Apis.Discovery.Parameter
{
Name = "actorIpAddress",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"C.+",
});
RequestParameters.Add(
"endTime", new Google.Apis.Discovery.Parameter
{
Name = "endTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?(?:(Z)|([-+])(\d\d):(\d\d))",
});
RequestParameters.Add(
"eventName", new Google.Apis.Discovery.Parameter
{
Name = "eventName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filters", new Google.Apis.Discovery.Parameter
{
Name = "filters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)",
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startTime", new Google.Apis.Discovery.Parameter
{
Name = "startTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?(?:(Z)|([-+])(\d\d):(\d\d))",
});
}
}
/// <summary>Push changes to activities</summary>
/// <param name="body">The body of the request.</param>
/// <param name="userKey">Represents the profile id or the user email for which the data should be filtered. When 'all'
/// is specified as the userKey, it returns usageReports for all users.</param>
/// <param
/// name="applicationName">Application name for which the events are to be retrieved.</param>
public virtual WatchRequest Watch(Google.Apis.Admin.Reports.reports_v1.Data.Channel body, string userKey, string applicationName)
{
return new WatchRequest(service, body, userKey, applicationName);
}
/// <summary>Push changes to activities</summary>
public class WatchRequest : ReportsBaseServiceRequest<Google.Apis.Admin.Reports.reports_v1.Data.Channel>
{
/// <summary>Constructs a new Watch request.</summary>
public WatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Admin.Reports.reports_v1.Data.Channel body, string userKey, string applicationName)
: base(service)
{
UserKey = userKey;
ApplicationName = applicationName;
Body = body;
InitParameters();
}
/// <summary>Represents the profile id or the user email for which the data should be filtered. When 'all'
/// is specified as the userKey, it returns usageReports for all users.</summary>
[Google.Apis.Util.RequestParameterAttribute("userKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserKey { get; private set; }
/// <summary>Application name for which the events are to be retrieved.</summary>
[Google.Apis.Util.RequestParameterAttribute("applicationName", Google.Apis.Util.RequestParameterType.Path)]
public virtual string ApplicationName { get; private set; }
/// <summary>IP Address of host where the event was performed. Supports both IPv4 and IPv6
/// addresses.</summary>
[Google.Apis.Util.RequestParameterAttribute("actorIpAddress", Google.Apis.Util.RequestParameterType.Query)]
public virtual string ActorIpAddress { get; set; }
/// <summary>Represents the customer for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Return events which occurred at or before this time.</summary>
[Google.Apis.Util.RequestParameterAttribute("endTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EndTime { get; set; }
/// <summary>Name of the event being queried.</summary>
[Google.Apis.Util.RequestParameterAttribute("eventName", Google.Apis.Util.RequestParameterType.Query)]
public virtual string EventName { get; set; }
/// <summary>Event parameters in the form [parameter1 name][operator][parameter1 value],[parameter2
/// name][operator][parameter2 value],...</summary>
[Google.Apis.Util.RequestParameterAttribute("filters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filters { get; set; }
/// <summary>Number of activity records to be shown in each page.</summary>
/// [minimum: 1]
/// [maximum: 1000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> MaxResults { get; set; }
/// <summary>Token to specify next page.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Return events which occurred at or after this time.</summary>
[Google.Apis.Util.RequestParameterAttribute("startTime", Google.Apis.Util.RequestParameterType.Query)]
public virtual string StartTime { get; set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Admin.Reports.reports_v1.Data.Channel Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "watch"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "activity/users/{userKey}/applications/{applicationName}/watch"; }
}
/// <summary>Initializes Watch parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"userKey", new Google.Apis.Discovery.Parameter
{
Name = "userKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"applicationName", new Google.Apis.Discovery.Parameter
{
Name = "applicationName",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"(admin)|(calendar)|(drive)|(login)|(mobile)|(token)|(groups)|(saml)|(chat)|(gplus)|(rules)",
});
RequestParameters.Add(
"actorIpAddress", new Google.Apis.Discovery.Parameter
{
Name = "actorIpAddress",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"C.+",
});
RequestParameters.Add(
"endTime", new Google.Apis.Discovery.Parameter
{
Name = "endTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?(?:(Z)|([-+])(\d\d):(\d\d))",
});
RequestParameters.Add(
"eventName", new Google.Apis.Discovery.Parameter
{
Name = "eventName",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"filters", new Google.Apis.Discovery.Parameter
{
Name = "filters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(.+[<,<=,==,>=,>,<>].+,)*(.+[<,<=,==,>=,>,<>].+)",
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"startTime", new Google.Apis.Discovery.Parameter
{
Name = "startTime",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)(?:\.(\d+))?(?:(Z)|([-+])(\d\d):(\d\d))",
});
}
}
}
/// <summary>The "channels" collection of methods.</summary>
public class ChannelsResource
{
private const string Resource = "channels";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public ChannelsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Stop watching resources through this channel</summary>
/// <param name="body">The body of the request.</param>
public virtual StopRequest Stop(Google.Apis.Admin.Reports.reports_v1.Data.Channel body)
{
return new StopRequest(service, body);
}
/// <summary>Stop watching resources through this channel</summary>
public class StopRequest : ReportsBaseServiceRequest<string>
{
/// <summary>Constructs a new Stop request.</summary>
public StopRequest(Google.Apis.Services.IClientService service, Google.Apis.Admin.Reports.reports_v1.Data.Channel body)
: base(service)
{
Body = body;
InitParameters();
}
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.Admin.Reports.reports_v1.Data.Channel Body { get; set; }
///<summary>Returns the body of the request.</summary>
protected override object GetBody() { return Body; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "stop"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "POST"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "/admin/reports_v1/channels/stop"; }
}
/// <summary>Initializes Stop parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
/// <summary>The "customerUsageReports" collection of methods.</summary>
public class CustomerUsageReportsResource
{
private const string Resource = "customerUsageReports";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public CustomerUsageReportsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves a report which is a collection of properties / statistics for a specific
/// customer.</summary>
/// <param name="date">Represents the date in yyyy-mm-dd format for which the data is to be fetched.</param>
public virtual GetRequest Get(string date)
{
return new GetRequest(service, date);
}
/// <summary>Retrieves a report which is a collection of properties / statistics for a specific
/// customer.</summary>
public class GetRequest : ReportsBaseServiceRequest<Google.Apis.Admin.Reports.reports_v1.Data.UsageReports>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string date)
: base(service)
{
Date = date;
InitParameters();
}
/// <summary>Represents the date in yyyy-mm-dd format for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("date", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Date { get; private set; }
/// <summary>Represents the customer for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Token to specify next page.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1,
/// app_name2:param_name2.</summary>
[Google.Apis.Util.RequestParameterAttribute("parameters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Parameters { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "usage/dates/{date}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"date", new Google.Apis.Discovery.Parameter
{
Name = "date",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"(\d){4}-(\d){2}-(\d){2}",
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"C.+",
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"parameters", new Google.Apis.Discovery.Parameter
{
Name = "parameters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+,)*(((accounts)|(app_maker)|(apps_scripts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+)",
});
}
}
}
/// <summary>The "userUsageReport" collection of methods.</summary>
public class UserUsageReportResource
{
private const string Resource = "userUsageReport";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UserUsageReportResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>Retrieves a report which is a collection of properties / statistics for a set of users.</summary>
/// <param name="userKey">Represents the profile id or the user email for which the data should be
/// filtered.</param>
/// <param name="date">Represents the date in yyyy-mm-dd format for which the data is to be
/// fetched.</param>
public virtual GetRequest Get(string userKey, string date)
{
return new GetRequest(service, userKey, date);
}
/// <summary>Retrieves a report which is a collection of properties / statistics for a set of users.</summary>
public class GetRequest : ReportsBaseServiceRequest<Google.Apis.Admin.Reports.reports_v1.Data.UsageReports>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service, string userKey, string date)
: base(service)
{
UserKey = userKey;
Date = date;
InitParameters();
}
/// <summary>Represents the profile id or the user email for which the data should be filtered.</summary>
[Google.Apis.Util.RequestParameterAttribute("userKey", Google.Apis.Util.RequestParameterType.Path)]
public virtual string UserKey { get; private set; }
/// <summary>Represents the date in yyyy-mm-dd format for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("date", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Date { get; private set; }
/// <summary>Represents the customer for which the data is to be fetched.</summary>
[Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)]
public virtual string CustomerId { get; set; }
/// <summary>Represents the set of filters including parameter operator value.</summary>
[Google.Apis.Util.RequestParameterAttribute("filters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filters { get; set; }
/// <summary>Maximum number of results to return. Maximum allowed is 1000</summary>
/// [maximum: 1000]
[Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<long> MaxResults { get; set; }
/// <summary>Token to specify next page.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Represents the application name, parameter name pairs to fetch in csv as app_name1:param_name1,
/// app_name2:param_name2.</summary>
[Google.Apis.Util.RequestParameterAttribute("parameters", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Parameters { get; set; }
///<summary>Gets the method name.</summary>
public override string MethodName
{
get { return "get"; }
}
///<summary>Gets the HTTP method.</summary>
public override string HttpMethod
{
get { return "GET"; }
}
///<summary>Gets the REST path.</summary>
public override string RestPath
{
get { return "usage/users/{userKey}/dates/{date}"; }
}
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add(
"userKey", new Google.Apis.Discovery.Parameter
{
Name = "userKey",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"date", new Google.Apis.Discovery.Parameter
{
Name = "date",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"(\d){4}-(\d){2}-(\d){2}",
});
RequestParameters.Add(
"customerId", new Google.Apis.Discovery.Parameter
{
Name = "customerId",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"C.+",
});
RequestParameters.Add(
"filters", new Google.Apis.Discovery.Parameter
{
Name = "filters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[a-z0-9_]+[<,<=,==,>=,>,!=][^,]+)",
});
RequestParameters.Add(
"maxResults", new Google.Apis.Discovery.Parameter
{
Name = "maxResults",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add(
"parameters", new Google.Apis.Discovery.Parameter
{
Name = "parameters",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = @"(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+,)*(((accounts)|(classroom)|(cros)|(gmail)|(calendar)|(docs)|(gplus)|(sites)|(device_management)|(drive)):[^,]+)",
});
}
}
}
}
namespace Google.Apis.Admin.Reports.reports_v1.Data
{
/// <summary>JSON template for a collection of activites.</summary>
public class Activities : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Each record in read response.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("items")]
public virtual System.Collections.Generic.IList<Activity> Items { get; set; }
/// <summary>Kind of list response this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Token for retrieving the next page</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
}
/// <summary>JSON template for the activity resource.</summary>
public class Activity : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>User doing the action.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("actor")]
public virtual Activity.ActorData Actor { get; set; }
/// <summary>ETag of the entry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>Activity events.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("events")]
public virtual System.Collections.Generic.IList<Activity.EventsData> Events { get; set; }
/// <summary>Unique identifier for each activity record.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual Activity.IdData Id { get; set; }
/// <summary>IP Address of the user doing the action.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ipAddress")]
public virtual string IpAddress { get; set; }
/// <summary>Kind of resource this is.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Domain of source customer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("ownerDomain")]
public virtual string OwnerDomain { get; set; }
/// <summary>User doing the action.</summary>
public class ActorData
{
/// <summary>User or OAuth 2LO request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("callerType")]
public virtual string CallerType { get; set; }
/// <summary>Email address of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>For OAuth 2LO API requests, consumer_key of the requestor.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>Obfuscated user id of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profileId")]
public virtual string ProfileId { get; set; }
}
public class EventsData
{
/// <summary>Name of event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>Parameter value pairs for various applications.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<EventsData.ParametersData> Parameters { get; set; }
/// <summary>Type of event.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
public class ParametersData
{
/// <summary>Boolean value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("boolValue")]
public virtual System.Nullable<bool> BoolValue { get; set; }
/// <summary>Integral value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intValue")]
public virtual System.Nullable<long> IntValue { get; set; }
/// <summary>Multi-int value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("multiIntValue")]
public virtual System.Collections.Generic.IList<System.Nullable<long>> MultiIntValue { get; set; }
/// <summary>Multi-string value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("multiValue")]
public virtual System.Collections.Generic.IList<string> MultiValue { get; set; }
/// <summary>The name of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>String value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
}
}
/// <summary>Unique identifier for each activity record.</summary>
public class IdData
{
/// <summary>Application name to which the event belongs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("applicationName")]
public virtual string ApplicationName { get; set; }
/// <summary>Obfuscated customer ID of the source customer.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("customerId")]
public virtual string CustomerId { get; set; }
/// <summary>Time of occurrence of the activity.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("time")]
public virtual string TimeRaw { get; set; }
/// <summary><seealso cref="System.DateTime"/> representation of <see cref="TimeRaw"/>.</summary>
[Newtonsoft.Json.JsonIgnore]
public virtual System.Nullable<System.DateTime> Time
{
get
{
return Google.Apis.Util.Utilities.GetDateTimeFromString(TimeRaw);
}
set
{
TimeRaw = Google.Apis.Util.Utilities.GetStringFromDateTime(value);
}
}
/// <summary>Unique qualifier if multiple events have the same time.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("uniqueQualifier")]
public virtual System.Nullable<long> UniqueQualifier { get; set; }
}
}
/// <summary>An notification channel used to watch for resource changes.</summary>
public class Channel : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The address where notifications are delivered for this channel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("address")]
public virtual string Address { get; set; }
/// <summary>Date and time of notification channel expiration, expressed as a Unix timestamp, in milliseconds.
/// Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expiration")]
public virtual System.Nullable<long> Expiration { get; set; }
/// <summary>A UUID or similar unique string that identifies this channel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>Identifies this as a notification channel used to watch for changes to a resource. Value: the fixed
/// string "api#channel".</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Additional parameters controlling delivery channel behavior. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("params")]
public virtual System.Collections.Generic.IDictionary<string,string> Params__ { get; set; }
/// <summary>A Boolean value to indicate whether payload is wanted. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("payload")]
public virtual System.Nullable<bool> Payload { get; set; }
/// <summary>An opaque ID that identifies the resource being watched on this channel. Stable across different
/// API versions.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceId")]
public virtual string ResourceId { get; set; }
/// <summary>A version-specific identifier for the watched resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("resourceUri")]
public virtual string ResourceUri { get; set; }
/// <summary>An arbitrary string delivered to the target address with each notification delivered over this
/// channel. Optional.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("token")]
public virtual string Token { get; set; }
/// <summary>The type of delivery mechanism used for this channel.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>JSON template for a usage report.</summary>
public class UsageReport : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The date to which the record belongs.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("date")]
public virtual string Date { get; set; }
/// <summary>Information about the type of the item.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("entity")]
public virtual UsageReport.EntityData Entity { get; set; }
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The kind of object.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Parameter value pairs for various applications.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("parameters")]
public virtual System.Collections.Generic.IList<UsageReport.ParametersData> Parameters { get; set; }
/// <summary>Information about the type of the item.</summary>
public class EntityData
{
/// <summary>Obfuscated customer id for the record.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("customerId")]
public virtual string CustomerId { get; set; }
/// <summary>Obfuscated user id for the record.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("profileId")]
public virtual string ProfileId { get; set; }
/// <summary>The type of item, can be a customer or user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("type")]
public virtual string Type { get; set; }
/// <summary>user's email.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("userEmail")]
public virtual string UserEmail { get; set; }
}
public class ParametersData
{
/// <summary>Boolean value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("boolValue")]
public virtual System.Nullable<bool> BoolValue { get; set; }
/// <summary>RFC 3339 formatted value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("datetimeValue")]
public virtual string DatetimeValueRaw { get; set; }
/// <summary><seealso cref="System.DateTime"/> representation of <see cref="DatetimeValueRaw"/>.</summary>
[Newtonsoft.Json.JsonIgnore]
public virtual System.Nullable<System.DateTime> DatetimeValue
{
get
{
return Google.Apis.Util.Utilities.GetDateTimeFromString(DatetimeValueRaw);
}
set
{
DatetimeValueRaw = Google.Apis.Util.Utilities.GetStringFromDateTime(value);
}
}
/// <summary>Integral value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("intValue")]
public virtual System.Nullable<long> IntValue { get; set; }
/// <summary>Nested message value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("msgValue")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> MsgValue { get; set; }
/// <summary>The name of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>String value of the parameter.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("stringValue")]
public virtual string StringValue { get; set; }
}
}
/// <summary>JSON template for a collection of usage reports.</summary>
public class UsageReports : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>ETag of the resource.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("etag")]
public virtual string ETag { get; set; }
/// <summary>The kind of object.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("kind")]
public virtual string Kind { get; set; }
/// <summary>Token for retrieving the next page</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>Various application parameter records.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("usageReports")]
public virtual System.Collections.Generic.IList<UsageReport> UsageReportsValue { get; set; }
/// <summary>Warnings if any.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("warnings")]
public virtual System.Collections.Generic.IList<UsageReports.WarningsData> Warnings { get; set; }
public class WarningsData
{
/// <summary>Machine readable code / warning type.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual string Code { get; set; }
/// <summary>Key-Value pairs to give detailed information on the warning.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("data")]
public virtual System.Collections.Generic.IList<WarningsData.DataData> Data { get; set; }
/// <summary>Human readable message for the warning.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
public class DataData
{
/// <summary>Key associated with a key-value pair to give detailed information on the warning.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("key")]
public virtual string Key { get; set; }
/// <summary>Value associated with a key-value pair to give detailed information on the
/// warning.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("value")]
public virtual string Value { get; set; }
}
}
}
}
| |
using ClosedXML.Excel;
using NUnit.Framework;
using System;
namespace ClosedXML.Tests
{
[TestFixture]
public class XLRangeAddressTests
{
[Test]
public void ToStringTest()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet1");
IXLRangeAddress address = ws.Cell(1, 1).AsRange().RangeAddress;
Assert.AreEqual("A1:A1", address.ToString());
Assert.AreEqual("Sheet1!R1C1:R1C1", address.ToString(XLReferenceStyle.R1C1, true));
Assert.AreEqual("A1:A1", address.ToStringRelative());
Assert.AreEqual("Sheet1!A1:A1", address.ToStringRelative(true));
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed());
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.A1));
Assert.AreEqual("R1C1:R1C1", address.ToStringFixed(XLReferenceStyle.R1C1));
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.Default));
Assert.AreEqual("Sheet1!$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.A1, true));
Assert.AreEqual("Sheet1!R1C1:R1C1", address.ToStringFixed(XLReferenceStyle.R1C1, true));
Assert.AreEqual("Sheet1!$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.Default, true));
}
[Test]
public void ToStringTestWithSpace()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet 1");
IXLRangeAddress address = ws.Cell(1, 1).AsRange().RangeAddress;
Assert.AreEqual("A1:A1", address.ToString());
Assert.AreEqual("'Sheet 1'!R1C1:R1C1", address.ToString(XLReferenceStyle.R1C1, true));
Assert.AreEqual("A1:A1", address.ToStringRelative());
Assert.AreEqual("'Sheet 1'!A1:A1", address.ToStringRelative(true));
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed());
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.A1));
Assert.AreEqual("R1C1:R1C1", address.ToStringFixed(XLReferenceStyle.R1C1));
Assert.AreEqual("$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.Default));
Assert.AreEqual("'Sheet 1'!$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.A1, true));
Assert.AreEqual("'Sheet 1'!R1C1:R1C1", address.ToStringFixed(XLReferenceStyle.R1C1, true));
Assert.AreEqual("'Sheet 1'!$A$1:$A$1", address.ToStringFixed(XLReferenceStyle.Default, true));
}
[TestCase("B2:E5", "B2:E5")]
[TestCase("E5:B2", "B2:E5")]
[TestCase("B5:E2", "B2:E5")]
[TestCase("B2:E$5", "B2:E$5")]
[TestCase("B2:$E$5", "B2:$E$5")]
[TestCase("B$2:$E$5", "B$2:$E$5")]
[TestCase("$B$2:$E$5", "$B$2:$E$5")]
[TestCase("B5:E$2", "B$2:E5")]
[TestCase("$B$5:E2", "$B2:E$5")]
[TestCase("$B$5:E$2", "$B$2:E$5")]
[TestCase("$B$5:$E$2", "$B$2:$E$5")]
public void RangeAddressNormalizeTest(string inputAddress, string expectedAddress)
{
XLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet 1") as XLWorksheet;
var rangeAddress = new XLRangeAddress(ws, inputAddress);
var normalizedAddress = rangeAddress.Normalize();
Assert.AreSame(ws, rangeAddress.Worksheet);
Assert.AreEqual(expectedAddress, normalizedAddress.ToString());
}
[Test]
public void InvalidRangeAddressToStringTest()
{
var address = ProduceInvalidAddress();
Assert.AreEqual("#REF!", address.ToString());
Assert.AreEqual("#REF!", address.ToString(XLReferenceStyle.A1));
Assert.AreEqual("#REF!", address.ToString(XLReferenceStyle.Default));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToString(XLReferenceStyle.R1C1));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToString(XLReferenceStyle.A1, true));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToString(XLReferenceStyle.Default, true));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToString(XLReferenceStyle.R1C1, true));
}
[Test]
public void InvalidRangeAddressToStringFixedTest()
{
var address = ProduceInvalidAddress();
Assert.AreEqual("#REF!", address.ToStringFixed());
Assert.AreEqual("#REF!", address.ToStringFixed(XLReferenceStyle.A1));
Assert.AreEqual("#REF!", address.ToStringFixed(XLReferenceStyle.Default));
Assert.AreEqual("#REF!", address.ToStringFixed(XLReferenceStyle.R1C1));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToStringFixed(XLReferenceStyle.A1, true));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToStringFixed(XLReferenceStyle.Default, true));
Assert.AreEqual("'Sheet 1'!#REF!", address.ToStringFixed(XLReferenceStyle.R1C1, true));
}
[Test]
public void InvalidRangeAddressToStringRelativeTest()
{
var address = ProduceInvalidAddress();
Assert.AreEqual("#REF!", address.ToStringRelative());
Assert.AreEqual("'Sheet 1'!#REF!", address.ToStringRelative(true));
}
[Test]
public void RangeAddressOnDeletedWorksheetToStringTest()
{
var address = ProduceAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!A1:B2", address.ToString());
Assert.AreEqual("#REF!A1:B2", address.ToString(XLReferenceStyle.A1));
Assert.AreEqual("#REF!A1:B2", address.ToString(XLReferenceStyle.Default));
Assert.AreEqual("#REF!R1C1:R2C2", address.ToString(XLReferenceStyle.R1C1));
Assert.AreEqual("#REF!A1:B2", address.ToString(XLReferenceStyle.A1, true));
Assert.AreEqual("#REF!A1:B2", address.ToString(XLReferenceStyle.Default, true));
Assert.AreEqual("#REF!R1C1:R2C2", address.ToString(XLReferenceStyle.R1C1, true));
}
[Test]
public void RangeAddressOnDeletedWorksheetToStringFixedTest()
{
var address = ProduceAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!$A$1:$B$2", address.ToStringFixed());
Assert.AreEqual("#REF!$A$1:$B$2", address.ToStringFixed(XLReferenceStyle.A1));
Assert.AreEqual("#REF!$A$1:$B$2", address.ToStringFixed(XLReferenceStyle.Default));
Assert.AreEqual("#REF!R1C1:R2C2", address.ToStringFixed(XLReferenceStyle.R1C1));
Assert.AreEqual("#REF!$A$1:$B$2", address.ToStringFixed(XLReferenceStyle.A1, true));
Assert.AreEqual("#REF!$A$1:$B$2", address.ToStringFixed(XLReferenceStyle.Default, true));
Assert.AreEqual("#REF!R1C1:R2C2", address.ToStringFixed(XLReferenceStyle.R1C1, true));
}
[Test]
public void RangeAddressOnDeletedWorksheetToStringRelativeTest()
{
var address = ProduceAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!A1:B2", address.ToStringRelative());
Assert.AreEqual("#REF!A1:B2", address.ToStringRelative(true));
}
[Test]
public void InvalidRangeAddressOnDeletedWorksheetToStringTest()
{
var address = ProduceInvalidAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!#REF!", address.ToString());
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.A1));
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.Default));
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.R1C1));
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.A1, true));
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.Default, true));
Assert.AreEqual("#REF!#REF!", address.ToString(XLReferenceStyle.R1C1, true));
}
[Test]
public void InvalidRangeAddressOnDeletedWorksheetToStringFixedTest()
{
var address = ProduceInvalidAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!#REF!", address.ToStringFixed());
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.A1));
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.Default));
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.R1C1));
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.A1, true));
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.Default, true));
Assert.AreEqual("#REF!#REF!", address.ToStringFixed(XLReferenceStyle.R1C1, true));
}
[Test]
public void InvalidRangeAddressOnDeletedWorksheetToStringRelativeTest()
{
var address = ProduceInvalidAddressOnDeletedWorksheet();
Assert.AreEqual("#REF!#REF!", address.ToStringRelative());
Assert.AreEqual("#REF!#REF!", address.ToStringRelative(true));
}
[Test]
public void FullSpanAddressCannotChange()
{
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
var wsRange = ws.AsRange();
var row = ws.FirstRow().RowBelow(4).AsRange();
var column = ws.FirstColumn().ColumnRight(4).AsRange();
Assert.AreEqual($"1:{XLHelper.MaxRowNumber}", wsRange.RangeAddress.ToString());
Assert.AreEqual("5:5", row.RangeAddress.ToString());
Assert.AreEqual("E:E", column.RangeAddress.ToString());
ws.Columns("Y:Z").Delete();
ws.Rows("9:10").Delete();
Assert.AreEqual($"1:{XLHelper.MaxRowNumber}", wsRange.RangeAddress.ToString());
Assert.AreEqual("5:5", row.RangeAddress.ToString());
Assert.AreEqual("E:E", column.RangeAddress.ToString());
}
}
[Test]
public void RangeAddressIsNormalized()
{
var ws = new XLWorkbook().AddWorksheet();
XLRangeAddress rangeAddress;
rangeAddress = (XLRangeAddress)ws.Range(ws.Cell("A1"), ws.Cell("C3")).RangeAddress;
Assert.IsTrue(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.Range(ws.Cell("C3"), ws.Cell("A1")).RangeAddress;
Assert.IsFalse(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.Range("B2:B1").RangeAddress;
Assert.IsFalse(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.Range("B2:B10").RangeAddress;
Assert.IsTrue(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.Range("B:B").RangeAddress;
Assert.IsTrue(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.Range("2:2").RangeAddress;
Assert.IsTrue(rangeAddress.IsNormalized);
rangeAddress = (XLRangeAddress)ws.RangeAddress;
Assert.IsTrue(rangeAddress.IsNormalized);
}
[Test]
public void AsRangeTests()
{
XLRangeAddress rangeAddress;
rangeAddress = new XLRangeAddress
(
new XLAddress(1, 1, false, false),
new XLAddress(5, 5, false, false)
);
Assert.IsTrue(rangeAddress.IsValid);
Assert.IsTrue(rangeAddress.IsNormalized);
Assert.Throws<InvalidOperationException>(() => rangeAddress.AsRange());
var ws = new XLWorkbook().AddWorksheet() as XLWorksheet;
rangeAddress = new XLRangeAddress
(
new XLAddress(ws, 1, 1, false, false),
new XLAddress(ws, 5, 5, false, false)
);
Assert.IsTrue(rangeAddress.IsValid);
Assert.IsTrue(rangeAddress.IsNormalized);
Assert.DoesNotThrow(() => rangeAddress.AsRange());
}
[Test]
public void RelativeRanges()
{
var ws = new XLWorkbook().AddWorksheet();
IXLRangeAddress rangeAddress;
rangeAddress = ws.Range("D4:E4").RangeAddress.Relative(ws.Range("A1:E4").RangeAddress, ws.Range("B10:F14").RangeAddress);
Assert.IsTrue(rangeAddress.IsValid);
Assert.AreEqual("E13:F13", rangeAddress.ToString());
rangeAddress = ws.Range("D4:E4").RangeAddress.Relative(ws.Range("B10:F14").RangeAddress, ws.Range("A1:E4").RangeAddress);
Assert.IsFalse(rangeAddress.IsValid);
Assert.AreEqual("#REF!", rangeAddress.ToString());
rangeAddress = ws.Range("C3").RangeAddress.Relative(ws.Range("A1:B2").RangeAddress, ws.Range("C3").RangeAddress);
Assert.IsTrue(rangeAddress.IsValid);
Assert.AreEqual("E5:E5", rangeAddress.ToString());
rangeAddress = ws.Range("B2").RangeAddress.Relative(ws.Range("A1").RangeAddress, ws.Range("C3").RangeAddress);
Assert.IsTrue(rangeAddress.IsValid);
Assert.AreEqual("D4:D4", rangeAddress.ToString());
rangeAddress = ws.Range("A1").RangeAddress.Relative(ws.Range("B2").RangeAddress, ws.Range("A1").RangeAddress);
Assert.IsFalse(rangeAddress.IsValid);
Assert.AreEqual("#REF!", rangeAddress.ToString());
}
[Test]
public void TestSpanProperties()
{
var ws = new XLWorkbook().AddWorksheet() as XLWorksheet;
var range = ws.Range("B3:E5");
var rangeAddress = range.RangeAddress as IXLRangeAddress;
Assert.AreEqual(4, rangeAddress.ColumnSpan);
Assert.AreEqual(3, rangeAddress.RowSpan);
Assert.AreEqual(12, rangeAddress.NumberOfCells);
range = ws.Range("E5:B3");
rangeAddress = range.RangeAddress as IXLRangeAddress;
Assert.AreEqual(4, rangeAddress.ColumnSpan);
Assert.AreEqual(3, rangeAddress.RowSpan);
Assert.AreEqual(12, rangeAddress.NumberOfCells);
rangeAddress = ProduceAddressOnDeletedWorksheet();
Assert.AreEqual(2, rangeAddress.ColumnSpan);
Assert.AreEqual(2, rangeAddress.RowSpan);
Assert.AreEqual(4, rangeAddress.NumberOfCells);
rangeAddress = ProduceInvalidAddress();
Assert.Throws<InvalidOperationException>(() => { var x = rangeAddress.ColumnSpan; });
Assert.Throws<InvalidOperationException>(() => { var x = rangeAddress.RowSpan; });
Assert.Throws<InvalidOperationException>(() => { var x = rangeAddress.NumberOfCells; });
}
#region Private Methods
private IXLRangeAddress ProduceInvalidAddress()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet 1");
var range = ws.Range("A1:B2");
ws.Rows(1, 5).Delete();
return range.RangeAddress;
}
private IXLRangeAddress ProduceAddressOnDeletedWorksheet()
{
IXLWorksheet ws = new XLWorkbook().Worksheets.Add("Sheet 1");
var address = ws.Range("A1:B2").RangeAddress;
ws.Delete();
return address;
}
private IXLRangeAddress ProduceInvalidAddressOnDeletedWorksheet()
{
var address = ProduceInvalidAddress();
address.Worksheet.Delete();
return address;
}
#endregion Private Methods
}
}
| |
using System;
using System.Collections.Generic;
using Npgsql;
using TroutDash.DatabaseImporter.Convention;
namespace TroutStreamMangler.MN
{
public class LinearReferenceResult
{
public int StreamId { get; set; }
public string StreamNumber { get; set; }
public string StreamName { get; set; }
public string GeometryName { get; set; }
public int GeometryId { get; set; }
public string IntersectionGeometry { get; set; }
public string IntersectionGeometryType { get; set; }
public double StartPoint { get; set; }
public double EndPoint { get; set; }
public double StreamLength { get; set; }
}
public class GetLinearOffsets
{
private readonly IDatabaseConnection _dbConnection;
public GetLinearOffsets(IDatabaseConnection dbConnection)
{
_dbConnection = dbConnection;
}
public IEnumerable<LinearReferenceResult> ExecuteBufferedLinearReferenceResults(string streamTableName,
string streamNameColumn,
string streamIdColumn,
string streamId,
string geometryTableName,
string geometryIdColumn,
string geometryNameColumn)
{
const string linearReferenceString =
@"SELECT intersection_data.stream_id,
intersection_data.stream_number,
intersection_data.stream_name,
intersection_data.body_name,
intersection_data.body_id,
intersection_data.mini_line,
intersection_data.geometry_type,
St_linelocatepoint(St_linemerge(stream_route.geom), St_startpoint(intersection_data.mini_line)) AS start_point ,
St_linelocatepoint(St_linemerge(stream_route.geom), St_endpoint(intersection_data.mini_line)) AS end_point,
St_length(stream_route.geom) AS outer_length
FROM (
SELECT dumped.stream_id,
dumped.stream_number,
dumped.stream_name,
dumped.body_name,
dumped.body_id,
st_linemerge((dumped.geom_dump).geom) AS mini_line,
geometrytype(st_linemerge((dumped.geom_dump).geom)) AS geometry_type
FROM (
SELECT stream_id,
stream_number,
stream_name,
body_name,
body_id,
st_dump(intersection_geom) AS geom_dump
FROM (
SELECT stream.{2} AS stream_id,
stream.{3} stream_number,
stream.{3} stream_name,
lake.{6} AS body_name,
lake.{5} AS body_id,
st_intersection(stream.geom, lake.geom) AS intersection_geom,
geometrytype(st_intersection(stream.geom, lake.geom)) AS geom_type
FROM PUBLIC.{0} stream,
(
SELECT new_reg AS {5},
'Some Regulation' AS {6},
st_buffer(st_multi(st_union(geom)), 10) AS geom
FROM (
SELECT regulation.{5},
'asdf' AS {6},
regulation.geom
FROM public.{1} regulation,
public.{0} route
WHERE st_intersects(st_envelope(route.geom), regulation.geom)
AND route.{2} = {4}) AS subquery
GROUP BY new_reg) lake
WHERE stream.{2} = {4}
AND st_intersects(lake.geom, stream.geom)) AS complex ) AS dumped ) AS intersection_data,
PUBLIC.{0} stream_route
WHERE stream_route.{2} = {4}";
var sql = string.Format(linearReferenceString, streamTableName, geometryTableName, streamIdColumn,
streamNameColumn, streamId, geometryIdColumn, geometryNameColumn);
foreach (var linearReferenceResult in ExecuteQuery(sql))
{
yield return linearReferenceResult;
}
}
public IEnumerable<LinearReferenceResult> ExecuteLinearReference(string streamTableName,
string streamNameColumn,
string streamIdColumn,
string streamId,
string geometryTableName,
string geometryIdColumn,
string geometryNameColumn)
{
const string linearReferenceString =
@"SELECT intersection_data.stream_id,
intersection_data.stream_number,
intersection_data.stream_name,
intersection_data.body_name,
intersection_data.body_id,
intersection_data.mini_line,
intersection_data.geometry_type,
St_linelocatepoint(St_linemerge(stream_route.geom), St_startpoint(intersection_data.mini_line)) AS start_point ,
St_linelocatepoint(St_linemerge(stream_route.geom), St_endpoint(intersection_data.mini_line)) AS end_point,
St_length(stream_route.geom) AS outer_length
FROM (
SELECT dumped.stream_id,
dumped.stream_number,
dumped.stream_name,
dumped.body_name,
dumped.body_id,
st_linemerge((dumped.geom_dump).geom) AS mini_line,
geometrytype(st_linemerge((dumped.geom_dump).geom)) AS geometry_type
FROM (
SELECT stream_id,
stream_number,
stream_name,
body_name,
body_id,
st_dump(intersection_geom) AS geom_dump
FROM (
SELECT stream.{2} AS stream_id,
stream.{3} stream_number,
stream.{3} stream_name,
lake.{6} AS body_name,
lake.{5} AS body_id,
st_intersection(stream.geom, lake.geom) AS intersection_geom,
geometrytype(st_intersection(stream.geom, lake.geom)) AS geom_type
FROM PUBLIC.{0} stream,
PUBLIC.{1} lake
WHERE stream.{2} = {4}
AND st_intersects(lake.geom, stream.geom)) AS complex ) AS dumped ) AS intersection_data,
PUBLIC.{0} stream_route
WHERE stream_route.{2} = {4}
";
var sql = string.Format(linearReferenceString, streamTableName, geometryTableName, streamIdColumn,
streamNameColumn, streamId, geometryIdColumn, geometryNameColumn);
foreach (var linearReferenceResult in ExecuteQuery(sql))
{
yield return linearReferenceResult;
}
}
private IEnumerable<LinearReferenceResult> ExecuteQuery(string sql)
{
var connection = String.Format("Server={0};Port=5432;User Id={1};Database={2};Password=fakepassword;", _dbConnection.HostName, _dbConnection.UserName, _dbConnection.DatabaseName);
var conn = new NpgsqlConnection(connection);
conn.Open();
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
try
{
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
var l = new LinearReferenceResult();
// sometimes when a line intercepts a polygon you can
// get a point, e.g. the EXACT mouth of a river.
// ignore these non-line geometries.
l.IntersectionGeometryType = dr.GetString(6);
var isLineString = String.Equals("Linestring", l.IntersectionGeometryType,
StringComparison.OrdinalIgnoreCase);
if (isLineString == false)
{
yield break;
}
if (dr.IsDBNull(1))
{
yield break;
}
l.StreamId = dr.GetInt32(0);
l.StreamNumber = dr.IsDBNull(1) ? "Unnamed" : dr.GetString(1);
l.StreamName = dr.IsDBNull(2) ? "" : dr.GetString(2);
l.GeometryName = dr.IsDBNull(3) ? "" : dr.GetString(3);
var asdf = dr[4];
l.GeometryId = Convert.ToInt32(asdf);
l.IntersectionGeometry = dr.GetString(5);
l.StartPoint = dr.GetDouble(7);
l.EndPoint = dr.GetDouble(8);
l.StreamLength = dr.GetDouble(9);
yield return l;
}
}
finally
{
conn.Close();
}
}
public IEnumerable<Tuple<decimal, decimal>> GetOffsets(string streamId, string geometryTable)
{
const string linearReferenceString =
@"SELECT (St_dump(St_intersection(palbuffer, strouter.geom))).geom as thegeom,
st_linelocatepoint(st_linemerge(strouter.geom), st_startpoint((st_dump(st_intersection(palbuffer, strouter.geom))).geom)) AS start,
st_linelocatepoint(st_linemerge(strouter.geom), st_endpoint((st_dump(st_intersection(palbuffer, strouter.geom))).geom)) AS stop
FROM streams_with_measured_kittle_routes strouter,
(
SELECT st_buffer(st_union(dumpgeom), 3, 'endcap=flat join=round') AS palbuffer
FROM (
SELECT pal.geom AS dumpgeom
FROM {1} AS pal,
streams_with_measured_kittle_routes routes
WHERE ST_Intersects(pal.geom, routes.geom)
and routes.gid = '{0}') AS DUMP) AS palbuffer
WHERE strouter.gid = '{0}'
";
var connection = String.Format("Server={0};Port=5432;User Id={1};Database={2};Password=fakepassword;", _dbConnection.HostName, _dbConnection.UserName, _dbConnection.DatabaseName);
var conn = new NpgsqlConnection(connection);
conn.Open();
var sql = string.Format(linearReferenceString, streamId, geometryTable);
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
try
{
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
var start = Convert.ToDecimal(dr[1]);
var stop = Convert.ToDecimal(dr[2]);
yield return new Tuple<decimal, decimal>(start, stop);
}
}
finally
{
conn.Close();
}
}
}
}
| |
// 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.Threading;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
// DateTimeOffset is a value type that consists of a DateTime and a time zone offset,
// ie. how far away the time is from GMT. The DateTime is stored whole, and the offset
// is stored as an Int16 internally to save space, but presented as a TimeSpan.
//
// The range is constrained so that both the represented clock time and the represented
// UTC time fit within the boundaries of MaxValue. This gives it the same range as DateTime
// for actual UTC times, and a slightly constrained range on one end when an offset is
// present.
//
// This class should be substitutable for date time in most cases; so most operations
// effectively work on the clock time. However, the underlying UTC time is what counts
// for the purposes of identity, sorting and subtracting two instances.
//
//
// There are theoretically two date times stored, the UTC and the relative local representation
// or the 'clock' time. It actually does not matter which is stored in m_dateTime, so it is desirable
// for most methods to go through the helpers UtcDateTime and ClockDateTime both to abstract this
// out and for internal readability.
[StructLayout(LayoutKind.Auto)]
[Serializable]
public struct DateTimeOffset : IComparable, IFormattable,
IComparable<DateTimeOffset>, IEquatable<DateTimeOffset>, ISerializable, IDeserializationCallback
{
// Constants
internal const Int64 MaxOffset = TimeSpan.TicksPerHour * 14;
internal const Int64 MinOffset = -MaxOffset;
private const long UnixEpochTicks = TimeSpan.TicksPerDay * DateTime.DaysTo1970; // 621,355,968,000,000,000
private const long UnixEpochSeconds = UnixEpochTicks / TimeSpan.TicksPerSecond; // 62,135,596,800
private const long UnixEpochMilliseconds = UnixEpochTicks / TimeSpan.TicksPerMillisecond; // 62,135,596,800,000
internal const long UnixMinSeconds = DateTime.MinTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
internal const long UnixMaxSeconds = DateTime.MaxTicks / TimeSpan.TicksPerSecond - UnixEpochSeconds;
// Static Fields
public static readonly DateTimeOffset MinValue = new DateTimeOffset(DateTime.MinTicks, TimeSpan.Zero);
public static readonly DateTimeOffset MaxValue = new DateTimeOffset(DateTime.MaxTicks, TimeSpan.Zero);
// Instance Fields
private DateTime m_dateTime;
private Int16 m_offsetMinutes;
// Constructors
// Constructs a DateTimeOffset from a tick count and offset
public DateTimeOffset(long ticks, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
// Let the DateTime constructor do the range checks
DateTime dateTime = new DateTime(ticks);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. For Local and Unspecified kinds,
// extracts the local offset. For UTC, creates a UTC instance with a zero offset.
public DateTimeOffset(DateTime dateTime) {
TimeSpan offset;
if (dateTime.Kind != DateTimeKind.Utc) {
// Local and Unspecified are both treated as Local
offset = TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime);
}
else {
offset = new TimeSpan(0);
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a DateTime. And an offset. Always makes the clock time
// consistent with the DateTime. For Utc ensures the offset is zero. For local, ensures that
// the offset corresponds to the local.
public DateTimeOffset(DateTime dateTime, TimeSpan offset) {
if (dateTime.Kind == DateTimeKind.Local) {
if (offset != TimeZoneInfo.GetLocalUtcOffset(dateTime, TimeZoneInfoOptions.NoThrowOnInvalidTime)) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetLocalMismatch"), "offset");
}
}
else if (dateTime.Kind == DateTimeKind.Utc) {
if (offset != TimeSpan.Zero) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetUtcMismatch"), "offset");
}
}
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(dateTime, offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond and offset
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond), offset);
}
// Constructs a DateTimeOffset from a given year, month, day, hour,
// minute, second, millsecond, Calendar and offset.
public DateTimeOffset(int year, int month, int day, int hour, int minute, int second, int millisecond, Calendar calendar, TimeSpan offset) {
m_offsetMinutes = ValidateOffset(offset);
m_dateTime = ValidateDate(new DateTime(year, month, day, hour, minute, second, millisecond, calendar), offset);
}
// Returns a DateTimeOffset representing the current date and time. The
// resolution of the returned value depends on the system timer. For
// Windows NT 3.5 and later the timer resolution is approximately 10ms,
// for Windows NT 3.1 it is approximately 16ms, and for Windows 95 and 98
// it is approximately 55ms.
//
public static DateTimeOffset Now {
get {
return new DateTimeOffset(DateTime.Now);
}
}
public static DateTimeOffset UtcNow {
get {
return new DateTimeOffset(DateTime.UtcNow);
}
}
public DateTime DateTime {
get {
return ClockDateTime;
}
}
public DateTime UtcDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Utc);
return DateTime.SpecifyKind(m_dateTime, DateTimeKind.Utc);
}
}
public DateTime LocalDateTime {
[Pure]
get {
Contract.Ensures(Contract.Result<DateTime>().Kind == DateTimeKind.Local);
return UtcDateTime.ToLocalTime();
}
}
// Adjust to a given offset with the same UTC time. Can throw ArgumentException
//
public DateTimeOffset ToOffset(TimeSpan offset) {
return new DateTimeOffset((m_dateTime + offset).Ticks, offset);
}
// Instance Properties
// The clock or visible time represented. This is just a wrapper around the internal date because this is
// the chosen storage mechanism. Going through this helper is good for readability and maintainability.
// This should be used for display but not identity.
private DateTime ClockDateTime {
get {
return new DateTime((m_dateTime + Offset).Ticks, DateTimeKind.Unspecified);
}
}
// Returns the date part of this DateTimeOffset. The resulting value
// corresponds to this DateTimeOffset with the time-of-day part set to
// zero (midnight).
//
public DateTime Date {
get {
return ClockDateTime.Date;
}
}
// Returns the day-of-month part of this DateTimeOffset. The returned
// value is an integer between 1 and 31.
//
public int Day {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 31);
return ClockDateTime.Day;
}
}
// Returns the day-of-week part of this DateTimeOffset. The returned value
// is an integer between 0 and 6, where 0 indicates Sunday, 1 indicates
// Monday, 2 indicates Tuesday, 3 indicates Wednesday, 4 indicates
// Thursday, 5 indicates Friday, and 6 indicates Saturday.
//
public DayOfWeek DayOfWeek {
get {
Contract.Ensures(Contract.Result<DayOfWeek>() >= DayOfWeek.Sunday);
Contract.Ensures(Contract.Result<DayOfWeek>() <= DayOfWeek.Saturday);
return ClockDateTime.DayOfWeek;
}
}
// Returns the day-of-year part of this DateTimeOffset. The returned value
// is an integer between 1 and 366.
//
public int DayOfYear {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
Contract.Ensures(Contract.Result<int>() <= 366); // leap year
return ClockDateTime.DayOfYear;
}
}
// Returns the hour part of this DateTimeOffset. The returned value is an
// integer between 0 and 23.
//
public int Hour {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 24);
return ClockDateTime.Hour;
}
}
// Returns the millisecond part of this DateTimeOffset. The returned value
// is an integer between 0 and 999.
//
public int Millisecond {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 1000);
return ClockDateTime.Millisecond;
}
}
// Returns the minute part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Minute {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Minute;
}
}
// Returns the month part of this DateTimeOffset. The returned value is an
// integer between 1 and 12.
//
public int Month {
get {
Contract.Ensures(Contract.Result<int>() >= 1);
return ClockDateTime.Month;
}
}
public TimeSpan Offset {
get {
return new TimeSpan(0, m_offsetMinutes, 0);
}
}
// Returns the second part of this DateTimeOffset. The returned value is
// an integer between 0 and 59.
//
public int Second {
get {
Contract.Ensures(Contract.Result<int>() >= 0);
Contract.Ensures(Contract.Result<int>() < 60);
return ClockDateTime.Second;
}
}
// Returns the tick count for this DateTimeOffset. The returned value is
// the number of 100-nanosecond intervals that have elapsed since 1/1/0001
// 12:00am.
//
public long Ticks {
get {
return ClockDateTime.Ticks;
}
}
public long UtcTicks {
get {
return UtcDateTime.Ticks;
}
}
// Returns the time-of-day part of this DateTimeOffset. The returned value
// is a TimeSpan that indicates the time elapsed since midnight.
//
public TimeSpan TimeOfDay {
get {
return ClockDateTime.TimeOfDay;
}
}
// Returns the year part of this DateTimeOffset. The returned value is an
// integer between 1 and 9999.
//
public int Year {
get {
Contract.Ensures(Contract.Result<int>() >= 1 && Contract.Result<int>() <= 9999);
return ClockDateTime.Year;
}
}
// Returns the DateTimeOffset resulting from adding the given
// TimeSpan to this DateTimeOffset.
//
public DateTimeOffset Add(TimeSpan timeSpan) {
return new DateTimeOffset(ClockDateTime.Add(timeSpan), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// days to this DateTimeOffset. The result is computed by rounding the
// fractional number of days given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddDays(double days) {
return new DateTimeOffset(ClockDateTime.AddDays(days), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// hours to this DateTimeOffset. The result is computed by rounding the
// fractional number of hours given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddHours(double hours) {
return new DateTimeOffset(ClockDateTime.AddHours(hours), Offset);
}
// Returns the DateTimeOffset resulting from the given number of
// milliseconds to this DateTimeOffset. The result is computed by rounding
// the number of milliseconds given by value to the nearest integer,
// and adding that interval to this DateTimeOffset. The value
// argument is permitted to be negative.
//
public DateTimeOffset AddMilliseconds(double milliseconds) {
return new DateTimeOffset(ClockDateTime.AddMilliseconds(milliseconds), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// minutes to this DateTimeOffset. The result is computed by rounding the
// fractional number of minutes given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddMinutes(double minutes) {
return new DateTimeOffset(ClockDateTime.AddMinutes(minutes), Offset);
}
public DateTimeOffset AddMonths(int months) {
return new DateTimeOffset(ClockDateTime.AddMonths(months), Offset);
}
// Returns the DateTimeOffset resulting from adding a fractional number of
// seconds to this DateTimeOffset. The result is computed by rounding the
// fractional number of seconds given by value to the nearest
// millisecond, and adding that interval to this DateTimeOffset. The
// value argument is permitted to be negative.
//
public DateTimeOffset AddSeconds(double seconds) {
return new DateTimeOffset(ClockDateTime.AddSeconds(seconds), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// 100-nanosecond ticks to this DateTimeOffset. The value argument
// is permitted to be negative.
//
public DateTimeOffset AddTicks(long ticks) {
return new DateTimeOffset(ClockDateTime.AddTicks(ticks), Offset);
}
// Returns the DateTimeOffset resulting from adding the given number of
// years to this DateTimeOffset. The result is computed by incrementing
// (or decrementing) the year part of this DateTimeOffset by value
// years. If the month and day of this DateTimeOffset is 2/29, and if the
// resulting year is not a leap year, the month and day of the resulting
// DateTimeOffset becomes 2/28. Otherwise, the month, day, and time-of-day
// parts of the result are the same as those of this DateTimeOffset.
//
public DateTimeOffset AddYears(int years) {
return new DateTimeOffset(ClockDateTime.AddYears(years), Offset);
}
// Compares two DateTimeOffset values, returning an integer that indicates
// their relationship.
//
public static int Compare(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Compare(first.UtcDateTime, second.UtcDateTime);
}
// Compares this DateTimeOffset to a given object. This method provides an
// implementation of the IComparable interface. The object
// argument must be another DateTimeOffset, or otherwise an exception
// occurs. Null is considered less than any instance.
//
int IComparable.CompareTo(Object obj) {
if (obj == null) return 1;
if (!(obj is DateTimeOffset)) {
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDateTimeOffset"));
}
DateTime objUtc = ((DateTimeOffset)obj).UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > objUtc) return 1;
if (utc < objUtc) return -1;
return 0;
}
public int CompareTo(DateTimeOffset other) {
DateTime otherUtc = other.UtcDateTime;
DateTime utc = UtcDateTime;
if (utc > otherUtc) return 1;
if (utc < otherUtc) return -1;
return 0;
}
// Checks if this DateTimeOffset is equal to a given object. Returns
// true if the given object is a boxed DateTimeOffset and its value
// is equal to the value of this DateTimeOffset. Returns false
// otherwise.
//
public override bool Equals(Object obj) {
if (obj is DateTimeOffset) {
return UtcDateTime.Equals(((DateTimeOffset)obj).UtcDateTime);
}
return false;
}
public bool Equals(DateTimeOffset other) {
return UtcDateTime.Equals(other.UtcDateTime);
}
public bool EqualsExact(DateTimeOffset other) {
//
// returns true when the ClockDateTime, Kind, and Offset match
//
// currently the Kind should always be Unspecified, but there is always the possibility that a future version
// of DateTimeOffset overloads the Kind field
//
return (ClockDateTime == other.ClockDateTime && Offset == other.Offset && ClockDateTime.Kind == other.ClockDateTime.Kind);
}
// Compares two DateTimeOffset values for equality. Returns true if
// the two DateTimeOffset values are equal, or false if they are
// not equal.
//
public static bool Equals(DateTimeOffset first, DateTimeOffset second) {
return DateTime.Equals(first.UtcDateTime, second.UtcDateTime);
}
// Creates a DateTimeOffset from a Windows filetime. A Windows filetime is
// a long representing the date and time as the number of
// 100-nanosecond intervals that have elapsed since 1/1/1601 12:00am.
//
public static DateTimeOffset FromFileTime(long fileTime) {
return new DateTimeOffset(DateTime.FromFileTime(fileTime));
}
public static DateTimeOffset FromUnixTimeSeconds(long seconds) {
if (seconds < UnixMinSeconds || seconds > UnixMaxSeconds) {
throw new ArgumentOutOfRangeException("seconds",
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), UnixMinSeconds, UnixMaxSeconds));
}
long ticks = seconds * TimeSpan.TicksPerSecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
public static DateTimeOffset FromUnixTimeMilliseconds(long milliseconds) {
const long MinMilliseconds = DateTime.MinTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
const long MaxMilliseconds = DateTime.MaxTicks / TimeSpan.TicksPerMillisecond - UnixEpochMilliseconds;
if (milliseconds < MinMilliseconds || milliseconds > MaxMilliseconds) {
throw new ArgumentOutOfRangeException("milliseconds",
string.Format(Environment.GetResourceString("ArgumentOutOfRange_Range"), MinMilliseconds, MaxMilliseconds));
}
long ticks = milliseconds * TimeSpan.TicksPerMillisecond + UnixEpochTicks;
return new DateTimeOffset(ticks, TimeSpan.Zero);
}
// ----- SECTION: private serialization instance methods ----------------*
void IDeserializationCallback.OnDeserialization(Object sender) {
try {
m_offsetMinutes = ValidateOffset(Offset);
m_dateTime = ValidateDate(ClockDateTime, Offset);
}
catch (ArgumentException e) {
throw new SerializationException(Environment.GetResourceString("Serialization_InvalidData"), e);
}
}
[System.Security.SecurityCritical] // auto-generated_required
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
Contract.EndContractBlock();
info.AddValue("DateTime", m_dateTime);
info.AddValue("OffsetMinutes", m_offsetMinutes);
}
DateTimeOffset(SerializationInfo info, StreamingContext context) {
if (info == null) {
throw new ArgumentNullException("info");
}
m_dateTime = (DateTime)info.GetValue("DateTime", typeof(DateTime));
m_offsetMinutes = (Int16)info.GetValue("OffsetMinutes", typeof(Int16));
}
// Returns the hash code for this DateTimeOffset.
//
public override int GetHashCode() {
return UtcDateTime.GetHashCode();
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input) {
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider) {
return Parse(input, formatProvider, DateTimeStyles.None);
}
public static DateTimeOffset Parse(String input, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.Parse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider) {
return ParseExact(input, format, formatProvider, DateTimeStyles.None);
}
// Constructs a DateTimeOffset from a string. The string must specify a
// date and optionally a time in a culture-specific or universal format.
// Leading and trailing whitespace characters are allowed.
//
public static DateTimeOffset ParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public static DateTimeOffset ParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult = DateTimeParse.ParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out offset);
return new DateTimeOffset(dateResult.Ticks, offset);
}
public TimeSpan Subtract(DateTimeOffset value) {
return UtcDateTime.Subtract(value.UtcDateTime);
}
public DateTimeOffset Subtract(TimeSpan value) {
return new DateTimeOffset(ClockDateTime.Subtract(value), Offset);
}
public long ToFileTime() {
return UtcDateTime.ToFileTime();
}
public long ToUnixTimeSeconds() {
// Truncate sub-second precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times.
//
// For example, consider the DateTimeOffset 12/31/1969 12:59:59.001 +0
// ticks = 621355967990010000
// ticksFromEpoch = ticks - UnixEpochTicks = -9990000
// secondsFromEpoch = ticksFromEpoch / TimeSpan.TicksPerSecond = 0
//
// Notice that secondsFromEpoch is rounded *up* by the truncation induced by integer division,
// whereas we actually always want to round *down* when converting to Unix time. This happens
// automatically for positive Unix time values. Now the example becomes:
// seconds = ticks / TimeSpan.TicksPerSecond = 62135596799
// secondsFromEpoch = seconds - UnixEpochSeconds = -1
//
// In other words, we want to consistently round toward the time 1/1/0001 00:00:00,
// rather than toward the Unix Epoch (1/1/1970 00:00:00).
long seconds = UtcDateTime.Ticks / TimeSpan.TicksPerSecond;
return seconds - UnixEpochSeconds;
}
public long ToUnixTimeMilliseconds() {
// Truncate sub-millisecond precision before offsetting by the Unix Epoch to avoid
// the last digit being off by one for dates that result in negative Unix times
long milliseconds = UtcDateTime.Ticks / TimeSpan.TicksPerMillisecond;
return milliseconds - UnixEpochMilliseconds;
}
public DateTimeOffset ToLocalTime() {
return ToLocalTime(false);
}
internal DateTimeOffset ToLocalTime(bool throwOnOverflow)
{
return new DateTimeOffset(UtcDateTime.ToLocalTime(throwOnOverflow));
}
public override String ToString() {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(String format) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.CurrentInfo, Offset);
}
public String ToString(IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, null, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public String ToString(String format, IFormatProvider formatProvider) {
Contract.Ensures(Contract.Result<String>() != null);
return DateTimeFormat.Format(ClockDateTime, format, DateTimeFormatInfo.GetInstance(formatProvider), Offset);
}
public DateTimeOffset ToUniversalTime() {
return new DateTimeOffset(UtcDateTime);
}
public static Boolean TryParse(String input, out DateTimeOffset result) {
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.CurrentInfo,
DateTimeStyles.None,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParse(String input, IFormatProvider formatProvider, DateTimeStyles styles, out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParse(input,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String format, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExact(input,
format,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
public static Boolean TryParseExact(String input, String[] formats, IFormatProvider formatProvider, DateTimeStyles styles,
out DateTimeOffset result) {
styles = ValidateStyles(styles, "styles");
TimeSpan offset;
DateTime dateResult;
Boolean parsed = DateTimeParse.TryParseExactMultiple(input,
formats,
DateTimeFormatInfo.GetInstance(formatProvider),
styles,
out dateResult,
out offset);
result = new DateTimeOffset(dateResult.Ticks, offset);
return parsed;
}
// Ensures the TimeSpan is valid to go in a DateTimeOffset.
private static Int16 ValidateOffset(TimeSpan offset) {
Int64 ticks = offset.Ticks;
if (ticks % TimeSpan.TicksPerMinute != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_OffsetPrecision"), "offset");
}
if (ticks < MinOffset || ticks > MaxOffset) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_OffsetOutOfRange"));
}
return (Int16)(offset.Ticks / TimeSpan.TicksPerMinute);
}
// Ensures that the time and offset are in range.
private static DateTime ValidateDate(DateTime dateTime, TimeSpan offset) {
// The key validation is that both the UTC and clock times fit. The clock time is validated
// by the DateTime constructor.
Contract.Assert(offset.Ticks >= MinOffset && offset.Ticks <= MaxOffset, "Offset not validated.");
// This operation cannot overflow because offset should have already been validated to be within
// 14 hours and the DateTime instance is more than that distance from the boundaries of Int64.
Int64 utcTicks = dateTime.Ticks - offset.Ticks;
if (utcTicks < DateTime.MinTicks || utcTicks > DateTime.MaxTicks) {
throw new ArgumentOutOfRangeException("offset", Environment.GetResourceString("Argument_UTCOutOfRange"));
}
// make sure the Kind is set to Unspecified
//
return new DateTime(utcTicks, DateTimeKind.Unspecified);
}
private static DateTimeStyles ValidateStyles(DateTimeStyles style, String parameterName) {
if ((style & DateTimeFormatInfo.InvalidDateTimeStyles) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidDateTimeStyles"), parameterName);
}
if (((style & (DateTimeStyles.AssumeLocal)) != 0) && ((style & (DateTimeStyles.AssumeUniversal)) != 0)) {
throw new ArgumentException(Environment.GetResourceString("Argument_ConflictingDateTimeStyles"), parameterName);
}
if ((style & DateTimeStyles.NoCurrentDateDefault) != 0) {
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeOffsetInvalidDateTimeStyles"), parameterName);
}
Contract.EndContractBlock();
// RoundtripKind does not make sense for DateTimeOffset; ignore this flag for backward compatibility with DateTime
style &= ~DateTimeStyles.RoundtripKind;
// AssumeLocal is also ignored as that is what we do by default with DateTimeOffset.Parse
style &= ~DateTimeStyles.AssumeLocal;
return style;
}
// Operators
public static implicit operator DateTimeOffset (DateTime dateTime) {
return new DateTimeOffset(dateTime);
}
public static DateTimeOffset operator +(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime + timeSpan, dateTimeOffset.Offset);
}
public static DateTimeOffset operator -(DateTimeOffset dateTimeOffset, TimeSpan timeSpan) {
return new DateTimeOffset(dateTimeOffset.ClockDateTime - timeSpan, dateTimeOffset.Offset);
}
public static TimeSpan operator -(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime - right.UtcDateTime;
}
public static bool operator ==(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime == right.UtcDateTime;
}
public static bool operator !=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime != right.UtcDateTime;
}
public static bool operator <(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime < right.UtcDateTime;
}
public static bool operator <=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime <= right.UtcDateTime;
}
public static bool operator >(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime > right.UtcDateTime;
}
public static bool operator >=(DateTimeOffset left, DateTimeOffset right) {
return left.UtcDateTime >= right.UtcDateTime;
}
}
}
| |
using System;
using System.Globalization;
using System.Collections.Generic;
using Sasoma.Utils;
using Sasoma.Microdata.Interfaces;
using Sasoma.Languages.Core;
using Sasoma.Microdata.Properties;
namespace Sasoma.Microdata.Types
{
/// <summary>
/// A campground.
/// </summary>
public class Campground_Core : TypeCore, ICivicStructure
{
public Campground_Core()
{
this._TypeId = 51;
this._Id = "Campground";
this._Schema_Org_Url = "http://schema.org/Campground";
string label = "";
GetLabel(out label, "Campground", typeof(Campground_Core));
this._Label = label;
this._Ancestors = new int[]{266,206,62};
this._SubTypes = new int[0];
this._SuperTypes = new int[]{62};
this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196,152};
}
/// <summary>
/// Physical address of the item.
/// </summary>
private Address_Core address;
public Address_Core Address
{
get
{
return address;
}
set
{
address = value;
SetPropertyInstance(address);
}
}
/// <summary>
/// The overall rating, based on a collection of reviews or ratings, of the item.
/// </summary>
private Properties.AggregateRating_Core aggregateRating;
public Properties.AggregateRating_Core AggregateRating
{
get
{
return aggregateRating;
}
set
{
aggregateRating = value;
SetPropertyInstance(aggregateRating);
}
}
/// <summary>
/// The basic containment relation between places.
/// </summary>
private ContainedIn_Core containedIn;
public ContainedIn_Core ContainedIn
{
get
{
return containedIn;
}
set
{
containedIn = value;
SetPropertyInstance(containedIn);
}
}
/// <summary>
/// A short description of the item.
/// </summary>
private Description_Core description;
public Description_Core Description
{
get
{
return description;
}
set
{
description = value;
SetPropertyInstance(description);
}
}
/// <summary>
/// Upcoming or past events associated with this place or organization.
/// </summary>
private Events_Core events;
public Events_Core Events
{
get
{
return events;
}
set
{
events = value;
SetPropertyInstance(events);
}
}
/// <summary>
/// The fax number.
/// </summary>
private FaxNumber_Core faxNumber;
public FaxNumber_Core FaxNumber
{
get
{
return faxNumber;
}
set
{
faxNumber = value;
SetPropertyInstance(faxNumber);
}
}
/// <summary>
/// The geo coordinates of the place.
/// </summary>
private Geo_Core geo;
public Geo_Core Geo
{
get
{
return geo;
}
set
{
geo = value;
SetPropertyInstance(geo);
}
}
/// <summary>
/// URL of an image of the item.
/// </summary>
private Image_Core image;
public Image_Core Image
{
get
{
return image;
}
set
{
image = value;
SetPropertyInstance(image);
}
}
/// <summary>
/// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>.
/// </summary>
private InteractionCount_Core interactionCount;
public InteractionCount_Core InteractionCount
{
get
{
return interactionCount;
}
set
{
interactionCount = value;
SetPropertyInstance(interactionCount);
}
}
/// <summary>
/// A URL to a map of the place.
/// </summary>
private Maps_Core maps;
public Maps_Core Maps
{
get
{
return maps;
}
set
{
maps = value;
SetPropertyInstance(maps);
}
}
/// <summary>
/// The name of the item.
/// </summary>
private Name_Core name;
public Name_Core Name
{
get
{
return name;
}
set
{
name = value;
SetPropertyInstance(name);
}
}
/// <summary>
/// The opening hours for a business. Opening hours can be specified as a weekly time range, starting with days, then times per day. Multiple days can be listed with commas ',' separating each day. Day or time ranges are specified using a hyphen '-'.<br/>- Days are specified using the following two-letter combinations: <code>Mo</code>, <code>Tu</code>, <code>We</code>, <code>Th</code>, <code>Fr</code>, <code>Sa</code>, <code>Su</code>.<br/>- Times are specified using 24:00 time. For example, 3pm is specified as <code>15:00</code>. <br/>- Here is an example: <code><time itemprop=\openingHours\ datetime=\Tu,Th 16:00-20:00\>Tuesdays and Thursdays 4-8pm</time></code>. <br/>- If a business is open 7 days a week, then it can be specified as <code><time itemprop=\openingHours\ datetime=\Mo-Su\>Monday through Sunday, all day</time></code>.
/// </summary>
private OpeningHours_Core openingHours;
public OpeningHours_Core OpeningHours
{
get
{
return openingHours;
}
set
{
openingHours = value;
SetPropertyInstance(openingHours);
}
}
/// <summary>
/// Photographs of this place.
/// </summary>
private Photos_Core photos;
public Photos_Core Photos
{
get
{
return photos;
}
set
{
photos = value;
SetPropertyInstance(photos);
}
}
/// <summary>
/// Review of the item.
/// </summary>
private Reviews_Core reviews;
public Reviews_Core Reviews
{
get
{
return reviews;
}
set
{
reviews = value;
SetPropertyInstance(reviews);
}
}
/// <summary>
/// The telephone number.
/// </summary>
private Telephone_Core telephone;
public Telephone_Core Telephone
{
get
{
return telephone;
}
set
{
telephone = value;
SetPropertyInstance(telephone);
}
}
/// <summary>
/// URL of the item.
/// </summary>
private Properties.URL_Core uRL;
public Properties.URL_Core URL
{
get
{
return uRL;
}
set
{
uRL = value;
SetPropertyInstance(uRL);
}
}
}
}
| |
// This file is part of Wintermute Engine
// For conditions of distribution and use, see copyright notice in license.txt
// http://dead-code.org/redir.php?target=wme
using System;
using System.Collections.Generic;
using System.Text;
using DeadCode.WME.Core;
using System.IO;
using System.Windows.Forms;
namespace DeadCode.WME.Global
{
public class Document
{
public enum DocumentOpenResult
{
Ok, Cancel, Error
};
private string _FileName = "";
//////////////////////////////////////////////////////////////////////////
public string FileName
{
get
{
return _FileName;
}
set
{
_FileName = value;
OnFileNameChanged();
OnCaptionChanged();
}
}
private bool _IsDirty = false;
//////////////////////////////////////////////////////////////////////////
public bool IsDirty
{
get
{
return _IsDirty;
}
set
{
_IsDirty = value;
OnCaptionChanged();
}
}
//////////////////////////////////////////////////////////////////////////
public string GetDocumentCaption()
{
return GetDocumentCaption("");
}
//////////////////////////////////////////////////////////////////////////
public string GetDocumentCaption(string AppName)
{
string Ret = "";
if (AppName != "") Ret += AppName + " - [";
if (FileName != "") Ret += Path.GetFileName(FileName);
else Ret += "untitled";
if(IsDirty) Ret += "*";
if(AppName != "") Ret += "]";
return Ret;
}
//////////////////////////////////////////////////////////////////////////
public event EventHandler CaptionChanged;
protected void OnCaptionChanged()
{
if (CaptionChanged != null) CaptionChanged(this, new EventArgs());
}
//////////////////////////////////////////////////////////////////////////
public event EventHandler FileNameChanged;
protected void OnFileNameChanged()
{
if (FileNameChanged != null) FileNameChanged(this, new EventArgs());
}
#region Undo system
private int _MaxUndoLevel = 100;
//////////////////////////////////////////////////////////////////////////
public int MaxUndoLevel
{
get
{
return _MaxUndoLevel;
}
set
{
_MaxUndoLevel = value;
}
}
//////////////////////////////////////////////////////////////////////////
private class UndoState
{
public UndoState(string Name, byte[] State, bool IsCompressed, int OrigSize)
{
this.Name = Name;
this.State = State;
this.IsCompressed = IsCompressed;
this.OrigSize = OrigSize;
}
public string Name;
public byte[] State;
public bool IsCompressed;
public int OrigSize;
}
private List<UndoState> UndoStates = new List<UndoState>();
private int UndoPointer = -1;
//////////////////////////////////////////////////////////////////////////
public bool SaveUndoState(string Name)
{
IsDirty = true;
string StrState = GetCurrentStateForUndo();
if (StrState == null) return false;
UndoPointer++;
while (UndoStates.Count > UndoPointer)
UndoStates.RemoveAt(UndoStates.Count - 1);
try
{
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
byte[] OrigBuf = enc.GetBytes(StrState);
byte[] CompBuf = WUtils.CompressBuffer(OrigBuf);
UndoState State;
if (CompBuf != null)
State = new UndoState(Name, CompBuf, true, OrigBuf.Length);
else
State = new UndoState(Name, OrigBuf, false, OrigBuf.Length);
UndoStates.Add(State);
if(UndoStates.Count > MaxUndoLevel)
{
UndoStates.RemoveAt(0);
UndoPointer--;
}
return true;
}
catch
{
UndoPointer--;
return false;
}
}
//////////////////////////////////////////////////////////////////////////
public virtual string GetCurrentStateForUndo()
{
return null;
}
//////////////////////////////////////////////////////////////////////////
public string GetUndo()
{
if (UndoPointer >= 0)
{
if (UndoPointer == UndoStates.Count - 1)
{
if (SaveUndoState("")) UndoPointer--;
}
UndoPointer--;
return GetUndoState(UndoPointer + 1);
}
else return null;
}
//////////////////////////////////////////////////////////////////////////
public string GetRedo()
{
if (UndoPointer < UndoStates.Count - 2)
{
UndoPointer++;
return GetUndoState(UndoPointer + 1);
}
else return null;
}
//////////////////////////////////////////////////////////////////////////
public void KillUndo()
{
UndoStates.Clear();
UndoPointer = -1;
}
//////////////////////////////////////////////////////////////////////////
public bool UndoAvailable
{
get
{
return UndoPointer >= 0;
}
}
//////////////////////////////////////////////////////////////////////////
public string UndoName
{
get
{
if (UndoPointer >= 0 && UndoPointer < UndoStates.Count)
return UndoStates[UndoPointer].Name;
else
return "";
}
}
//////////////////////////////////////////////////////////////////////////
public string RedoName
{
get
{
if (UndoPointer < UndoStates.Count - 2)
return UndoStates[UndoPointer+1].Name;
else
return "";
}
}
//////////////////////////////////////////////////////////////////////////
public bool RedoAvailable
{
get
{
return UndoPointer < UndoStates.Count - 2;
}
}
//////////////////////////////////////////////////////////////////////////
private string GetUndoState(int Pos)
{
if (Pos < 0 || Pos >= UndoStates.Count) return null;
UndoState State = UndoStates[Pos];
byte[] StrBuf;
if (State.IsCompressed) StrBuf = WUtils.DecompressBuffer(State.State, State.OrigSize);
else StrBuf = State.State;
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
return enc.GetString(StrBuf);
}
#endregion
#region Project selection
//////////////////////////////////////////////////////////////////////////
protected string GetProjectFile(string DefinitionFile, FormBase ParentForm)
{
if (DefinitionFile == null) return GetProjectFile(ParentForm);
try
{
string ProjectPath = "";
if (File.Exists(DefinitionFile))
{
using (StreamReader sr = new StreamReader(DefinitionFile, Encoding.Default, true))
{
string Line;
string Magic = "; $EDITOR_PROJECT_ROOT_DIR$ ";
while ((Line = sr.ReadLine()) != null)
{
if (Line.StartsWith(Magic))
{
ProjectPath = Line.Substring(Magic.Length).Trim();
break;
}
}
}
}
if (ProjectPath != "")
{
string FilePath = Path.GetDirectoryName(DefinitionFile);
ProjectPath = Path.GetFullPath(Path.Combine(FilePath, ProjectPath));
if (Directory.Exists(ProjectPath))
{
string[] ProjectFiles = Directory.GetFiles(ProjectPath, "*.wpr");
if (ProjectFiles.Length > 0)
{
Document.AddRecentProject(ProjectFiles[0]);
return ProjectFiles[0];
}
}
}
// not found, we'll scan all the directories in file path
string TestPath = Path.GetDirectoryName(DefinitionFile);
while (true)
{
string[] ProjectFiles = Directory.GetFiles(TestPath, "*.wpr");
if (ProjectFiles.Length > 0)
{
Document.AddRecentProject(ProjectFiles[0]);
return ProjectFiles[0];
}
int i = TestPath.LastIndexOfAny(new char[] { '\\', '/' });
if (i < 0) break;
TestPath = TestPath.Substring(0, i);
}
// still not found, ask user
return GetProjectFile(ParentForm);
}
catch (IOException)
{
return GetProjectFile(ParentForm);
}
catch (UnauthorizedAccessException)
{
return GetProjectFile(ParentForm);
}
}
//////////////////////////////////////////////////////////////////////////
protected string GetProjectFile(FormBase ParentForm)
{
ProjectSelectionForm dlg = new ProjectSelectionForm();
if (ParentForm != null)
dlg.AppMgr = ParentForm.AppMgr;
dlg.RecentFiles = Document.RecentProjects;
if (dlg.ShowDialog() == DialogResult.OK)
{
Document.AddRecentProject(dlg.FileName);
return dlg.FileName;
}
else return null;
}
private static List<string> _RecentProjects;
//////////////////////////////////////////////////////////////////////////
public static List<string> RecentProjects
{
get
{
if (_RecentProjects == null) _RecentProjects = new List<string>();
return _RecentProjects;
}
}
//////////////////////////////////////////////////////////////////////////
public static void AddRecentProject(string ProjectFile)
{
StringComparer Comparer = StringComparer.InvariantCultureIgnoreCase;
if (RecentProjects.BinarySearch(ProjectFile, Comparer) < 0)
{
RecentProjects.Add(ProjectFile);
RecentProjects.Sort(Comparer);
}
}
#endregion
}
}
| |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange (mailto:Stefan.Lange@pdfsharp.com)
// Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com)
// David Stephensen (mailto:David.Stephensen@pdfsharp.com)
//
// Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
namespace MigraDoc.DocumentObjectModel.Internals
{
/// <summary>
/// Base class of all value descriptor classes.
/// </summary>
public abstract class ValueDescriptor
{
internal ValueDescriptor(string valueName, Type valueType, Type memberType, MemberInfo memberInfo, VDFlags flags)
{
this.ValueName = valueName;
this.ValueType = valueType;
this.MemberType = memberType;
this.memberInfo = memberInfo;
this.flags = flags;
}
public object CreateValue()
{
ConstructorInfo constructorInfoObj = this.ValueType.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
return constructorInfoObj.Invoke(null);
//return this.ValueType.GetConstructor(Type.EmptyTypes).Invoke(null);
}
public abstract object GetValue(DocumentObject dom, GV flags);
public abstract void SetValue(DocumentObject dom, object val);
public abstract void SetNull(DocumentObject dom);
public abstract bool IsNull(DocumentObject dom);
internal static ValueDescriptor CreateValueDescriptor(MemberInfo memberInfo, DVAttribute attr)
{
VDFlags flags = VDFlags.None;
if (attr.RefOnly)
flags |= VDFlags.RefOnly;
string name = memberInfo.Name;
Type type;
if (memberInfo is FieldInfo)
type = ((FieldInfo)memberInfo).FieldType;
else
type = ((PropertyInfo)memberInfo).PropertyType;
if (type == typeof(NBool))
return new NullableDescriptor(name, typeof(Boolean), type, memberInfo, flags);
if (type == typeof(NInt))
return new NullableDescriptor(name, typeof(Int32), type, memberInfo, flags);
if (type == typeof(NDouble))
return new NullableDescriptor(name, typeof(Double), type, memberInfo, flags);
if (type == typeof(NString))
return new NullableDescriptor(name, typeof(String), type, memberInfo, flags);
if (type == typeof(String))
return new ValueTypeDescriptor(name, typeof(String), type, memberInfo, flags);
if (type == typeof(NEnum))
{
Type valueType = attr.Type;
Debug.Assert(valueType.IsSubclassOf(typeof(Enum)), "NEnum must have 'Type' attribute with the underlying type");
return new NullableDescriptor(name, valueType, type, memberInfo, flags);
}
if (type.IsSubclassOf(typeof(ValueType)))
return new ValueTypeDescriptor(name, type, type, memberInfo, flags);
if (typeof(DocumentObjectCollection).IsAssignableFrom(type))
return new DocumentObjectCollectionDescriptor(name, type, type, memberInfo, flags);
if (typeof(DocumentObject).IsAssignableFrom(type))
return new DocumentObjectDescriptor(name, type, type, memberInfo, flags);
Debug.Assert(false, type.FullName);
return null;
}
public bool IsRefOnly
{
get { return (this.flags & VDFlags.RefOnly) == VDFlags.RefOnly; }
}
public FieldInfo FieldInfo
{
get { return this.memberInfo as FieldInfo; }
}
public PropertyInfo PropertyInfo
{
get { return this.memberInfo as PropertyInfo; }
}
/// <summary>
/// Name of the value.
/// </summary>
public string ValueName;
/// <summary>
/// Type of the described value, e.g. typeof(Int32) for an NInt.
/// </summary>
public Type ValueType;
/// <summary>
/// Type of the described field or property, e.g. typeof(NInt) for an NInt.
/// </summary>
public Type MemberType;
/// <summary>
/// FieldInfo of the described field.
/// </summary>
protected MemberInfo memberInfo;
/// <summary>
/// Flags of the described field, e.g. RefOnly.
/// </summary>
VDFlags flags;
}
/// <summary>
/// Value descriptor of all nullable types.
/// </summary>
internal class NullableDescriptor : ValueDescriptor
{
internal NullableDescriptor(string valueName, Type valueType, Type fieldType, MemberInfo memberInfo, VDFlags flags)
: base(valueName, valueType, fieldType, memberInfo, flags)
{
}
public override object GetValue(DocumentObject dom, GV flags)
{
if (!Enum.IsDefined(typeof(GV), flags))
throw new InvalidEnumArgumentException("flags", (int)flags, typeof(GV));
object val;
if (FieldInfo != null)
val = FieldInfo.GetValue(dom);
else
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
INullableValue ival = (INullableValue)val;
if (ival.IsNull && flags == GV.GetNull)
return null;
return ival.GetValue();
}
public override void SetValue(DocumentObject dom, object value)
{
object val;
INullableValue ival;
if (FieldInfo != null)
{
val = FieldInfo.GetValue(dom);
ival = (INullableValue)val;
ival.SetValue(value);
FieldInfo.SetValue(dom, ival);
}
else
{
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
ival = (INullableValue)val;
ival.SetValue(value);
PropertyInfo.GetSetMethod(true).Invoke(dom, new object[] { ival });
}
}
public override void SetNull(DocumentObject dom)
{
object val;
INullableValue ival;
if (FieldInfo != null)
{
val = FieldInfo.GetValue(dom);
ival = (INullableValue)val;
ival.SetNull();
FieldInfo.SetValue(dom, ival);
}
else
{
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
ival = (INullableValue)val;
ival.SetNull();
PropertyInfo.GetSetMethod(true).Invoke(dom, new object[] { ival });
}
}
/// <summary>
/// Determines whether the given DocumentObject is null (not set).
/// </summary>
public override bool IsNull(DocumentObject dom)
{
object val;
if (FieldInfo != null)
val = FieldInfo.GetValue(dom);
else
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
return ((INullableValue)val).IsNull;
}
}
/// <summary>
/// Value descriptor of value types.
/// </summary>
internal class ValueTypeDescriptor : ValueDescriptor
{
internal ValueTypeDescriptor(string valueName, Type valueType, Type fieldType, MemberInfo memberInfo, VDFlags flags)
:
base(valueName, valueType, fieldType, memberInfo, flags)
{
}
public override object GetValue(DocumentObject dom, GV flags)
{
if (!Enum.IsDefined(typeof(GV), flags))
throw new InvalidEnumArgumentException("flags", (int)flags, typeof(GV));
object val;
if (FieldInfo != null)
val = FieldInfo.GetValue(dom);
else
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
INullableValue ival = val as INullableValue;
if (ival != null && ival.IsNull && flags == GV.GetNull)
return null;
return val;
}
public override void SetValue(DocumentObject dom, object value)
{
if (FieldInfo != null)
FieldInfo.SetValue(dom, value);
else
{
PropertyInfo.GetSetMethod(true).Invoke(dom, new object[] { value });
}
}
public override void SetNull(DocumentObject dom)
{
object val;
INullableValue ival;
if (FieldInfo != null)
{
val = FieldInfo.GetValue(dom);
ival = (INullableValue)val;
ival.SetNull();
FieldInfo.SetValue(dom, ival);
}
else
{
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
ival = (INullableValue)val;
ival.SetNull();
PropertyInfo.GetSetMethod(true).Invoke(dom, new object[] { ival });
}
}
/// <summary>
/// Determines whether the given DocumentObject is null (not set).
/// </summary>
public override bool IsNull(DocumentObject dom)
{
object val;
if (FieldInfo != null)
val = FieldInfo.GetValue(dom);
else
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes);
INullableValue ival = val as INullableValue;
if (ival != null)
return ival.IsNull;
return false;
}
}
/// <summary>
/// Value descriptor of DocumentObject.
/// </summary>
internal class DocumentObjectDescriptor : ValueDescriptor
{
internal DocumentObjectDescriptor(string valueName, Type valueType, Type fieldType, MemberInfo memberInfo, VDFlags flags)
:
base(valueName, valueType, fieldType, memberInfo, flags)
{
}
public override object GetValue(DocumentObject dom, GV flags)
{
if (!Enum.IsDefined(typeof(GV), flags))
throw new InvalidEnumArgumentException("flags", (int)flags, typeof(GV));
FieldInfo fieldInfo = FieldInfo;
DocumentObject val;
if (fieldInfo != null)
{
// Member is a field
val = FieldInfo.GetValue(dom) as DocumentObject;
if (val == null && flags == GV.ReadWrite)
{
val = CreateValue() as DocumentObject;
val.parent = dom;
FieldInfo.SetValue(dom, val);
return val;
}
}
else
{
// Member is a property
val = PropertyInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes) as DocumentObject;
}
if (val != null && (val.IsNull() && flags == GV.GetNull))
return null;
return val;
}
public override void SetValue(DocumentObject dom, object val)
{
FieldInfo fieldInfo = FieldInfo;
// Member is a field
if (fieldInfo != null)
{
fieldInfo.SetValue(dom, val);
return;
}
throw new InvalidOperationException("This value cannot be set.");
}
public override void SetNull(DocumentObject dom)
{
FieldInfo fieldInfo = FieldInfo;
DocumentObject val;
// Member is a field
if (fieldInfo != null)
{
val = FieldInfo.GetValue(dom) as DocumentObject;
if (val != null)
val.SetNull();
}
// Member is a property
//REVIEW KlPo4All: Wird das gebraucht?
if (PropertyInfo != null)
{
PropertyInfo propInfo = PropertyInfo;
val = propInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes) as DocumentObject;
if (val != null)
val.SetNull();
}
return;
}
/// <summary>
/// Determines whether the given DocumentObject is null (not set).
/// </summary>
public override bool IsNull(DocumentObject dom)
{
FieldInfo fieldInfo = FieldInfo;
DocumentObject val;
// Member is a field
if (fieldInfo != null)
{
val = FieldInfo.GetValue(dom) as DocumentObject;
if (val == null)
return true;
return val.IsNull();
}
// Member is a property
PropertyInfo propInfo = PropertyInfo;
val = propInfo.GetGetMethod(true).Invoke(dom, Type.EmptyTypes) as DocumentObject;
if (val != null)
val.IsNull();
return true;
}
}
/// <summary>
/// Value descriptor of DocumentObjectCollection.
/// </summary>
internal class DocumentObjectCollectionDescriptor : ValueDescriptor
{
internal DocumentObjectCollectionDescriptor(string valueName, Type valueType, Type fieldType, MemberInfo memberInfo, VDFlags flags)
:
base(valueName, valueType, fieldType, memberInfo, flags)
{
}
public override object GetValue(DocumentObject dom, GV flags)
{
if (!Enum.IsDefined(typeof(GV), flags))
throw new InvalidEnumArgumentException("flags", (int)flags, typeof(GV));
Debug.Assert(this.memberInfo is FieldInfo, "Properties of DocumentObjectCollection not allowed.");
DocumentObjectCollection val = FieldInfo.GetValue(dom) as DocumentObjectCollection;
if (val == null && flags == GV.ReadWrite)
{
val = CreateValue() as DocumentObjectCollection;
val.parent = dom;
FieldInfo.SetValue(dom, val);
return val;
}
if (val != null && val.IsNull() && flags == GV.GetNull)
return null;
return val;
}
public override void SetValue(DocumentObject dom, object val)
{
FieldInfo.SetValue(dom, val);
}
public override void SetNull(DocumentObject dom)
{
DocumentObjectCollection val = FieldInfo.GetValue(dom) as DocumentObjectCollection;
if (val != null)
val.SetNull();
}
/// <summary>
/// Determines whether the given DocumentObject is null (not set).
/// </summary>
public override bool IsNull(DocumentObject dom)
{
DocumentObjectCollection val = FieldInfo.GetValue(dom) as DocumentObjectCollection;
if (val == null)
return true;
return val.IsNull();
}
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.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;
using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// User
/// </summary>
[DataContract]
public partial class User : IEquatable<User>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="User" /> class.
/// </summary>
/// <param name="apiIpAddressMasks">A list of IP addresses whitelisted for any user with API Access permission. Without this list, each ip address must be authenticated by a user, which can be a pain for some servers..</param>
/// <param name="changeFtpPasswordTo">Supply a new FTP password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system. The FTP password cannot be the same as the normal password..</param>
/// <param name="changePasswordTo">Supply a new password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system..</param>
/// <param name="email">Email address of user.</param>
/// <param name="fullName">Full name of user. This is used solely for human assistance and so the UltraCart staff knows who they are calling when there is a problem..</param>
/// <param name="groups">A list of groups for this merchant and whether or not this user is a member of those groups..</param>
/// <param name="linkedAccounts">A list of linked accounts and whether or not this user is mirrored to any of those accounts..</param>
/// <param name="login">User name of user. Must be unique across a merchant account..</param>
/// <param name="loginHistories">A list of user logins over the past 90 days.</param>
/// <param name="notifications">A list of notifications the user receives..</param>
/// <param name="otpSerialNumber">OTP Serial Number such as Google Authenticator or Crypto Card..</param>
/// <param name="permissions">A list of permissions the user enjoys for accessing the backend of UltraCart..</param>
/// <param name="phone">Phone number of user. Please supply a valid phone number. When something breaks on your account, we need to be able to reach you..</param>
/// <param name="userId">User id is a unique identifier for this user.</param>
public User(List<string> apiIpAddressMasks = default(List<string>), string changeFtpPasswordTo = default(string), string changePasswordTo = default(string), string email = default(string), string fullName = default(string), List<UserGroupMembership> groups = default(List<UserGroupMembership>), List<LinkedAccount> linkedAccounts = default(List<LinkedAccount>), string login = default(string), List<UserLogin> loginHistories = default(List<UserLogin>), List<Notification> notifications = default(List<Notification>), string otpSerialNumber = default(string), List<Permission> permissions = default(List<Permission>), string phone = default(string), int? userId = default(int?))
{
this.ApiIpAddressMasks = apiIpAddressMasks;
this.ChangeFtpPasswordTo = changeFtpPasswordTo;
this.ChangePasswordTo = changePasswordTo;
this.Email = email;
this.FullName = fullName;
this.Groups = groups;
this.LinkedAccounts = linkedAccounts;
this.Login = login;
this.LoginHistories = loginHistories;
this.Notifications = notifications;
this.OtpSerialNumber = otpSerialNumber;
this.Permissions = permissions;
this.Phone = phone;
this.UserId = userId;
}
/// <summary>
/// A list of IP addresses whitelisted for any user with API Access permission. Without this list, each ip address must be authenticated by a user, which can be a pain for some servers.
/// </summary>
/// <value>A list of IP addresses whitelisted for any user with API Access permission. Without this list, each ip address must be authenticated by a user, which can be a pain for some servers.</value>
[DataMember(Name="api_ip_address_masks", EmitDefaultValue=false)]
public List<string> ApiIpAddressMasks { get; set; }
/// <summary>
/// Supply a new FTP password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system. The FTP password cannot be the same as the normal password.
/// </summary>
/// <value>Supply a new FTP password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system. The FTP password cannot be the same as the normal password.</value>
[DataMember(Name="change_ftp_password_to", EmitDefaultValue=false)]
public string ChangeFtpPasswordTo { get; set; }
/// <summary>
/// Supply a new password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system.
/// </summary>
/// <value>Supply a new password using this field. Password are stored using one-way encryption, so they are never available anywhere in the system.</value>
[DataMember(Name="change_password_to", EmitDefaultValue=false)]
public string ChangePasswordTo { get; set; }
/// <summary>
/// Email address of user
/// </summary>
/// <value>Email address of user</value>
[DataMember(Name="email", EmitDefaultValue=false)]
public string Email { get; set; }
/// <summary>
/// Full name of user. This is used solely for human assistance and so the UltraCart staff knows who they are calling when there is a problem.
/// </summary>
/// <value>Full name of user. This is used solely for human assistance and so the UltraCart staff knows who they are calling when there is a problem.</value>
[DataMember(Name="full_name", EmitDefaultValue=false)]
public string FullName { get; set; }
/// <summary>
/// A list of groups for this merchant and whether or not this user is a member of those groups.
/// </summary>
/// <value>A list of groups for this merchant and whether or not this user is a member of those groups.</value>
[DataMember(Name="groups", EmitDefaultValue=false)]
public List<UserGroupMembership> Groups { get; set; }
/// <summary>
/// A list of linked accounts and whether or not this user is mirrored to any of those accounts.
/// </summary>
/// <value>A list of linked accounts and whether or not this user is mirrored to any of those accounts.</value>
[DataMember(Name="linked_accounts", EmitDefaultValue=false)]
public List<LinkedAccount> LinkedAccounts { get; set; }
/// <summary>
/// User name of user. Must be unique across a merchant account.
/// </summary>
/// <value>User name of user. Must be unique across a merchant account.</value>
[DataMember(Name="login", EmitDefaultValue=false)]
public string Login { get; set; }
/// <summary>
/// A list of user logins over the past 90 days
/// </summary>
/// <value>A list of user logins over the past 90 days</value>
[DataMember(Name="login_histories", EmitDefaultValue=false)]
public List<UserLogin> LoginHistories { get; set; }
/// <summary>
/// A list of notifications the user receives.
/// </summary>
/// <value>A list of notifications the user receives.</value>
[DataMember(Name="notifications", EmitDefaultValue=false)]
public List<Notification> Notifications { get; set; }
/// <summary>
/// OTP Serial Number such as Google Authenticator or Crypto Card.
/// </summary>
/// <value>OTP Serial Number such as Google Authenticator or Crypto Card.</value>
[DataMember(Name="otp_serial_number", EmitDefaultValue=false)]
public string OtpSerialNumber { get; set; }
/// <summary>
/// A list of permissions the user enjoys for accessing the backend of UltraCart.
/// </summary>
/// <value>A list of permissions the user enjoys for accessing the backend of UltraCart.</value>
[DataMember(Name="permissions", EmitDefaultValue=false)]
public List<Permission> Permissions { get; set; }
/// <summary>
/// Phone number of user. Please supply a valid phone number. When something breaks on your account, we need to be able to reach you.
/// </summary>
/// <value>Phone number of user. Please supply a valid phone number. When something breaks on your account, we need to be able to reach you.</value>
[DataMember(Name="phone", EmitDefaultValue=false)]
public string Phone { get; set; }
/// <summary>
/// User id is a unique identifier for this user
/// </summary>
/// <value>User id is a unique identifier for this user</value>
[DataMember(Name="user_id", EmitDefaultValue=false)]
public int? UserId { 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 User {\n");
sb.Append(" ApiIpAddressMasks: ").Append(ApiIpAddressMasks).Append("\n");
sb.Append(" ChangeFtpPasswordTo: ").Append(ChangeFtpPasswordTo).Append("\n");
sb.Append(" ChangePasswordTo: ").Append(ChangePasswordTo).Append("\n");
sb.Append(" Email: ").Append(Email).Append("\n");
sb.Append(" FullName: ").Append(FullName).Append("\n");
sb.Append(" Groups: ").Append(Groups).Append("\n");
sb.Append(" LinkedAccounts: ").Append(LinkedAccounts).Append("\n");
sb.Append(" Login: ").Append(Login).Append("\n");
sb.Append(" LoginHistories: ").Append(LoginHistories).Append("\n");
sb.Append(" Notifications: ").Append(Notifications).Append("\n");
sb.Append(" OtpSerialNumber: ").Append(OtpSerialNumber).Append("\n");
sb.Append(" Permissions: ").Append(Permissions).Append("\n");
sb.Append(" Phone: ").Append(Phone).Append("\n");
sb.Append(" UserId: ").Append(UserId).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 virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as User);
}
/// <summary>
/// Returns true if User instances are equal
/// </summary>
/// <param name="input">Instance of User to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(User input)
{
if (input == null)
return false;
return
(
this.ApiIpAddressMasks == input.ApiIpAddressMasks ||
this.ApiIpAddressMasks != null &&
this.ApiIpAddressMasks.SequenceEqual(input.ApiIpAddressMasks)
) &&
(
this.ChangeFtpPasswordTo == input.ChangeFtpPasswordTo ||
(this.ChangeFtpPasswordTo != null &&
this.ChangeFtpPasswordTo.Equals(input.ChangeFtpPasswordTo))
) &&
(
this.ChangePasswordTo == input.ChangePasswordTo ||
(this.ChangePasswordTo != null &&
this.ChangePasswordTo.Equals(input.ChangePasswordTo))
) &&
(
this.Email == input.Email ||
(this.Email != null &&
this.Email.Equals(input.Email))
) &&
(
this.FullName == input.FullName ||
(this.FullName != null &&
this.FullName.Equals(input.FullName))
) &&
(
this.Groups == input.Groups ||
this.Groups != null &&
this.Groups.SequenceEqual(input.Groups)
) &&
(
this.LinkedAccounts == input.LinkedAccounts ||
this.LinkedAccounts != null &&
this.LinkedAccounts.SequenceEqual(input.LinkedAccounts)
) &&
(
this.Login == input.Login ||
(this.Login != null &&
this.Login.Equals(input.Login))
) &&
(
this.LoginHistories == input.LoginHistories ||
this.LoginHistories != null &&
this.LoginHistories.SequenceEqual(input.LoginHistories)
) &&
(
this.Notifications == input.Notifications ||
this.Notifications != null &&
this.Notifications.SequenceEqual(input.Notifications)
) &&
(
this.OtpSerialNumber == input.OtpSerialNumber ||
(this.OtpSerialNumber != null &&
this.OtpSerialNumber.Equals(input.OtpSerialNumber))
) &&
(
this.Permissions == input.Permissions ||
this.Permissions != null &&
this.Permissions.SequenceEqual(input.Permissions)
) &&
(
this.Phone == input.Phone ||
(this.Phone != null &&
this.Phone.Equals(input.Phone))
) &&
(
this.UserId == input.UserId ||
(this.UserId != null &&
this.UserId.Equals(input.UserId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.ApiIpAddressMasks != null)
hashCode = hashCode * 59 + this.ApiIpAddressMasks.GetHashCode();
if (this.ChangeFtpPasswordTo != null)
hashCode = hashCode * 59 + this.ChangeFtpPasswordTo.GetHashCode();
if (this.ChangePasswordTo != null)
hashCode = hashCode * 59 + this.ChangePasswordTo.GetHashCode();
if (this.Email != null)
hashCode = hashCode * 59 + this.Email.GetHashCode();
if (this.FullName != null)
hashCode = hashCode * 59 + this.FullName.GetHashCode();
if (this.Groups != null)
hashCode = hashCode * 59 + this.Groups.GetHashCode();
if (this.LinkedAccounts != null)
hashCode = hashCode * 59 + this.LinkedAccounts.GetHashCode();
if (this.Login != null)
hashCode = hashCode * 59 + this.Login.GetHashCode();
if (this.LoginHistories != null)
hashCode = hashCode * 59 + this.LoginHistories.GetHashCode();
if (this.Notifications != null)
hashCode = hashCode * 59 + this.Notifications.GetHashCode();
if (this.OtpSerialNumber != null)
hashCode = hashCode * 59 + this.OtpSerialNumber.GetHashCode();
if (this.Permissions != null)
hashCode = hashCode * 59 + this.Permissions.GetHashCode();
if (this.Phone != null)
hashCode = hashCode * 59 + this.Phone.GetHashCode();
if (this.UserId != null)
hashCode = hashCode * 59 + this.UserId.GetHashCode();
return hashCode;
}
}
/// <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;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using MigAz.Azure.UserControls;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MigAz.Azure.Forms
{
public partial class AzureNewOrExistingLoginContextDialog : Form
{
private bool _IsInitializing = false;
private AzureLoginContextViewer _AzureLoginContextViewer;
private List<AzureEnvironment> _AzureEnvironments;
private List<AzureEnvironment> _UserDefinedAzureEnvironments;
public AzureNewOrExistingLoginContextDialog()
{
InitializeComponent();
}
public async Task InitializeDialog(AzureLoginContextViewer azureLoginContextViewer, List<AzureEnvironment> azureEnvironments, List<AzureEnvironment> userDefinedAzureEnvironments)
{
try {
_IsInitializing = true;
_AzureLoginContextViewer = azureLoginContextViewer;
_AzureEnvironments = azureEnvironments;
_UserDefinedAzureEnvironments = userDefinedAzureEnvironments;
await azureArmLoginControl1.BindContext(azureLoginContextViewer.AzureContext, azureEnvironments, userDefinedAzureEnvironments);
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "Start AzureSubscriptionContextDialog InitializeDialog");
lblSameEnviroronment.Text = azureLoginContextViewer.ExistingContext.AzureEnvironment.ToString();
lblSameTenant.Text = azureLoginContextViewer.ExistingContext.AzureTenant.ToString();
lblSameSubscription.Text = azureLoginContextViewer.ExistingContext.AzureSubscription.ToString();
lblSameEnvironment2.Text = azureLoginContextViewer.ExistingContext.AzureEnvironment.ToString();
if (azureLoginContextViewer.ExistingContext.TokenProvider != null && azureLoginContextViewer.ExistingContext.TokenProvider.LastUserInfo != null)
{
lblSameUsername.Text = azureLoginContextViewer.ExistingContext.TokenProvider.LastUserInfo.DisplayableId;
lblSameUsername2.Text = azureLoginContextViewer.ExistingContext.TokenProvider.LastUserInfo.DisplayableId;
}
int subscriptionCount = 0;
cboTenant.Items.Clear();
if (azureLoginContextViewer.ExistingContext.AzureRetriever != null && azureLoginContextViewer.ExistingContext.TokenProvider != null)
{
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "Loading Azure Tenants");
foreach (AzureTenant azureTenant in await azureLoginContextViewer.ExistingContext.GetAzureARMTenants())
{
subscriptionCount += azureTenant.Subscriptions.Count;
if (azureTenant.Subscriptions.Count > 0) // Only add Tenants that have one or more Subscriptions
{
if (azureTenant.Subscriptions.Count == 1 && azureTenant.Subscriptions[0] == azureLoginContextViewer.ExistingContext.AzureSubscription)
{
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "Not adding Azure Tenant '" + azureTenant.ToString() + "', as it has only one subscription, which is the same as the Existing Azure Context.");
}
else
{
cboTenant.Items.Add(azureTenant);
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "Added Azure Tenant '" + azureTenant.ToString() + "'");
}
}
else
{
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "Not adding Azure Tenant '" + azureTenant.ToString() + "'. Contains no subscriptions.");
}
}
cboTenant.Enabled = true;
if (azureLoginContextViewer.SelectedAzureContext != null && azureLoginContextViewer.SelectedAzureContext.AzureTenant != null)
{
foreach (AzureTenant azureTenant in cboTenant.Items)
{
if (azureLoginContextViewer.SelectedAzureContext.AzureTenant == azureTenant)
cboTenant.SelectedItem = azureTenant;
}
}
}
rbSameUserDifferentSubscription.Enabled = subscriptionCount > 1;
switch (azureLoginContextViewer.AzureContextSelectedType)
{
case AzureContextSelectedType.ExistingContext:
rbExistingContext.Checked = true;
break;
case AzureContextSelectedType.SameUserDifferentSubscription:
if (rbSameUserDifferentSubscription.Enabled)
rbSameUserDifferentSubscription.Checked = true;
else
rbExistingContext.Checked = true;
break;
case AzureContextSelectedType.NewContext:
rbNewContext.Checked = true;
break;
}
azureLoginContextViewer.ExistingContext.LogProvider.WriteLog("InitializeDialog", "End AzureSubscriptionContextDialog InitializeDialog");
}
finally
{
_IsInitializing = false;
}
if (rbSameUserDifferentSubscription.Checked && cboTenant.SelectedIndex == -1 && cboTenant.Items.Count > 0)
{
cboTenant.SelectedIndex = 0;
}
azureLoginContextViewer.ExistingContext.StatusProvider.UpdateStatus("Ready");
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void rbExistingContext_CheckedChanged(object sender, EventArgs e)
{
if (rbExistingContext.Checked)
{
cboTenant.Enabled = false;
cboSubscription.Enabled = false;
_AzureLoginContextViewer.AzureContextSelectedType = AzureContextSelectedType.ExistingContext;
_AzureLoginContextViewer.AzureContext.LoginPromptBehavior = PromptBehavior.Auto;
}
_AzureLoginContextViewer.UpdateLabels();
}
private async void rbSameUserDifferentSubscription_CheckedChanged(object sender, EventArgs e)
{
if (!_IsInitializing)
{
if (rbSameUserDifferentSubscription.Checked)
{
_AzureLoginContextViewer.AzureContext.TokenProvider.LastUserInfo = _AzureLoginContextViewer.ExistingContext.TokenProvider.LastUserInfo;
_AzureLoginContextViewer.AzureContext.AzureEnvironment = _AzureLoginContextViewer.ExistingContext.AzureEnvironment;
_AzureLoginContextViewer.AzureContextSelectedType = AzureContextSelectedType.SameUserDifferentSubscription;
_AzureLoginContextViewer.AzureContext.LoginPromptBehavior = PromptBehavior.Auto;
if (cboTenant.SelectedIndex == -1 && cboTenant.Items.Count > 0)
{
cboTenant.SelectedIndex = 0;
}
if (cboTenant.SelectedItem != null)
{
AzureTenant azureTenant = (AzureTenant)cboTenant.SelectedItem;
if (_AzureLoginContextViewer.AzureContext.AzureTenant != azureTenant)
{
await _AzureLoginContextViewer.AzureContext.SetTenantContext(azureTenant);
}
}
if (cboSubscription.SelectedIndex == -1 && cboSubscription.Items.Count > 0)
{
cboSubscription.SelectedIndex = 0;
}
if (cboSubscription.SelectedItem != null)
{
AzureSubscription azureSubscription = (AzureSubscription)cboSubscription.SelectedItem;
if (_AzureLoginContextViewer.AzureContext.AzureSubscription != azureSubscription)
{
await _AzureLoginContextViewer.AzureContext.SetSubscriptionContext(azureSubscription);
}
}
}
}
await azureArmLoginControl1.BindContext(_AzureLoginContextViewer.AzureContext, _AzureEnvironments, _UserDefinedAzureEnvironments);
cboTenant.Enabled = rbSameUserDifferentSubscription.Checked;
cboSubscription.Enabled = rbSameUserDifferentSubscription.Checked;
_AzureLoginContextViewer.UpdateLabels();
}
private async void rbNewContext_CheckedChanged(object sender, EventArgs e)
{
if (rbNewContext.Checked)
{
cboTenant.Enabled = false;
cboSubscription.Enabled = false;
_AzureLoginContextViewer.AzureContextSelectedType = AzureContextSelectedType.NewContext;
_AzureLoginContextViewer.AzureContext.LoginPromptBehavior = PromptBehavior.SelectAccount;
}
await azureArmLoginControl1.BindContext(_AzureLoginContextViewer.AzureContext, _AzureEnvironments, _UserDefinedAzureEnvironments);
azureArmLoginControl1.Enabled = rbNewContext.Checked;
_AzureLoginContextViewer.UpdateLabels();
}
private void AzureNewOrExistingLoginContextDialog_FormClosing(object sender, FormClosingEventArgs e)
{
bool isValidTargetContext = false;
if (rbExistingContext.Checked)
{
isValidTargetContext = true;
}
else if (rbSameUserDifferentSubscription.Checked)
{
isValidTargetContext = cboSubscription.SelectedIndex >= 0;
}
else if (rbNewContext.Checked)
{
isValidTargetContext = _AzureLoginContextViewer.AzureContext.AzureSubscription != null;
}
if (!isValidTargetContext)
{
e.Cancel = true;
MessageBox.Show("You must have a valid target Azure Subscription selected.");
}
}
private void cboTenant_SelectedIndexChanged(object sender, EventArgs e)
{
cboSubscription.Items.Clear();
if (cboTenant.SelectedItem != null)
{
AzureTenant azureTenant = (AzureTenant)cboTenant.SelectedItem;
foreach (AzureSubscription azureSubscription in azureTenant.Subscriptions)
{
if (azureSubscription != _AzureLoginContextViewer.ExistingContext.AzureSubscription) // Do not add if same as existing subscription. Combobox intent is to pick a different subscription.
cboSubscription.Items.Add(azureSubscription);
}
if (cboSubscription.Items.Count > 0)
cboSubscription.SelectedIndex = 0;
}
}
private async void cboSubscription_SelectedIndexChanged(object sender, EventArgs e)
{
AzureSubscription selectedSubscription = (AzureSubscription)cboSubscription.SelectedItem;
await _AzureLoginContextViewer.AzureContext.SetSubscriptionContext(selectedSubscription);
}
}
}
| |
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using Avro.IO;
namespace Avro.Generic
{
/// <summary>
/// Defines the signature for a function that writes an object.
/// </summary>
/// <typeparam name="T">Type of object to write.</typeparam>
/// <param name="t">Object to write.</param>
public delegate void Writer<T>(T t);
/// <summary>
/// A typesafe wrapper around DefaultWriter. While a specific object of DefaultWriter
/// allows the client to serialize a generic type, an object of this class allows
/// only a single type of object to be serialized through it.
/// </summary>
/// <typeparam name="T">The type of object to be serialized.</typeparam>
public class GenericWriter<T> : DatumWriter<T>
{
private readonly DefaultWriter writer;
/// <summary>
/// Initializes a new instance of the <see cref="GenericWriter{T}"/> class.
/// </summary>
/// <param name="schema">Schema to use when writing.</param>
public GenericWriter(Schema schema) : this(new DefaultWriter(schema))
{
}
/// <inheritdoc/>
public Schema Schema { get { return writer.Schema; } }
/// <summary>
/// Initializes a new instance of the <see cref="GenericWriter{T}"/> class from a
/// <see cref="DefaultWriter"/>.
/// </summary>
/// <param name="writer">Write to initialize this new writer from.</param>
public GenericWriter(DefaultWriter writer)
{
this.writer = writer;
}
/// <summary>
/// Serializes the given object using this writer's schema.
/// </summary>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder to use for serializing</param>
public void Write(T value, Encoder encoder)
{
writer.Write(value, encoder);
}
}
/// <summary>
/// A General purpose writer for serializing objects into a Stream using
/// Avro. This class implements a default way of serializing objects. But
/// one can derive a class from this and override different methods to
/// acheive results that are different from the default implementation.
/// </summary>
public class DefaultWriter
{
/// <summary>
/// Schema that this object uses to write datum.
/// </summary>
public Schema Schema { get; private set; }
/// <summary>
/// Constructs a generic writer for the given schema.
/// </summary>
/// <param name="schema">The schema for the object to be serialized</param>
public DefaultWriter(Schema schema)
{
Schema = schema;
}
/// <summary>
/// Examines the <see cref="Schema"/> and dispatches the actual work to one
/// of the other methods of this class. This allows the derived
/// classes to override specific methods and get custom results.
/// </summary>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder to use during serialization</param>
public void Write<T>(T value, Encoder encoder)
{
Write(Schema, value, encoder);
}
/// <summary>
/// Examines the schema and dispatches the actual work to one
/// of the other methods of this class. This allows the derived
/// classes to override specific methods and get custom results.
/// </summary>
/// <param name="schema">The schema to use for serializing</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder to use during serialization</param>
public virtual void Write(Schema schema, object value, Encoder encoder)
{
switch (schema.Tag)
{
case Schema.Type.Null:
WriteNull(value, encoder);
break;
case Schema.Type.Boolean:
Write<bool>(value, schema.Tag, encoder.WriteBoolean);
break;
case Schema.Type.Int:
Write<int>(value, schema.Tag, encoder.WriteInt);
break;
case Schema.Type.Long:
Write<long>(value, schema.Tag, encoder.WriteLong);
break;
case Schema.Type.Float:
Write<float>(value, schema.Tag, encoder.WriteFloat);
break;
case Schema.Type.Double:
Write<double>(value, schema.Tag, encoder.WriteDouble);
break;
case Schema.Type.String:
Write<string>(value, schema.Tag, encoder.WriteString);
break;
case Schema.Type.Bytes:
Write<byte[]>(value, schema.Tag, encoder.WriteBytes);
break;
case Schema.Type.Record:
case Schema.Type.Error:
WriteRecord(schema as RecordSchema, value, encoder);
break;
case Schema.Type.Enumeration:
WriteEnum(schema as EnumSchema, value, encoder);
break;
case Schema.Type.Fixed:
WriteFixed(schema as FixedSchema, value, encoder);
break;
case Schema.Type.Array:
WriteArray(schema as ArraySchema, value, encoder);
break;
case Schema.Type.Map:
WriteMap(schema as MapSchema, value, encoder);
break;
case Schema.Type.Union:
WriteUnion(schema as UnionSchema, value, encoder);
break;
case Schema.Type.Logical:
WriteLogical(schema as LogicalSchema, value, encoder);
break;
default:
Error(schema, value);
break;
}
}
/// <summary>
/// Serializes a "null"
/// </summary>
/// <param name="value">The object to be serialized using null schema</param>
/// <param name="encoder">The encoder to use while serialization</param>
protected virtual void WriteNull(object value, Encoder encoder)
{
if (value != null) throw TypeMismatch(value, "null", "null");
}
/// <summary>
/// A generic method to serialize primitive Avro types.
/// </summary>
/// <typeparam name="T">Type of the C# type to be serialized</typeparam>
/// <param name="value">The value to be serialized</param>
/// <param name="tag">The schema type tag</param>
/// <param name="writer">The writer which should be used to write the given type.</param>
protected virtual void Write<T>(object value, Schema.Type tag, Writer<T> writer)
{
if (!(value is T)) throw TypeMismatch(value, tag.ToString(), typeof(T).ToString());
writer((T)value);
}
/// <summary>
/// Serialized a record using the given RecordSchema. It uses GetField method
/// to extract the field value from the given object.
/// </summary>
/// <param name="schema">The RecordSchema to use for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The Encoder for serialization</param>
protected virtual void WriteRecord(RecordSchema schema, object value, Encoder encoder)
{
EnsureRecordObject(schema, value);
foreach (Field field in schema)
{
try
{
object obj = GetField(value, field.Name, field.Pos);
Write(field.Schema, obj, encoder);
}
catch (Exception ex)
{
throw new AvroException(ex.Message + " in field " + field.Name, ex);
}
}
}
/// <summary>
/// Ensures that the given value is a record and that it corresponds to the given schema.
/// Throws an exception if either of those assertions are false.
/// </summary>
/// <param name="s">Schema associated with the record</param>
/// <param name="value">Ensure this object is a record</param>
protected virtual void EnsureRecordObject(RecordSchema s, object value)
{
if (value == null || !(value is GenericRecord) || !(value as GenericRecord).Schema.Equals(s))
{
throw TypeMismatch(value, "record", "GenericRecord");
}
}
/// <summary>
/// Extracts the field value from the given object. In this default implementation,
/// value should be of type GenericRecord.
/// </summary>
/// <param name="value">The record value from which the field needs to be extracted</param>
/// <param name="fieldName">The name of the field in the record</param>
/// <param name="fieldPos">The position of field in the record</param>
/// <returns></returns>
protected virtual object GetField(object value, string fieldName, int fieldPos)
{
GenericRecord d = value as GenericRecord;
return d.GetValue(fieldPos);
}
/// <summary>
/// Serializes an enumeration. The default implementation expectes the value to be string whose
/// value is the name of the enumeration.
/// </summary>
/// <param name="es">The EnumSchema for serialization</param>
/// <param name="value">Value to be written</param>
/// <param name="encoder">Encoder for serialization</param>
protected virtual void WriteEnum(EnumSchema es, object value, Encoder encoder)
{
if (value == null || !(value is GenericEnum) || !(value as GenericEnum).Schema.Equals(es))
throw TypeMismatch(value, "enum", "GenericEnum");
encoder.WriteEnum(es.Ordinal((value as GenericEnum).Value));
}
/// <summary>
/// Serialized an array. The default implementation calls EnsureArrayObject() to ascertain that the
/// given value is an array. It then calls GetArrayLength() and GetArrayElement()
/// to access the members of the array and then serialize them.
/// </summary>
/// <param name="schema">The ArraySchema for serialization</param>
/// <param name="value">The value being serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteArray(ArraySchema schema, object value, Encoder encoder)
{
EnsureArrayObject(value);
long l = GetArrayLength(value);
encoder.WriteArrayStart();
encoder.SetItemCount(l);
for (long i = 0; i < l; i++)
{
encoder.StartItem();
Write(schema.ItemSchema, GetArrayElement(value, i), encoder);
}
encoder.WriteArrayEnd();
}
/// <summary>
/// Checks if the given object is an array. If it is a valid array, this function returns normally. Otherwise,
/// it throws an exception. The default implementation checks if the value is an array.
/// </summary>
/// <param name="value"></param>
protected virtual void EnsureArrayObject(object value)
{
if (value == null || !(value is Array)) throw TypeMismatch(value, "array", "Array");
}
/// <summary>
/// Returns the length of an array. The default implementation requires the object
/// to be an array of objects and returns its length. The defaul implementation
/// gurantees that EnsureArrayObject() has been called on the value before this
/// function is called.
/// </summary>
/// <param name="value">The object whose array length is required</param>
/// <returns>The array length of the given object</returns>
protected virtual long GetArrayLength(object value)
{
return (value as Array).Length;
}
/// <summary>
/// Returns the element at the given index from the given array object. The default implementation
/// requires that the value is an object array and returns the element in that array. The defaul implementation
/// gurantees that EnsureArrayObject() has been called on the value before this
/// function is called.
/// </summary>
/// <param name="value">The array object</param>
/// <param name="index">The index to look for</param>
/// <returns>The array element at the index</returns>
protected virtual object GetArrayElement(object value, long index)
{
return (value as Array).GetValue(index);
}
/// <summary>
/// Serialized a map. The default implementation first ensure that the value is indeed a map and then uses
/// GetMapSize() and GetMapElements() to access the contents of the map.
/// </summary>
/// <param name="schema">The MapSchema for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteMap(MapSchema schema, object value, Encoder encoder)
{
EnsureMapObject(value);
IDictionary<string, object> vv = (IDictionary<string, object>)value;
encoder.WriteMapStart();
encoder.SetItemCount(GetMapSize(value));
foreach (KeyValuePair<string, object> obj in GetMapValues(vv))
{
encoder.StartItem();
encoder.WriteString(obj.Key);
Write(schema.ValueSchema, obj.Value, encoder);
}
encoder.WriteMapEnd();
}
/// <summary>
/// Checks if the given object is a map. If it is a valid map, this function returns normally. Otherwise,
/// it throws an exception. The default implementation checks if the value is an IDictionary<string, object>.
/// </summary>
/// <param name="value"></param>
protected virtual void EnsureMapObject(object value)
{
if (value == null || !(value is IDictionary<string, object>)) throw TypeMismatch(value, "map", "IDictionary<string, object>");
}
/// <summary>
/// Returns the size of the map object. The default implementation gurantees that EnsureMapObject has been
/// successfully called with the given value. The default implementation requires the value
/// to be an IDictionary<string, object> and returns the number of elements in it.
/// </summary>
/// <param name="value">The map object whose size is desired</param>
/// <returns>The size of the given map object</returns>
protected virtual long GetMapSize(object value)
{
return (value as IDictionary<string, object>).Count;
}
/// <summary>
/// Returns the contents of the given map object. The default implementation guarantees that EnsureMapObject
/// has been called with the given value. The defualt implementation of this method requires that
/// the value is an IDictionary<string, object> and returns its contents.
/// </summary>
/// <param name="value">The map object whose size is desired</param>
/// <returns>The contents of the given map object</returns>
protected virtual IEnumerable<KeyValuePair<string, object>> GetMapValues(object value)
{
return value as IDictionary<string, object>;
}
/// <summary>
/// Resolves the given value against the given UnionSchema and serializes the object against
/// the resolved schema member. The default implementation of this method uses
/// ResolveUnion to find the member schema within the UnionSchema.
/// </summary>
/// <param name="us">The UnionSchema to resolve against</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteUnion(UnionSchema us, object value, Encoder encoder)
{
int index = ResolveUnion(us, value);
encoder.WriteUnionIndex(index);
Write(us[index], value, encoder);
}
/// <summary>
/// Finds the branch within the given UnionSchema that matches the given object. The default implementation
/// calls Matches() method in the order of branches within the UnionSchema. If nothing matches, throws
/// an exception.
/// </summary>
/// <param name="us">The UnionSchema to resolve against</param>
/// <param name="obj">The object that should be used in matching</param>
/// <returns></returns>
protected virtual int ResolveUnion(UnionSchema us, object obj)
{
for (int i = 0; i < us.Count; i++)
{
if (Matches(us[i], obj)) return i;
}
throw new AvroException("Cannot find a match for " + obj.GetType() + " in " + us);
}
/// <summary>
/// Serializes a logical value object by using the underlying logical type to convert the value
/// to its base value.
/// </summary>
/// <param name="ls">The schema for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteLogical(LogicalSchema ls, object value, Encoder encoder)
{
Write(ls.BaseSchema, ls.LogicalType.ConvertToBaseValue(value, ls), encoder);
}
/// <summary>
/// Serialized a fixed object. The default implementation requires that the value is
/// a GenericFixed object with an identical schema as es.
/// </summary>
/// <param name="es">The schema for serialization</param>
/// <param name="value">The value to be serialized</param>
/// <param name="encoder">The encoder for serialization</param>
protected virtual void WriteFixed(FixedSchema es, object value, Encoder encoder)
{
if (value == null || !(value is GenericFixed) || !(value as GenericFixed).Schema.Equals(es))
{
throw TypeMismatch(value, "fixed", "GenericFixed");
}
GenericFixed ba = (GenericFixed)value;
encoder.WriteFixed(ba.Value);
}
/// <summary>
/// Creates a new <see cref="AvroException"/> and uses the provided parameters to build an
/// exception message indicathing there was a type mismatch.
/// </summary>
/// <param name="obj">Object whose type does not the expected type</param>
/// <param name="schemaType">Schema that we tried to write against</param>
/// <param name="type">Type that we expected</param>
/// <returns>A new <see cref="AvroException"/> indicating a type mismatch.</returns>
protected AvroException TypeMismatch(object obj, string schemaType, string type)
{
return new AvroException(type + " required to write against " + schemaType + " schema but found " + (null == obj ? "null" : obj.GetType().ToString()) );
}
private void Error(Schema schema, Object value)
{
throw new AvroTypeException("Not a " + schema + ": " + value);
}
/// <summary>
/// Tests whether the given schema an object are compatible.
/// </summary>
/// <remarks>
/// FIXME: This method of determining the Union branch has problems. If the data is IDictionary<string, object>
/// if there are two branches one with record schema and the other with map, it choose the first one. Similarly if
/// the data is byte[] and there are fixed and bytes schemas as branches, it choose the first one that matches.
/// Also it does not recognize the arrays of primitive types.
/// </remarks>
/// <param name="sc">Schema to compare</param>
/// <param name="obj">Object to compare</param>
/// <returns>True if the two parameters are compatible, false otherwise.</returns>
protected virtual bool Matches(Schema sc, object obj)
{
if (obj == null && sc.Tag != Avro.Schema.Type.Null) return false;
switch (sc.Tag)
{
case Schema.Type.Null:
return obj == null;
case Schema.Type.Boolean:
return obj is bool;
case Schema.Type.Int:
return obj is int;
case Schema.Type.Long:
return obj is long;
case Schema.Type.Float:
return obj is float;
case Schema.Type.Double:
return obj is double;
case Schema.Type.Bytes:
return obj is byte[];
case Schema.Type.String:
return obj is string;
case Schema.Type.Record:
//return obj is GenericRecord && (obj as GenericRecord).Schema.Equals(s);
return obj is GenericRecord && (obj as GenericRecord).Schema.SchemaName.Equals((sc as RecordSchema).SchemaName);
case Schema.Type.Enumeration:
//return obj is GenericEnum && (obj as GenericEnum).Schema.Equals(s);
return obj is GenericEnum && (obj as GenericEnum).Schema.SchemaName.Equals((sc as EnumSchema).SchemaName);
case Schema.Type.Array:
return obj is Array && !(obj is byte[]);
case Schema.Type.Map:
return obj is IDictionary<string, object>;
case Schema.Type.Union:
return false; // Union directly within another union not allowed!
case Schema.Type.Fixed:
//return obj is GenericFixed && (obj as GenericFixed).Schema.Equals(s);
return obj is GenericFixed && (obj as GenericFixed).Schema.SchemaName.Equals((sc as FixedSchema).SchemaName);
case Schema.Type.Logical:
return (sc as LogicalSchema).LogicalType.IsInstanceOfLogicalType(obj);
default:
throw new AvroException("Unknown schema type: " + sc.Tag);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using AspNetCore.Identity.MongoDB;
using IdentityModel;
using IdentityServer4.Events;
using IdentityServer4.Services;
using IdentityServer4.Stores;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
namespace IdSrv4.Controllers.Account
{
[SecurityHeaders]
[AllowAnonymous]
public class ExternalController : Controller
{
private readonly UserManager<MongoIdentityUser> _userManager;
private readonly IIdentityServerInteractionService _interaction;
private readonly IClientStore _clientStore;
private readonly IEventService _events;
public ExternalController(
IIdentityServerInteractionService interaction,
IClientStore clientStore,
IEventService events,
UserManager<MongoIdentityUser> userManager)
{
_userManager = userManager;
_interaction = interaction;
_clientStore = clientStore;
_events = events;
}
/// <summary>
/// initiate roundtrip to external authentication provider
/// </summary>
[HttpGet]
public async Task<IActionResult> Challenge(string provider, string returnUrl)
{
if (string.IsNullOrEmpty(returnUrl)) returnUrl = "~/";
// validate returnUrl - either it is a valid OIDC URL or back to a local page
if (Url.IsLocalUrl(returnUrl) == false && _interaction.IsValidReturnUrl(returnUrl) == false)
{
// user might have clicked on a malicious link - should be logged
throw new Exception("invalid return URL");
}
if (AccountOptions.WindowsAuthenticationSchemeName == provider)
{
// windows authentication needs special handling
return await ProcessWindowsLoginAsync(returnUrl);
}
else
{
// start challenge and roundtrip the return URL and scheme
var props = new AuthenticationProperties
{
RedirectUri = Url.Action(nameof(Callback)),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", provider },
}
};
return Challenge(props, provider);
}
}
/// <summary>
/// Post processing of external authentication
/// </summary>
[HttpGet]
public async Task<IActionResult> Callback()
{
// read external identity from the temporary cookie
var result = await HttpContext.AuthenticateAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);
if (result?.Succeeded != true)
{
throw new Exception("External authentication error");
}
// lookup our user and external provider info
var (user, provider, providerUserId, claims) = await FindUserFromExternalProvider(result);
if (user == null)
{
// this might be where you might initiate a custom workflow for user registration
// in this sample we don't show how that would be done, as our sample implementation
// simply auto-provisions new external user
user = await AutoProvisionUser(provider, providerUserId, claims);
}
// this allows us to collect any additonal claims or properties
// for the specific prtotocols used and store them in the local auth cookie.
// this is typically used to store data needed for signout from those protocols.
var additionalLocalClaims = new List<Claim>();
var localSignInProps = new AuthenticationProperties();
ProcessLoginCallbackForOidc(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForWsFed(result, additionalLocalClaims, localSignInProps);
ProcessLoginCallbackForSaml2p(result, additionalLocalClaims, localSignInProps);
// issue authentication cookie for user
await _events.RaiseAsync(new UserLoginSuccessEvent(provider, providerUserId, user.Id, user.UserName));
await HttpContext.SignInAsync(user.Id, user.UserName, provider, localSignInProps, additionalLocalClaims.ToArray());
// delete temporary cookie used during external authentication
await HttpContext.SignOutAsync(IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme);
// retrieve return URL
var returnUrl = result.Properties.Items["returnUrl"] ?? "~/";
// check if external login is in the context of an OIDC request
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (context != null)
{
if (await _clientStore.IsPkceClientAsync(context.ClientId))
{
// if the client is PKCE then we assume it's native, so this change in how to
// return the response is for better UX for the end user.
return View("Redirect", new RedirectViewModel { RedirectUrl = returnUrl });
}
}
return Redirect(returnUrl);
}
private async Task<IActionResult> ProcessWindowsLoginAsync(string returnUrl)
{
// see if windows auth has already been requested and succeeded
var result = await HttpContext.AuthenticateAsync(AccountOptions.WindowsAuthenticationSchemeName);
if (result?.Principal is WindowsPrincipal wp)
{
// we will issue the external cookie and then redirect the
// user back to the external callback, in essence, tresting windows
// auth the same as any other external authentication mechanism
var props = new AuthenticationProperties()
{
RedirectUri = Url.Action("Callback"),
Items =
{
{ "returnUrl", returnUrl },
{ "scheme", AccountOptions.WindowsAuthenticationSchemeName },
}
};
var id = new ClaimsIdentity(AccountOptions.WindowsAuthenticationSchemeName);
id.AddClaim(new Claim(JwtClaimTypes.Subject, wp.Identity.Name));
id.AddClaim(new Claim(JwtClaimTypes.Name, wp.Identity.Name));
// add the groups as claims -- be careful if the number of groups is too large
if (AccountOptions.IncludeWindowsGroups)
{
var wi = wp.Identity as WindowsIdentity;
var groups = wi.Groups.Translate(typeof(NTAccount));
var roles = groups.Select(x => new Claim(JwtClaimTypes.Role, x.Value));
id.AddClaims(roles);
}
await HttpContext.SignInAsync(
IdentityServer4.IdentityServerConstants.ExternalCookieAuthenticationScheme,
new ClaimsPrincipal(id),
props);
return Redirect(props.RedirectUri);
}
else
{
// trigger windows auth
// since windows auth don't support the redirect uri,
// this URL is re-triggered when we call challenge
return Challenge(AccountOptions.WindowsAuthenticationSchemeName);
}
}
private async Task<(MongoIdentityUser user, string provider, string providerUserId, IEnumerable<Claim> claims)> FindUserFromExternalProvider(AuthenticateResult result)
{
var externalUser = result.Principal;
// try to determine the unique id of the external user (issued by the provider)
// the most common claim type for that are the sub claim and the NameIdentifier
// depending on the external provider, some other claim type might be used
var userIdClaim = externalUser.FindFirst(JwtClaimTypes.Subject) ??
externalUser.FindFirst(ClaimTypes.NameIdentifier) ??
throw new Exception("Unknown userid");
// remove the user id claim so we don't include it as an extra claim if/when we provision the user
var claims = externalUser.Claims.ToList();
claims.Remove(userIdClaim);
var provider = result.Properties.Items["scheme"];
var providerUserId = userIdClaim.Value;
// find external user
var user = await _userManager.FindByLoginAsync(provider, providerUserId);
return (user, provider, providerUserId, claims);
}
private async Task<MongoIdentityUser> AutoProvisionUser(string provider, string providerUserId, IEnumerable<Claim> claims)
{
// create a list of claims that we want to transfer into our store
var filtered = new List<Claim>();
// user's display name
var name = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Name)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Name)?.Value;
if (name != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, name));
}
else
{
var first = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.GivenName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.GivenName)?.Value;
var last = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.FamilyName)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Surname)?.Value;
if (first != null && last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first + " " + last));
}
else if (first != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, first));
}
else if (last != null)
{
filtered.Add(new Claim(JwtClaimTypes.Name, last));
}
}
// email
var email = claims.FirstOrDefault(x => x.Type == JwtClaimTypes.Email)?.Value ??
claims.FirstOrDefault(x => x.Type == ClaimTypes.Email)?.Value;
if (email != null)
{
filtered.Add(new Claim(JwtClaimTypes.Email, email));
}
var user = new MongoIdentityUser(Guid.NewGuid().ToString(), email);
var identityResult = await _userManager.CreateAsync(user);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
if (filtered.Any())
{
identityResult = await _userManager.AddClaimsAsync(user, filtered);
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
}
identityResult = await _userManager.AddLoginAsync(user, new UserLoginInfo(provider, providerUserId, provider));
if (!identityResult.Succeeded) throw new Exception(identityResult.Errors.First().Description);
return user;
}
private void ProcessLoginCallbackForOidc(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
// if the external system sent a session id claim, copy it over
// so we can use it for single sign-out
var sid = externalResult.Principal.Claims.FirstOrDefault(x => x.Type == JwtClaimTypes.SessionId);
if (sid != null)
{
localClaims.Add(new Claim(JwtClaimTypes.SessionId, sid.Value));
}
// if the external provider issued an id_token, we'll keep it for signout
var id_token = externalResult.Properties.GetTokenValue("id_token");
if (id_token != null)
{
localSignInProps.StoreTokens(new[] { new AuthenticationToken { Name = "id_token", Value = id_token } });
}
}
private void ProcessLoginCallbackForWsFed(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
private void ProcessLoginCallbackForSaml2p(AuthenticateResult externalResult, List<Claim> localClaims, AuthenticationProperties localSignInProps)
{
}
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.ServiceModel.Description
{
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Xml;
using WsdlNS = System.Web.Services.Description;
using System.Globalization;
//
// PolicyReader is a complex nested class in the MetadataImporter
//
public abstract partial class MetadataImporter
{
internal MetadataImporterQuotas Quotas;
PolicyReader policyNormalizer = null;
internal delegate void PolicyWarningHandler(XmlElement contextAssertion, string warningMessage);
// Consider, [....], make this public?
internal event PolicyWarningHandler PolicyWarningOccured;
internal IEnumerable<IEnumerable<XmlElement>> NormalizePolicy(IEnumerable<XmlElement> policyAssertions)
{
if (this.policyNormalizer == null)
{
this.policyNormalizer = new PolicyReader(this);
}
return this.policyNormalizer.NormalizePolicy(policyAssertions);
}
//DevNote: The error handling goal for this class is to NEVER throw an exception.
// * Any Ignored Policy should generate a warning
// * All policy parsing errors should be logged as warnings in the WSDLImporter.Errors collection.
sealed class PolicyReader
{
int nodesRead = 0;
readonly MetadataImporter metadataImporter;
internal PolicyReader(MetadataImporter metadataImporter)
{
this.metadataImporter = metadataImporter;
}
static IEnumerable<XmlElement> Empty = new PolicyHelper.EmptyEnumerable<XmlElement>();
static IEnumerable<IEnumerable<XmlElement>> EmptyEmpty = new PolicyHelper.SingleEnumerable<IEnumerable<XmlElement>>(new PolicyHelper.EmptyEnumerable<XmlElement>());
//
// the core policy reading logic
// each step returns a list of lists -- an "and of ors":
// each inner list is a policy alternative: it contains the set of assertions that comprise the alternative
// the outer list represents the choice between alternatives
//
IEnumerable<IEnumerable<XmlElement>> ReadNode(XmlNode node, XmlElement contextAssertion, YieldLimiter yieldLimiter)
{
if (nodesRead >= this.metadataImporter.Quotas.MaxPolicyNodes)
{
if (nodesRead == this.metadataImporter.Quotas.MaxPolicyNodes)
{
// add wirning once
string warningMsg = SR.GetString(SR.ExceededMaxPolicyComplexity, node.Name, PolicyHelper.GetFragmentIdentifier((XmlElement)node));
metadataImporter.PolicyWarningOccured.Invoke(contextAssertion, warningMsg);
nodesRead++;
}
return EmptyEmpty;
}
nodesRead++;
IEnumerable<IEnumerable<XmlElement>> nodes = EmptyEmpty;
switch (PolicyHelper.GetNodeType(node))
{
case PolicyHelper.NodeType.Policy:
case PolicyHelper.NodeType.All:
nodes = ReadNode_PolicyOrAll((XmlElement)node, contextAssertion, yieldLimiter);
break;
case PolicyHelper.NodeType.ExactlyOne:
nodes = ReadNode_ExactlyOne((XmlElement)node, contextAssertion, yieldLimiter);
break;
case PolicyHelper.NodeType.Assertion:
nodes = ReadNode_Assertion((XmlElement)node, yieldLimiter);
break;
case PolicyHelper.NodeType.PolicyReference:
nodes = ReadNode_PolicyReference((XmlElement)node, contextAssertion, yieldLimiter);
break;
case PolicyHelper.NodeType.UnrecognizedWSPolicy:
string warningMsg = SR.GetString(SR.UnrecognizedPolicyElementInNamespace, node.Name, node.NamespaceURI);
metadataImporter.PolicyWarningOccured.Invoke(contextAssertion, warningMsg);
break;
//consider [....], add more error handling here. default?
}
return nodes;
}
IEnumerable<IEnumerable<XmlElement>> ReadNode_PolicyReference(XmlElement element, XmlElement contextAssertion, YieldLimiter yieldLimiter)
{
string idRef = element.GetAttribute(MetadataStrings.WSPolicy.Attributes.URI);
if (idRef == null)
{
string warningMsg = SR.GetString(SR.PolicyReferenceMissingURI, MetadataStrings.WSPolicy.Attributes.URI);
metadataImporter.PolicyWarningOccured.Invoke(contextAssertion, warningMsg);
return EmptyEmpty;
}
else if (idRef == string.Empty)
{
string warningMsg = SR.GetString(SR.PolicyReferenceInvalidId);
metadataImporter.PolicyWarningOccured.Invoke(contextAssertion, warningMsg);
return EmptyEmpty;
}
XmlElement policy = metadataImporter.ResolvePolicyReference(idRef, contextAssertion);
if (policy == null)
{
string warningMsg = SR.GetString(SR.UnableToFindPolicyWithId, idRef);
metadataImporter.PolicyWarningOccured.Invoke(contextAssertion, warningMsg);
return EmptyEmpty;
}
//
// Since we looked up a reference, the context assertion changes.
//
return ReadNode_PolicyOrAll(policy, policy, yieldLimiter);
}
IEnumerable<IEnumerable<XmlElement>> ReadNode_Assertion(XmlElement element, YieldLimiter yieldLimiter)
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
yield return Empty;
else
yield return new PolicyHelper.SingleEnumerable<XmlElement>(element);
}
IEnumerable<IEnumerable<XmlElement>> ReadNode_ExactlyOne(XmlElement element, XmlElement contextAssertion, YieldLimiter yieldLimiter)
{
foreach (XmlNode child in element.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
foreach (IEnumerable<XmlElement> alternative in ReadNode(child, contextAssertion, yieldLimiter))
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return alternative;
}
}
}
}
}
IEnumerable<IEnumerable<XmlElement>> ReadNode_PolicyOrAll(XmlElement element, XmlElement contextAssertion, YieldLimiter yieldLimiter)
{
IEnumerable<IEnumerable<XmlElement>> target = EmptyEmpty;
foreach (XmlNode child in element.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element)
{
IEnumerable<IEnumerable<XmlElement>> childPolicy = ReadNode(child, contextAssertion, yieldLimiter);
target = PolicyHelper.CrossProduct<XmlElement>(target, childPolicy, yieldLimiter);
}
}
return target;
}
internal IEnumerable<IEnumerable<XmlElement>> NormalizePolicy(IEnumerable<XmlElement> policyAssertions)
{
IEnumerable<IEnumerable<XmlElement>> target = EmptyEmpty;
YieldLimiter yieldLimiter = new YieldLimiter(this.metadataImporter.Quotas.MaxYields, this.metadataImporter);
foreach (XmlElement child in policyAssertions)
{
IEnumerable<IEnumerable<XmlElement>> childPolicy = ReadNode(child, child, yieldLimiter);
target = PolicyHelper.CrossProduct<XmlElement>(target, childPolicy, yieldLimiter);
}
return target;
}
}
internal class YieldLimiter
{
int maxYields;
int yieldsHit;
readonly MetadataImporter metadataImporter;
internal YieldLimiter(int maxYields, MetadataImporter metadataImporter)
{
this.metadataImporter = metadataImporter;
this.yieldsHit = 0;
this.maxYields = maxYields;
}
internal bool IncrementAndLogIfExceededLimit()
{
if (++yieldsHit > maxYields)
{
string warningMsg = SR.GetString(SR.ExceededMaxPolicySize);
metadataImporter.PolicyWarningOccured.Invoke(null, warningMsg);
return true;
}
else
{
return false;
}
}
}
internal static class PolicyHelper
{
internal static string GetFragmentIdentifier(XmlElement element)
{
string id = element.GetAttribute(MetadataStrings.Wsu.Attributes.Id, MetadataStrings.Wsu.NamespaceUri);
if (id == null)
{
id = element.GetAttribute(MetadataStrings.Xml.Attributes.Id, MetadataStrings.Xml.NamespaceUri);
}
if (string.IsNullOrEmpty(id))
return string.Empty;
else
return string.Format(CultureInfo.InvariantCulture, "#{0}", id);
}
internal static bool IsPolicyURIs(XmlAttribute attribute)
{
return ((attribute.NamespaceURI == MetadataStrings.WSPolicy.NamespaceUri
|| attribute.NamespaceURI == MetadataStrings.WSPolicy.NamespaceUri15)
&& attribute.LocalName == MetadataStrings.WSPolicy.Attributes.PolicyURIs);
}
internal static NodeType GetNodeType(XmlNode node)
{
XmlElement currentElement = node as XmlElement;
if (currentElement == null)
return PolicyHelper.NodeType.NonElement;
if (currentElement.NamespaceURI != MetadataStrings.WSPolicy.NamespaceUri
&& currentElement.NamespaceURI != MetadataStrings.WSPolicy.NamespaceUri15)
return NodeType.Assertion;
else if (currentElement.LocalName == MetadataStrings.WSPolicy.Elements.Policy)
return NodeType.Policy;
else if (currentElement.LocalName == MetadataStrings.WSPolicy.Elements.All)
return NodeType.All;
else if (currentElement.LocalName == MetadataStrings.WSPolicy.Elements.ExactlyOne)
return NodeType.ExactlyOne;
else if (currentElement.LocalName == MetadataStrings.WSPolicy.Elements.PolicyReference)
return NodeType.PolicyReference;
else
return PolicyHelper.NodeType.UnrecognizedWSPolicy;
}
//
// some helpers for dealing with ands of ors
//
internal static IEnumerable<IEnumerable<T>> CrossProduct<T>(IEnumerable<IEnumerable<T>> xs, IEnumerable<IEnumerable<T>> ys, YieldLimiter yieldLimiter)
{
foreach (IEnumerable<T> x in AtLeastOne<T>(xs, yieldLimiter))
{
foreach (IEnumerable<T> y in AtLeastOne<T>(ys, yieldLimiter))
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return Merge<T>(x, y, yieldLimiter);
}
}
}
}
static IEnumerable<IEnumerable<T>> AtLeastOne<T>(IEnumerable<IEnumerable<T>> xs, YieldLimiter yieldLimiter)
{
bool gotOne = false;
foreach (IEnumerable<T> x in xs)
{
gotOne = true;
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return x;
}
}
if (!gotOne)
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return new EmptyEnumerable<T>();
}
}
}
static IEnumerable<T> Merge<T>(IEnumerable<T> e1, IEnumerable<T> e2, YieldLimiter yieldLimiter)
{
foreach (T t1 in e1)
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return t1;
}
}
foreach (T t2 in e2)
{
if (yieldLimiter.IncrementAndLogIfExceededLimit())
{
yield break;
}
else
{
yield return t2;
}
}
}
//
// some helper enumerators
//
internal class EmptyEnumerable<T> : IEnumerable<T>, IEnumerator<T>
{
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return this;
}
object IEnumerator.Current
{
get { return this.Current; }
}
public T Current
{
get
{
#pragma warning suppress 56503 // [....], IEnumerator guidelines, Current throws exception before calling MoveNext
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.NoValue0)));
}
}
public bool MoveNext()
{
return false;
}
public void Dispose()
{
}
void IEnumerator.Reset()
{
}
}
internal class SingleEnumerable<T> : IEnumerable<T>
{
T value;
internal SingleEnumerable(T value)
{
this.value = value;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
yield return this.value;
}
}
//
// the NodeType enum
//
internal enum NodeType
{
NonElement,
Policy,
All,
ExactlyOne,
Assertion,
PolicyReference,
UnrecognizedWSPolicy,
}
}
}
}
| |
using System;
using System.Linq;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.MembershipService;
using Orleans.Providers;
using System.Collections.Generic;
using Orleans.Services;
namespace Orleans.Hosting
{
public static class LegacyClusterConfigurationExtensions
{
/// <summary>
/// Specifies the configuration to use for this silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="configuration">The configuration.</param>
/// <remarks>This method may only be called once per builder instance.</remarks>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder UseConfiguration(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
return builder.AddLegacyClusterConfigurationSupport(configuration);
}
/// <summary>
/// Loads <see cref="ClusterConfiguration"/> using <see cref="ClusterConfiguration.StandardLoad"/>.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder LoadClusterConfiguration(this ISiloHostBuilder builder)
{
var configuration = new ClusterConfiguration();
configuration.StandardLoad();
return builder.UseConfiguration(configuration);
}
/// <summary>
/// Configures a localhost silo.
/// </summary>
/// <param name="builder">The host builder.</param>
/// <param name="siloPort">The silo-to-silo communication port.</param>
/// <param name="gatewayPort">The client-to-silo communication port.</param>
/// <returns>The silo builder.</returns>
public static ISiloHostBuilder ConfigureLocalHostPrimarySilo(this ISiloHostBuilder builder, int siloPort = 22222, int gatewayPort = 40000)
{
string siloName = Silo.PrimarySiloName;
builder.Configure<SiloOptions>(options => options.SiloName = siloName);
return builder.UseConfiguration(ClusterConfiguration.LocalhostPrimarySilo(siloPort, gatewayPort));
}
public static ISiloHostBuilder AddLegacyClusterConfigurationSupport(this ISiloHostBuilder builder, ClusterConfiguration configuration)
{
LegacyMembershipConfigurator.ConfigureServices(configuration.Globals, builder);
LegacyRemindersConfigurator.Configure(configuration.Globals, builder);
return builder.ConfigureServices(services => AddLegacyClusterConfigurationSupport(services, configuration));
}
private static void AddLegacyClusterConfigurationSupport(IServiceCollection services, ClusterConfiguration configuration)
{
if (configuration == null) throw new ArgumentNullException(nameof(configuration));
if (services.TryGetClusterConfiguration() != null)
{
throw new InvalidOperationException("Cannot configure legacy ClusterConfiguration support twice");
}
// these will eventually be removed once our code doesn't depend on the old ClientConfiguration
services.AddSingleton(configuration);
services.TryAddSingleton<LegacyConfigurationWrapper>();
services.TryAddSingleton(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().ClusterConfig.Globals);
services.TryAddTransient(sp => sp.GetRequiredService<LegacyConfigurationWrapper>().NodeConfig);
services.TryAddSingleton<Factory<NodeConfiguration>>(
sp =>
{
var initializationParams = sp.GetRequiredService<LegacyConfigurationWrapper>();
return () => initializationParams.NodeConfig;
});
services.Configure<ClusterOptions>(options =>
{
if (string.IsNullOrWhiteSpace(options.ClusterId) && !string.IsNullOrWhiteSpace(configuration.Globals.ClusterId))
{
options.ClusterId = configuration.Globals.ClusterId;
}
if (string.IsNullOrWhiteSpace(options.ServiceId))
{
options.ServiceId = configuration.Globals.ServiceId.ToString();
}
});
services.Configure<MultiClusterOptions>(options =>
{
var globals = configuration.Globals;
if (globals.HasMultiClusterNetwork)
{
options.HasMultiClusterNetwork = true;
options.BackgroundGossipInterval = globals.BackgroundGossipInterval;
options.DefaultMultiCluster = globals.DefaultMultiCluster?.ToList();
options.GlobalSingleInstanceNumberRetries = globals.GlobalSingleInstanceNumberRetries;
options.GlobalSingleInstanceRetryInterval = globals.GlobalSingleInstanceRetryInterval;
options.MaxMultiClusterGateways = globals.MaxMultiClusterGateways;
options.UseGlobalSingleInstanceByDefault = globals.UseGlobalSingleInstanceByDefault;
foreach(GlobalConfiguration.GossipChannelConfiguration channelConfig in globals.GossipChannels)
{
options.GossipChannels.Add(GlobalConfiguration.Remap(channelConfig.ChannelType), channelConfig.ConnectionString);
}
}
});
services.TryAddFromExisting<IMessagingConfiguration, GlobalConfiguration>();
services.AddOptions<StatisticsOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) => LegacyConfigurationExtensions.CopyStatisticsOptions(nodeConfig, options));
services.AddOptions<DeploymentLoadPublisherOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.DeploymentLoadPublisherRefreshTime = config.DeploymentLoadPublisherRefreshTime;
});
services.AddOptions<LoadSheddingOptions>()
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.LoadSheddingEnabled = nodeConfig.LoadSheddingEnabled;
options.LoadSheddingLimit = nodeConfig.LoadSheddingLimit;
});
// Translate legacy configuration to new Options
services.AddOptions<SiloMessagingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
LegacyConfigurationExtensions.CopyCommonMessagingOptions(config, options);
options.SiloSenderQueues = config.SiloSenderQueues;
options.GatewaySenderQueues = config.GatewaySenderQueues;
options.MaxForwardCount = config.MaxForwardCount;
options.ClientDropTimeout = config.ClientDropTimeout;
options.ClientRegistrationRefresh = config.ClientRegistrationRefresh;
options.MaxRequestProcessingTime = config.MaxRequestProcessingTime;
options.AssumeHomogenousSilosForTesting = config.AssumeHomogenousSilosForTesting;
})
.Configure<NodeConfiguration>((options, config) =>
{
options.PropagateActivityId = config.PropagateActivityId;
LimitValue requestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS);
options.MaxEnqueuedRequestsSoftLimit = requestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit = requestLimit.HardLimitThreshold;
LimitValue statelessWorkerRequestLimit = config.LimitManager.GetLimit(LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER);
options.MaxEnqueuedRequestsSoftLimit_StatelessWorker = statelessWorkerRequestLimit.SoftLimitThreshold;
options.MaxEnqueuedRequestsHardLimit_StatelessWorker = statelessWorkerRequestLimit.HardLimitThreshold;
});
services.Configure<NetworkingOptions>(options => LegacyConfigurationExtensions.CopyNetworkingOptions(configuration.Globals, options));
services.AddOptions<EndpointOptions>()
.Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
if (!string.IsNullOrEmpty(nodeConfig.HostNameOrIPAddress) || nodeConfig.Port != 0)
{
options.AdvertisedIPAddress = nodeConfig.Endpoint.Address;
options.SiloPort = nodeConfig.Endpoint.Port;
}
});
services.Configure<SerializationProviderOptions>(options =>
{
options.SerializationProviders = configuration.Globals.SerializationProviders;
options.FallbackSerializationProvider = configuration.Globals.FallbackSerializationProvider;
});
services.Configure<TelemetryOptions>(options =>
{
LegacyConfigurationExtensions.CopyTelemetryOptions(configuration.Defaults.TelemetryConfiguration, services, options);
});
services.AddOptions<GrainClassOptions>().Configure<IOptions<SiloOptions>>((options, siloOptions) =>
{
var nodeConfig = configuration.GetOrCreateNodeConfigurationForSilo(siloOptions.Value.SiloName);
options.ExcludedGrainTypes.AddRange(nodeConfig.ExcludedGrainTypes);
});
services.AddOptions<SchedulingOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.AllowCallChainReentrancy = config.AllowCallChainReentrancy;
options.PerformDeadlockDetection = config.PerformDeadlockDetection;
})
.Configure<NodeConfiguration>((options, nodeConfig) =>
{
options.MaxActiveThreads = nodeConfig.MaxActiveThreads;
options.DelayWarningThreshold = nodeConfig.DelayWarningThreshold;
options.ActivationSchedulingQuantum = nodeConfig.ActivationSchedulingQuantum;
options.TurnWarningLengthThreshold = nodeConfig.TurnWarningLengthThreshold;
options.EnableWorkerThreadInjection = nodeConfig.EnableWorkerThreadInjection;
LimitValue itemLimit = nodeConfig.LimitManager.GetLimit(LimitNames.LIMIT_MAX_PENDING_ITEMS);
options.MaxPendingWorkItemsSoftLimit = itemLimit.SoftLimitThreshold;
});
services.AddOptions<GrainCollectionOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.CollectionQuantum = config.CollectionQuantum;
options.CollectionAge = config.Application.DefaultCollectionAgeLimit;
foreach (GrainTypeConfiguration grainConfig in config.Application.ClassSpecific)
{
if(grainConfig.CollectionAgeLimit.HasValue)
{
options.ClassSpecificCollectionAge.Add(grainConfig.FullTypeName, grainConfig.CollectionAgeLimit.Value);
}
};
});
LegacyProviderConfigurator<ISiloLifecycle>.ConfigureServices(configuration.Globals.ProviderConfigurations, services);
if (!string.IsNullOrWhiteSpace(configuration.Globals.DefaultPlacementStrategy))
{
services.AddSingleton(typeof(PlacementStrategy), MapDefaultPlacementStrategy(configuration.Globals.DefaultPlacementStrategy));
}
services.AddOptions<ActivationCountBasedPlacementOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.ChooseOutOf = config.ActivationCountBasedPlacementChooseOutOf;
});
services.AddOptions<StaticClusterDeploymentOptions>().Configure<ClusterConfiguration>((options, config) =>
{
options.SiloNames = config.Overrides.Keys.ToList();
});
// add grain service configs as keyed services
foreach (IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
{
var type = Type.GetType(grainServiceConfiguration.ServiceType);
services.AddSingletonKeyedService(type, (sp, k) => grainServiceConfiguration);
}
// populate grain service options
foreach(IGrainServiceConfiguration grainServiceConfiguration in configuration.Globals.GrainServiceConfigurations.GrainServices.Values)
{
services.AddGrainService(Type.GetType(grainServiceConfiguration.ServiceType));
}
services.AddOptions<ConsistentRingOptions>().Configure<GlobalConfiguration>((options, config) =>
{
options.UseVirtualBucketsConsistentRing = config.UseVirtualBucketsConsistentRing;
options.NumVirtualBucketsConsistentRing = config.NumVirtualBucketsConsistentRing;
});
services.AddOptions<ClusterMembershipOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.NumMissedTableIAmAliveLimit = config.NumMissedTableIAmAliveLimit;
options.LivenessEnabled = config.LivenessEnabled;
options.ProbeTimeout = config.ProbeTimeout;
options.TableRefreshTimeout = config.TableRefreshTimeout;
options.DeathVoteExpirationTimeout = config.DeathVoteExpirationTimeout;
options.IAmAliveTablePublishTimeout = config.IAmAliveTablePublishTimeout;
options.MaxJoinAttemptTime = config.MaxJoinAttemptTime;
options.ExpectedClusterSize = config.ExpectedClusterSize;
options.ValidateInitialConnectivity = config.ValidateInitialConnectivity;
options.NumMissedProbesLimit = config.NumMissedProbesLimit;
options.UseLivenessGossip = config.UseLivenessGossip;
options.NumProbedSilos = config.NumProbedSilos;
options.NumVotesForDeathDeclaration = config.NumVotesForDeathDeclaration;
})
.Configure<ClusterConfiguration>((options, config) =>
{
options.IsRunningAsUnitTest = config.IsRunningAsUnitTest;
});
services.AddOptions<GrainVersioningOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.DefaultCompatibilityStrategy = config.DefaultCompatibilityStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_COMPATABILITY_STRATEGY;
options.DefaultVersionSelectorStrategy = config.DefaultVersionSelectorStrategy?.GetType().Name ?? GrainVersioningOptions.DEFAULT_VERSION_SELECTOR_STRATEGY;
});
services.AddOptions<PerformanceTuningOptions>()
.Configure<NodeConfiguration>((options, config) =>
{
options.DefaultConnectionLimit = config.DefaultConnectionLimit;
options.Expect100Continue = config.Expect100Continue;
options.UseNagleAlgorithm = config.UseNagleAlgorithm;
options.MinDotNetThreadPoolSize = config.MinDotNetThreadPoolSize;
});
services.AddOptions<TypeManagementOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.TypeMapRefreshInterval = config.TypeMapRefreshInterval;
});
services.AddOptions<GrainDirectoryOptions>()
.Configure<GlobalConfiguration>((options, config) =>
{
options.CachingStrategy = Remap(config.DirectoryCachingStrategy);
options.CacheSize = config.CacheSize;
options.InitialCacheTTL = config.InitialCacheTTL;
options.MaximumCacheTTL = config.MaximumCacheTTL;
options.CacheTTLExtensionFactor = config.CacheTTLExtensionFactor;
options.LazyDeregistrationDelay = config.DirectoryLazyDeregistrationDelay;
});
}
private static Type MapDefaultPlacementStrategy(string strategy)
{
switch (strategy)
{
case nameof(RandomPlacement):
return typeof(RandomPlacement);
case nameof(PreferLocalPlacement):
return typeof(PreferLocalPlacement);
case nameof(SystemPlacement):
return typeof(SystemPlacement);
case nameof(ActivationCountBasedPlacement):
return typeof(ActivationCountBasedPlacement);
case nameof(HashBasedPlacement):
return typeof(HashBasedPlacement);
default:
return null;
}
}
public static ClusterConfiguration TryGetClusterConfiguration(this IServiceCollection services)
{
return services
.FirstOrDefault(s => s.ServiceType == typeof(ClusterConfiguration))
?.ImplementationInstance as ClusterConfiguration;
}
private static GrainDirectoryOptions.CachingStrategyType Remap(GlobalConfiguration.DirectoryCachingStrategyType type)
{
switch (type)
{
case GlobalConfiguration.DirectoryCachingStrategyType.None:
return GrainDirectoryOptions.CachingStrategyType.None;
case GlobalConfiguration.DirectoryCachingStrategyType.LRU:
return GrainDirectoryOptions.CachingStrategyType.LRU;
case GlobalConfiguration.DirectoryCachingStrategyType.Adaptive:
return GrainDirectoryOptions.CachingStrategyType.Adaptive;
default:
throw new NotSupportedException($"DirectoryCachingStrategyType {type} is not supported");
}
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Collections.CollectionBase.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Collections
{
abstract public partial class CollectionBase : IList, ICollection, IEnumerable
{
#region Methods and constructors
public void Clear()
{
}
protected CollectionBase()
{
}
protected CollectionBase(int capacity)
{
}
public IEnumerator GetEnumerator()
{
return default(IEnumerator);
}
protected virtual new void OnClear()
{
}
protected virtual new void OnClearComplete()
{
}
protected virtual new void OnInsert(int index, Object value)
{
}
protected virtual new void OnInsertComplete(int index, Object value)
{
}
protected virtual new void OnRemove(int index, Object value)
{
}
protected virtual new void OnRemoveComplete(int index, Object value)
{
}
protected virtual new void OnSet(int index, Object oldValue, Object newValue)
{
}
protected virtual new void OnSetComplete(int index, Object oldValue, Object newValue)
{
}
protected virtual new void OnValidate(Object value)
{
}
public void RemoveAt(int index)
{
}
void System.Collections.ICollection.CopyTo(Array array, int index)
{
}
int System.Collections.IList.Add(Object value)
{
return default(int);
}
bool System.Collections.IList.Contains(Object value)
{
return default(bool);
}
int System.Collections.IList.IndexOf(Object value)
{
return default(int);
}
void System.Collections.IList.Insert(int index, Object value)
{
}
void System.Collections.IList.Remove(Object value)
{
}
#endregion
#region Properties and indexers
public int Capacity
{
get
{
Contract.Ensures(Contract.Result<int>() == this.InnerList.Capacity);
return default(int);
}
set
{
Contract.Ensures(value == this.InnerList.Capacity);
}
}
public int Count
{
get
{
return default(int);
}
}
protected ArrayList InnerList
{
get
{
Contract.Ensures(Contract.Result<System.Collections.ArrayList>() != null);
return default(ArrayList);
}
}
protected IList List
{
get
{
Contract.Ensures(Contract.Result<System.Collections.IList>() != null);
Contract.Ensures(Contract.Result<System.Collections.IList>() == this);
return default(IList);
}
}
bool System.Collections.ICollection.IsSynchronized
{
get
{
return default(bool);
}
}
Object System.Collections.ICollection.SyncRoot
{
get
{
return default(Object);
}
}
bool System.Collections.IList.IsFixedSize
{
get
{
return default(bool);
}
}
bool System.Collections.IList.IsReadOnly
{
get
{
return default(bool);
}
}
Object System.Collections.IList.this [int index]
{
get
{
return default(Object);
}
set
{
}
}
#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.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO.Pipelines.Text.Primitives;
using Xunit;
namespace System.IO.Pipelines.Tests
{
public class PipelineReaderWriterFacts : IDisposable
{
private IPipe _pipe;
private PipeFactory _pipeFactory;
public PipelineReaderWriterFacts()
{
_pipeFactory = new PipeFactory();
_pipe = _pipeFactory.Create();
}
public void Dispose()
{
_pipe.Writer.Complete();
_pipe.Reader.Complete();
_pipeFactory?.Dispose();
}
[Fact]
public async Task ReaderShouldNotGetUnflushedBytesWhenOverflowingSegments()
{
// Fill the block with stuff leaving 5 bytes at the end
var buffer = _pipe.Writer.Alloc(1);
var len = buffer.Buffer.Length;
// Fill the buffer with garbage
// block 1 -> block2
// [padding..hello] -> [ world ]
var paddingBytes = Enumerable.Repeat((byte)'a', len - 5).ToArray();
buffer.Write(paddingBytes);
await buffer.FlushAsync();
// Write 10 and flush
buffer = _pipe.Writer.Alloc();
buffer.WriteLittleEndian(10);
// Write 9
buffer.WriteLittleEndian(9);
// Write 8
buffer.WriteLittleEndian(8);
// Make sure we don't see it yet
var result = await _pipe.Reader.ReadAsync();
var reader = result.Buffer;
Assert.Equal(len - 5, reader.Length);
// Don't move
_pipe.Reader.Advance(reader.End);
// Now flush
await buffer.FlushAsync();
reader = (await _pipe.Reader.ReadAsync()).Buffer;
Assert.Equal(12, reader.Length);
Assert.Equal(10, reader.ReadLittleEndian<int>());
Assert.Equal(9, reader.Slice(4).ReadLittleEndian<int>());
Assert.Equal(8, reader.Slice(8).ReadLittleEndian<int>());
_pipe.Reader.Advance(reader.Start, reader.Start);
}
[Fact]
public void WhenTryReadReturnsFalseDontNeedToCallAdvance()
{
var gotData = _pipe.Reader.TryRead(out var result);
Assert.False(gotData);
_pipe.Reader.Advance(default(ReadCursor));
}
[Fact]
public void TryReadAfterReaderCompleteThrows()
{
_pipe.Reader.Complete();
Assert.Throws<InvalidOperationException>(() => _pipe.Reader.TryRead(out var result));
}
[Fact]
public void TryReadAfterCloseWriterWithExceptionThrows()
{
_pipe.Writer.Complete(new Exception("wow"));
var ex = Assert.Throws<Exception>(() => _pipe.Reader.TryRead(out var result));
Assert.Equal("wow", ex.Message);
}
[Fact]
public void TryReadAfterCancelPendingReadReturnsTrue()
{
_pipe.Reader.CancelPendingRead();
var gotData = _pipe.Reader.TryRead(out var result);
Assert.True(result.IsCancelled);
_pipe.Reader.Advance(result.Buffer.End);
}
[Fact]
public void TryReadAfterWriterCompleteReturnsTrue()
{
_pipe.Writer.Complete();
var gotData = _pipe.Reader.TryRead(out var result);
Assert.True(result.IsCompleted);
_pipe.Reader.Advance(result.Buffer.End);
}
[Fact]
public async Task SyncReadThenAsyncRead()
{
var buffer = _pipe.Writer.Alloc();
buffer.Write(Encoding.ASCII.GetBytes("Hello World"));
await buffer.FlushAsync();
var gotData = _pipe.Reader.TryRead(out var result);
Assert.True(gotData);
Assert.Equal("Hello World", result.Buffer.GetAsciiString());
_pipe.Reader.Advance(result.Buffer.Move(result.Buffer.Start, 6));
result = await _pipe.Reader.ReadAsync();
Assert.Equal("World", result.Buffer.GetAsciiString());
_pipe.Reader.Advance(result.Buffer.End);
}
[Fact]
public async Task ReaderShouldNotGetUnflushedBytes()
{
// Write 10 and flush
var buffer = _pipe.Writer.Alloc();
buffer.WriteLittleEndian(10);
await buffer.FlushAsync();
// Write 9
buffer = _pipe.Writer.Alloc();
buffer.WriteLittleEndian(9);
// Write 8
buffer.WriteLittleEndian(8);
// Make sure we don't see it yet
var result = await _pipe.Reader.ReadAsync();
var reader = result.Buffer;
Assert.Equal(4, reader.Length);
Assert.Equal(10, reader.ReadLittleEndian<int>());
// Don't move
_pipe.Reader.Advance(reader.Start);
// Now flush
await buffer.FlushAsync();
reader = (await _pipe.Reader.ReadAsync()).Buffer;
Assert.Equal(12, reader.Length);
Assert.Equal(10, reader.ReadLittleEndian<int>());
Assert.Equal(9, reader.Slice(4).ReadLittleEndian<int>());
Assert.Equal(8, reader.Slice(8).ReadLittleEndian<int>());
_pipe.Reader.Advance(reader.Start, reader.Start);
}
[Fact]
public async Task ReaderShouldNotGetUnflushedBytesWithAppend()
{
// Write 10 and flush
var buffer = _pipe.Writer.Alloc();
buffer.WriteLittleEndian(10);
await buffer.FlushAsync();
// Write Hello to another pipeline and get the buffer
var bytes = Encoding.ASCII.GetBytes("Hello");
var c2 = _pipeFactory.Create();
await c2.Writer.WriteAsync(bytes);
var result = await c2.Reader.ReadAsync();
var c2Buffer = result.Buffer;
Assert.Equal(bytes.Length, c2Buffer.Length);
// Write 9 to the buffer
buffer = _pipe.Writer.Alloc();
buffer.WriteLittleEndian(9);
// Append the data from the other pipeline
buffer.Append(c2Buffer);
// Mark it as consumed
c2.Reader.Advance(c2Buffer.End);
// Now read and make sure we only see the comitted data
result = await _pipe.Reader.ReadAsync();
var reader = result.Buffer;
Assert.Equal(4, reader.Length);
Assert.Equal(10, reader.ReadLittleEndian<int>());
// Consume nothing
_pipe.Reader.Advance(reader.Start);
// Flush the second set of writes
await buffer.FlushAsync();
reader = (await _pipe.Reader.ReadAsync()).Buffer;
// int, int, "Hello"
Assert.Equal(13, reader.Length);
Assert.Equal(10, reader.ReadLittleEndian<int>());
Assert.Equal(9, reader.Slice(4).ReadLittleEndian<int>());
Assert.Equal("Hello", reader.Slice(8).GetUtf8String());
_pipe.Reader.Advance(reader.Start, reader.Start);
}
[Fact]
public async Task WritingDataMakesDataReadableViaPipeline()
{
var bytes = Encoding.ASCII.GetBytes("Hello World");
await _pipe.Writer.WriteAsync(bytes);
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
Assert.Equal(11, buffer.Length);
Assert.True(buffer.IsSingleSpan);
var array = new byte[11];
buffer.First.Span.CopyTo(array);
Assert.Equal("Hello World", Encoding.ASCII.GetString(array));
_pipe.Reader.Advance(buffer.Start, buffer.Start);
}
[Fact]
public async Task AdvanceEmptyBufferAfterWritingResetsAwaitable()
{
var bytes = Encoding.ASCII.GetBytes("Hello World");
await _pipe.Writer.WriteAsync(bytes);
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
Assert.Equal(11, buffer.Length);
Assert.True(buffer.IsSingleSpan);
var array = new byte[11];
buffer.First.Span.CopyTo(array);
Assert.Equal("Hello World", Encoding.ASCII.GetString(array));
_pipe.Reader.Advance(buffer.End);
// Now write 0 and advance 0
await _pipe.Writer.WriteAsync(new byte [] {});
result = await _pipe.Reader.ReadAsync();
_pipe.Reader.Advance(result.Buffer.End);
var awaitable = _pipe.Reader.ReadAsync();
Assert.False(awaitable.IsCompleted);
}
[Fact]
public async Task AdvanceShouldResetStateIfReadCancelled()
{
_pipe.Reader.CancelPendingRead();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
_pipe.Reader.Advance(buffer.End);
Assert.False(result.IsCompleted);
Assert.True(result.IsCancelled);
Assert.True(buffer.IsEmpty);
var awaitable = _pipe.Reader.ReadAsync();
Assert.False(awaitable.IsCompleted);
}
[Fact]
public async Task ReadingCanBeCancelled()
{
var cts = new CancellationTokenSource();
cts.Token.Register(() =>
{
_pipe.Writer.Complete(new OperationCanceledException(cts.Token));
});
var ignore = Task.Run(async () =>
{
await Task.Delay(1000);
cts.Cancel();
});
await Assert.ThrowsAsync<OperationCanceledException>(async () =>
{
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
});
}
[Fact]
public async Task HelloWorldAcrossTwoBlocks()
{
const int blockSize = 4032;
// block 1 -> block2
// [padding..hello] -> [ world ]
var paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray();
var bytes = Encoding.ASCII.GetBytes("Hello World");
var writeBuffer = _pipe.Writer.Alloc();
writeBuffer.Write(paddingBytes);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
Assert.False(buffer.IsSingleSpan);
var helloBuffer = buffer.Slice(blockSize - 5);
Assert.False(helloBuffer.IsSingleSpan);
var memory = new List<Buffer<byte>>();
foreach (var m in helloBuffer)
{
memory.Add(m);
}
var spans = memory;
_pipe.Reader.Advance(buffer.Start, buffer.Start);
Assert.Equal(2, memory.Count);
var helloBytes = new byte[spans[0].Length];
spans[0].Span.CopyTo(helloBytes);
var worldBytes = new byte[spans[1].Length];
spans[1].Span.CopyTo(worldBytes);
Assert.Equal("Hello", Encoding.ASCII.GetString(helloBytes));
Assert.Equal(" World", Encoding.ASCII.GetString(worldBytes));
}
[Fact]
public async Task IndexOfNotFoundReturnsEnd()
{
var bytes = Encoding.ASCII.GetBytes("Hello World");
await _pipe.Writer.WriteAsync(bytes);
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
ReadableBuffer slice;
ReadCursor cursor;
Assert.False(buffer.TrySliceTo(10, out slice, out cursor));
_pipe.Reader.Advance(buffer.Start, buffer.Start);
}
[Fact]
public async Task FastPathIndexOfAcrossBlocks()
{
var vecUpperR = new Vector<byte>((byte)'R');
const int blockSize = 4032;
// block 1 -> block2
// [padding..hello] -> [ world ]
var paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray();
var bytes = Encoding.ASCII.GetBytes("Hello World");
var writeBuffer = _pipe.Writer.Alloc();
writeBuffer.Write(paddingBytes);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
ReadableBuffer slice;
ReadCursor cursor;
Assert.False(buffer.TrySliceTo((byte)'R', out slice, out cursor));
_pipe.Reader.Advance(buffer.Start, buffer.Start);
}
[Fact]
public async Task SlowPathIndexOfAcrossBlocks()
{
const int blockSize = 4032;
// block 1 -> block2
// [padding..hello] -> [ world ]
var paddingBytes = Enumerable.Repeat((byte)'a', blockSize - 5).ToArray();
var bytes = Encoding.ASCII.GetBytes("Hello World");
var writeBuffer = _pipe.Writer.Alloc();
writeBuffer.Write(paddingBytes);
writeBuffer.Write(bytes);
await writeBuffer.FlushAsync();
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
ReadableBuffer slice;
ReadCursor cursor;
Assert.False(buffer.IsSingleSpan);
Assert.True(buffer.TrySliceTo((byte)' ', out slice, out cursor));
slice = buffer.Slice(cursor).Slice(1);
var array = slice.ToArray();
Assert.Equal("World", Encoding.ASCII.GetString(array));
_pipe.Reader.Advance(buffer.Start, buffer.Start);
}
[Fact]
public void AllocMoreThanPoolBlockSizeThrows()
{
Assert.Throws<ArgumentOutOfRangeException>(() => _pipe.Writer.Alloc(8192));
}
[Fact]
public void ThrowsOnReadAfterCompleteReader()
{
_pipe.Reader.Complete();
Assert.Throws<InvalidOperationException>(() => _pipe.Reader.ReadAsync());
}
[Fact]
public void ThrowsOnAllocAfterCompleteWriter()
{
_pipe.Writer.Complete();
Assert.Throws<InvalidOperationException>(() => _pipe.Writer.Alloc());
}
[Fact]
public async Task MultipleCompleteReaderWriterCauseDisposeOnlyOnce()
{
var pool = new DisposeTrackingBufferPool();
using (var factory = new PipeFactory(pool))
{
var readerWriter = factory.Create();
await readerWriter.Writer.WriteAsync(new byte[] { 1 });
readerWriter.Writer.Complete();
readerWriter.Reader.Complete();
Assert.Equal(1, pool.Disposed);
readerWriter.Writer.Complete();
readerWriter.Reader.Complete();
Assert.Equal(1, pool.Disposed);
}
}
[Fact]
public async Task CompleteReaderThrowsIfReadInProgress()
{
await _pipe.Writer.WriteAsync(new byte[1]);
var result = await _pipe.Reader.ReadAsync();
var buffer = result.Buffer;
Assert.Throws<InvalidOperationException>(() => _pipe.Reader.Complete());
_pipe.Reader.Advance(buffer.Start, buffer.Start);
}
[Fact]
public void CompleteWriterThrowsIfWriteInProgress()
{
var buffer = _pipe.Writer.Alloc();
Assert.Throws<InvalidOperationException>(() => _pipe.Writer.Complete());
buffer.Commit();
}
[Fact]
public async Task ReadAsync_ThrowsIfWriterCompletedWithException()
{
_pipe.Writer.Complete(new InvalidOperationException("Writer exception"));
var invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync());
Assert.Equal("Writer exception", invalidOperationException.Message);
invalidOperationException = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _pipe.Reader.ReadAsync());
Assert.Equal("Writer exception", invalidOperationException.Message);
}
[Fact]
public void FlushAsync_ReturnsCompletedTaskWhenMaxSizeIfZero()
{
var writableBuffer = _pipe.Writer.Alloc(1);
writableBuffer.Advance(1);
var flushTask = writableBuffer.FlushAsync();
Assert.True(flushTask.IsCompleted);
writableBuffer = _pipe.Writer.Alloc(1);
writableBuffer.Advance(1);
flushTask = writableBuffer.FlushAsync();
Assert.True(flushTask.IsCompleted);
}
private class DisposeTrackingBufferPool : BufferPool
{
private DisposeTrackingOwnedMemory _memory = new DisposeTrackingOwnedMemory(new byte[1]);
public override OwnedBuffer<byte> Rent(int size)
{
return _memory;
}
public int Disposed => _memory.Disposed;
protected override void Dispose(bool disposing)
{
}
private class DisposeTrackingOwnedMemory : ReferenceCountedBuffer<byte>
{
public DisposeTrackingOwnedMemory(byte[] array)
{
_array = array;
}
protected override void Dispose(bool disposing)
{
Disposed++;
base.Dispose(disposing);
}
protected override bool TryGetArray(out ArraySegment<byte> buffer)
{
if (IsDisposed) PipelinesThrowHelper.ThrowObjectDisposedException(nameof(DisposeTrackingBufferPool));
buffer = new ArraySegment<byte>(_array);
return true;
}
public int Disposed { get; set; }
public override int Length => _array.Length;
public override Span<byte> AsSpan(int index, int length)
{
if (IsDisposed) PipelinesThrowHelper.ThrowObjectDisposedException(nameof(DisposeTrackingBufferPool));
return _array.Slice(index, length);
}
public override BufferHandle Pin(int index = 0)
{
throw new NotImplementedException();
}
byte[] _array;
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="UriSection.cs" company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
namespace System.Configuration
{
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Collections.Generic;
using System.Diagnostics;
using System.Security.Permissions;
using System.Globalization;
using System.Runtime.InteropServices;
using System.IO;
/// <summary>
/// Summary description for UriSection.
/// </summary>
public sealed class UriSection : ConfigurationSection
{
private static readonly ConfigurationPropertyCollection properties = new ConfigurationPropertyCollection();
private static readonly ConfigurationProperty idn = new ConfigurationProperty(CommonConfigurationStrings.Idn,
typeof(IdnElement), null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty iriParsing = new ConfigurationProperty(
CommonConfigurationStrings.IriParsing, typeof(IriParsingElement), null, ConfigurationPropertyOptions.None);
private static readonly ConfigurationProperty schemeSettings =
new ConfigurationProperty(CommonConfigurationStrings.SchemeSettings,
typeof(SchemeSettingElementCollection), null, ConfigurationPropertyOptions.None);
static UriSection()
{
properties.Add(idn);
properties.Add(iriParsing);
properties.Add(schemeSettings);
}
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Idn", Justification = "changing this would be a breaking change because the API has been present since v3.5")]
[ConfigurationProperty(CommonConfigurationStrings.Idn)]
public IdnElement Idn{
get {
return (IdnElement)this[idn];
}
}
[ConfigurationProperty(CommonConfigurationStrings.IriParsing)]
public IriParsingElement IriParsing
{
get {
return (IriParsingElement)this[iriParsing];
}
}
[ConfigurationProperty(CommonConfigurationStrings.SchemeSettings)]
public SchemeSettingElementCollection SchemeSettings
{
get {
return (SchemeSettingElementCollection)this[schemeSettings];
}
}
protected override ConfigurationPropertyCollection Properties
{
get {
return properties;
}
}
}
internal sealed class UriSectionInternal
{
private static readonly object classSyncObject = new object();
private UriIdnScope idnScope;
private bool iriParsing;
private Dictionary<string, SchemeSettingInternal> schemeSettings;
private UriSectionInternal()
{
this.schemeSettings = new Dictionary<string, SchemeSettingInternal>();
}
private UriSectionInternal(UriSection section)
: this()
{
this.idnScope = section.Idn.Enabled;
this.iriParsing = section.IriParsing.Enabled;
if (section.SchemeSettings != null) {
SchemeSettingInternal schemeSetting;
foreach (SchemeSettingElement element in section.SchemeSettings)
{
schemeSetting = new SchemeSettingInternal(element.Name, element.GenericUriParserOptions);
this.schemeSettings.Add(schemeSetting.Name, schemeSetting);
}
}
}
private UriSectionInternal(UriIdnScope idnScope, bool iriParsing,
IEnumerable<SchemeSettingInternal> schemeSettings)
: this()
{
this.idnScope = idnScope;
this.iriParsing = iriParsing;
if (schemeSettings != null) {
foreach (SchemeSettingInternal schemeSetting in schemeSettings) {
this.schemeSettings.Add(schemeSetting.Name, schemeSetting);
}
}
}
internal UriIdnScope IdnScope
{
get { return idnScope; }
}
internal bool IriParsing
{
get { return iriParsing; }
}
internal SchemeSettingInternal GetSchemeSetting(string scheme)
{
SchemeSettingInternal result;
if (schemeSettings.TryGetValue(scheme.ToLowerInvariant(), out result)) {
return result;
}
else {
return null;
}
}
// This method originally just used System.Configuration to get the new-to-Orcas Uri config section.
// Unfortunately that created a circular dependency on System.Config that ultimately could cause
// ConfigurationExceptions that didn't used to happen in Whidbey and thus break existing deployed
// applications.
//
// Now this method will determine if it is running in a client application or a web scenario (ASP.NET).
// If in a web scenario this code must still use System.Configuration to read config as the web scenario
// has a hierarchy of config files that only System.Configuration can practically discover and parse.
// In a client scenario this code will now use System.Xml.XmlReader to parse machine and app config files.
//
// The default output of this method if it encounters invalid or non-existent Uri config is the original
// Whidbey settings (no IDN support, no IRI support, and escaped dots and slashes are unescaped).
//
[SuppressMessage("Microsoft.Security","CA2106:SecureAsserts", Justification="Must Assert unrestricted FileIOPermission to get the app config path")]
internal static UriSectionInternal GetSection()
{
lock (classSyncObject) {
string appConfigFilePath = null;
// Must Assert unrestricted FileIOPermission to get the app config path.
new FileIOPermission(PermissionState.Unrestricted).Assert();
try {
appConfigFilePath = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;
}
finally {
FileIOPermission.RevertAssert();
}
if (IsWebConfig(appConfigFilePath)) {
// This is a web scenario. It is safe and *necessary* to use System.Configuration.
return LoadUsingSystemConfiguration();
}
else {
// This is a client application scenario. It is not safe to use System.Config for app
// compat reasons.
return LoadUsingCustomParser(appConfigFilePath);
}
}
}
private static UriSectionInternal LoadUsingSystemConfiguration()
{
try {
UriSection section = PrivilegedConfigurationManager.GetSection(
CommonConfigurationStrings.UriSectionName) as UriSection;
if (section == null) {
return null;
}
return new UriSectionInternal(section);
}
catch (ConfigurationException) {
// Simply ---- any ConfigurationException.
// Throwing it would potentially break applications.
// Uri did not read config in previous releases.
return null;
}
}
[SuppressMessage("Microsoft.Security","CA2106:SecureAsserts", Justification="Must Assert unrestricted FileIOPermission to get the machine config path")]
private static UriSectionInternal LoadUsingCustomParser(string appConfigFilePath)
{
// Already have the application config file path in scope.
// Get the path of the machine config file.
string runtimeDir = null;
// Must Assert unrestricted FileIOPermission to get the machine config path.
new FileIOPermission(PermissionState.Unrestricted).Assert();
try {
runtimeDir = RuntimeEnvironment.GetRuntimeDirectory();
}
finally {
FileIOPermission.RevertAssert();
}
string machineConfigFilePath = Path.Combine(Path.Combine(runtimeDir, "Config"), "machine.config");
UriSectionData machineSettings = UriSectionReader.Read(machineConfigFilePath);
// pass machineSettings to ctor: appSettings will use the values of machineSettings as init values.
UriSectionData appSettings = UriSectionReader.Read(appConfigFilePath, machineSettings);
UriSectionData resultSectionData = null;
if (appSettings != null) {
resultSectionData = appSettings;
}
else if (machineSettings != null) {
resultSectionData = machineSettings;
}
if (resultSectionData != null) {
UriIdnScope idnScope = resultSectionData.IdnScope ?? IdnElement.EnabledDefaultValue;
bool iriParsing = resultSectionData.IriParsing ?? IriParsingElement.EnabledDefaultValue;
IEnumerable<SchemeSettingInternal> schemeSettings =
resultSectionData.SchemeSettings.Values as IEnumerable<SchemeSettingInternal>;
return new UriSectionInternal(idnScope, iriParsing, schemeSettings);
}
return null;
}
private static bool IsWebConfig(string appConfigFile)
{
// Determine if we are in a Web config scenario.
// Existence of string object associated with .appVPath tells
// us that this is an ASP.Net web scenario.
string appVPath = AppDomain.CurrentDomain.GetData(".appVPath") as string;
if (appVPath != null) {
return true;
}
// If application config file path not null
// and begins with http:// or https://
// then this is the No-Touch web deployment scenario.
if (appConfigFile != null) {
if (appConfigFile.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
appConfigFile.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) {
return true;
}
}
return false;
}
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseEventsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines.CSharpUseEventsWhereAppropriateFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UseEventsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines.BasicUseEventsWhereAppropriateFixer>;
namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines.UnitTests
{
public class UseEventsWhereAppropriateTests
{
#region No Diagnostic Tests
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_NamingCasesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class EventsClass1
{
public event EventHandler RaiseFileEvent;
public string RaiseAnotherProperty => null;
public void SomeMethodThatDoesNotStartWithRaise()
{
}
public void RaisedRoutine()
{
}
public void AddOneAssembly()
{
}
public void Remover()
{
}
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class EventsClass1
Public Event RaiseFileEvent As EventHandler
Public ReadOnly Property RaiseAnotherProperty() As String
Get
Return Nothing
End Get
End Property
Public Sub SomeMethodThatDoesNotStartWithRaise()
End Sub
Public Sub RaisedRoutine()
End Sub
Public Sub AddOneAssembly()
End Sub
Public Sub Remover()
End Sub
End Class
");
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_InterfaceMemberImplementationAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class InterfaceImplementation : I
{
// Explicit interface implementation - Rule does not fire.
void I.FireOnSomething_InterfaceMethod1()
{
throw new NotImplementedException();
}
// Implicit interface implementation - Rule does not fire.
public void FireOnSomething_InterfaceMethod2()
{
throw new NotImplementedException();
}
}
#pragma warning disable CA1030 // We are only testing no violations in InterfaceImplementation in this test, so suppress issues reported in the interface.
public interface I
{
// Interface methods - Rule fires.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
#pragma warning restore CA1030
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class InterfaceImplementation
Implements I
' Explicit interface implementation - Rule does not fire.
Private Sub FireOnSomething_InterfaceMethod1() Implements I.FireOnSomething_InterfaceMethod1
Throw New NotImplementedException()
End Sub
' Implicit interface implementation - Rule does not fire.
Public Sub FireOnSomething_InterfaceMethod2() Implements I.FireOnSomething_InterfaceMethod2
Throw New NotImplementedException()
End Sub
End Class
#Disable Warning CA1030 ' We are only testing no violations in InterfaceImplementation in this test, so suppress issues reported in the interface.
Public Interface I
' Interface methods - Rule fires.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
#Enable Warning CA1030
");
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task NoDiagnostic_UnflaggedMethodKindsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public class FireOnSomethingDerivedClass : BaseClass
{
// Constructor - Rule does not fire.
public FireOnSomethingDerivedClass()
{
}
// Finalizer - Rule does not fire.
~FireOnSomethingDerivedClass()
{
}
// Overridden methods - Rule does not fire.
public override void FireOnSomething()
{
throw new NotImplementedException();
}
public override void RaiseOnSomething()
{
throw new NotImplementedException();
}
public override void AddOnSomething()
{
throw new NotImplementedException();
}
public override void RemoveOnSomething()
{
throw new NotImplementedException();
}
}
#pragma warning disable CA1030 // We are only testing no violations in FireOnSomethingDerivedClass in this test, so suppress issues reported in the BaseClass.
public abstract class BaseClass
{
// Abstract method - Rule fires.
public abstract void FireOnSomething();
// Abstract method - Rule fires.
public abstract void RaiseOnSomething();
// Abstract method - Rule fires.
public abstract void AddOnSomething();
// Abstract method - Rule fires.
public abstract void RemoveOnSomething();
}
#pragma warning restore CA1030
");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Public Class FireOnSomethingDerivedClass
Inherits BaseClass
' Constructor - Rule does not fire.
Public Sub New()
End Sub
' Finalizer - Rule does not fire.
Protected Overrides Sub Finalize()
Try
Finally
MyBase.Finalize()
End Try
End Sub
' Overridden methods - Rule does not fire.
Public Overrides Sub FireOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub RaiseOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub AddOnSomething()
Throw New NotImplementedException()
End Sub
Public Overrides Sub RemoveOnSomething()
Throw New NotImplementedException()
End Sub
End Class
#Disable Warning CA1030 ' We are only testing no violations in FireOnSomethingDerivedClass in this test, so suppress issues reported in the BaseClass.
Public MustInherit Class BaseClass
' Abstract method - Rule fires.
Public MustOverride Overloads Sub FireOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub RaiseOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub AddOnSomething()
' Abstract method - Rule fires.
Public MustOverride Overloads Sub RemoveOnSomething()
End Class
#Enable Warning CA1030
");
}
[Fact, WorkItem(1432, "https://github.com/dotnet/roslyn-analyzers/issues/1432")]
public async Task NoDiagnostic_FlaggedMethodKinds_NotExternallyVisibleAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
internal interface InterfaceWithViolations
{
// Interface methods.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
public abstract class ClassWithViolations
{
private class InnerClass
{
// Static method.
public static void RaiseOnSomething_StaticMethod()
{
}
}
internal class InnerClass2
{
// Virtual method.
public virtual void FireOnSomething_VirtualMethod()
{
}
}
// Private method.
private static void RaiseOnSomething_StaticMethod()
{
}
// Abstract method.
internal abstract void FireOnSomething_AbstractMethod();
// Abstract method.
internal abstract void RaiseOnSomething_AbstractMethod();
// Abstract method.
internal abstract void AddOnSomething_AbstractMethod();
// Abstract method.
internal abstract void RemoveOnSomething_AbstractMethod();
}
");
await VerifyVB.VerifyAnalyzerAsync(@"
Friend Interface InterfaceWithViolations
' Interface methods.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
Public MustInherit Class ClassWithViolations
Private Class InnerClass
' Static method.
Public Shared Sub RaiseOnSomething_StaticMethod()
End Sub
End Class
Friend Class InnerClass2
' Virtual method.
Public Overridable Sub FireOnSomething_VirtualMethod()
End Sub
End Class
' Private method.
Private Shared Sub RaiseOnSomething_StaticMethod()
End Sub
' Abstract method.
Friend MustOverride Sub FireOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub RaiseOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub AddOnSomething_AbstractMethod()
' Abstract method.
Friend MustOverride Sub RemoveOnSomething_AbstractMethod()
End Class
");
}
#endregion
#region Diagnostic Tests
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_FlaggedMethodKindsAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
public interface InterfaceWithViolations
{
// Interface methods - Rule fires.
void FireOnSomething_InterfaceMethod1();
void FireOnSomething_InterfaceMethod2();
}
public abstract class ClassWithViolations
{
// Static method - Rule fires.
public static void RaiseOnSomething_StaticMethod()
{
}
// Virtual method - Rule fires.
public virtual void FireOnSomething_VirtualMethod()
{
}
// Abstract method - Rule fires.
public abstract void FireOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void RaiseOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void AddOnSomething_AbstractMethod();
// Abstract method - Rule fires.
public abstract void RemoveOnSomething_AbstractMethod();
}
",
// Test0.cs(7,10): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod1' an event.
GetCSharpResultAt(7, 10, "FireOnSomething_InterfaceMethod1"),
// Test0.cs(8,10): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod2' an event.
GetCSharpResultAt(8, 10, "FireOnSomething_InterfaceMethod2"),
// Test0.cs(14,24): warning CA1030: Consider making 'RaiseOnSomething_StaticMethod' an event.
GetCSharpResultAt(14, 24, "RaiseOnSomething_StaticMethod"),
// Test0.cs(19,25): warning CA1030: Consider making 'FireOnSomething_VirtualMethod' an event.
GetCSharpResultAt(19, 25, "FireOnSomething_VirtualMethod"),
// Test0.cs(24,26): warning CA1030: Consider making 'FireOnSomething_AbstractMethod' an event.
GetCSharpResultAt(24, 26, "FireOnSomething_AbstractMethod"),
// Test0.cs(27,26): warning CA1030: Consider making 'RaiseOnSomething_AbstractMethod' an event.
GetCSharpResultAt(27, 26, "RaiseOnSomething_AbstractMethod"),
// Test0.cs(30,26): warning CA1030: Consider making 'AddOnSomething_AbstractMethod' an event.
GetCSharpResultAt(30, 26, "AddOnSomething_AbstractMethod"),
// Test0.cs(33,26): warning CA1030: Consider making 'RemoveOnSomething_AbstractMethod' an event.
GetCSharpResultAt(33, 26, "RemoveOnSomething_AbstractMethod"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Interface InterfaceWithViolations
' Interface methods - Rule fires.
Sub FireOnSomething_InterfaceMethod1()
Sub FireOnSomething_InterfaceMethod2()
End Interface
Public MustInherit Class ClassWithViolations
' Static method - Rule fires.
Public Shared Sub RaiseOnSomething_StaticMethod()
End Sub
' Virtual method - Rule fires.
Public Overridable Sub FireOnSomething_VirtualMethod()
End Sub
' Abstract method - Rule fires.
Public MustOverride Sub FireOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub RaiseOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub AddOnSomething_AbstractMethod()
' Abstract method - Rule fires.
Public MustOverride Sub RemoveOnSomething_AbstractMethod()
End Class
",
// Test0.vb(4,6): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod1' an event.
GetBasicResultAt(4, 6, "FireOnSomething_InterfaceMethod1"),
// Test0.vb(5,6): warning CA1030: Consider making 'FireOnSomething_InterfaceMethod2' an event.
GetBasicResultAt(5, 6, "FireOnSomething_InterfaceMethod2"),
// Test0.vb(10,20): warning CA1030: Consider making 'RaiseOnSomething_StaticMethod' an event.
GetBasicResultAt(10, 20, "RaiseOnSomething_StaticMethod"),
// Test0.vb(14,25): warning CA1030: Consider making 'FireOnSomething_VirtualMethod' an event.
GetBasicResultAt(14, 25, "FireOnSomething_VirtualMethod"),
// Test0.vb(18,26): warning CA1030: Consider making 'FireOnSomething_AbstractMethod' an event.
GetBasicResultAt(18, 26, "FireOnSomething_AbstractMethod"),
// Test0.vb(21,26): warning CA1030: Consider making 'RaiseOnSomething_AbstractMethod' an event.
GetBasicResultAt(21, 26, "RaiseOnSomething_AbstractMethod"),
// Test0.vb(24,26): warning CA1030: Consider making 'AddOnSomething_AbstractMethod' an event.
GetBasicResultAt(24, 26, "AddOnSomething_AbstractMethod"),
// Test0.vb(27,26): warning CA1030: Consider making 'RemoveOnSomething_AbstractMethod' an event.
GetBasicResultAt(27, 26, "RemoveOnSomething_AbstractMethod"));
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_PascalCasedMethodNamesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class EventsClassPascalCased
{
public void Fire() { }
public void Raise() { }
public void RaiseFileEvent() { }
public void FireFileEvent() { }
public void AddOnFileEvent() { }
public void RemoveOnFileEvent() { }
public void Add_OnFileEvent() { }
public void Remove_OnFileEvent() { }
}
",
// Test0.cs(4,17): warning CA1030: Consider making 'Fire' an event.
GetCSharpResultAt(4, 17, "Fire"),
// Test0.cs(6,17): warning CA1030: Consider making 'Raise' an event.
GetCSharpResultAt(6, 17, "Raise"),
// Test0.cs(8,17): warning CA1030: Consider making 'RaiseFileEvent' an event.
GetCSharpResultAt(8, 17, "RaiseFileEvent"),
// Test0.cs(10,17): warning CA1030: Consider making 'FireFileEvent' an event.
GetCSharpResultAt(10, 17, "FireFileEvent"),
// Test0.cs(12,17): warning CA1030: Consider making 'AddOnFileEvent' an event.
GetCSharpResultAt(12, 17, "AddOnFileEvent"),
// Test0.cs(14,17): warning CA1030: Consider making 'RemoveOnFileEvent' an event.
GetCSharpResultAt(14, 17, "RemoveOnFileEvent"),
// Test0.cs(16,17): warning CA1030: Consider making 'Add_OnFileEvent' an event.
GetCSharpResultAt(16, 17, "Add_OnFileEvent"),
// Test0.cs(18,17): warning CA1030: Consider making 'Remove_OnFileEvent' an event.
GetCSharpResultAt(18, 17, "Remove_OnFileEvent"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class EventsClassPascalCased
Public Sub Fire()
End Sub
Public Sub Raise()
End Sub
Public Sub RaiseFileEvent()
End Sub
Public Sub FireFileEvent()
End Sub
Public Sub AddOnFileEvent()
End Sub
Public Sub RemoveOnFileEvent()
End Sub
Public Sub Add_OnFileEvent()
End Sub
Public Sub Remove_OnFileEvent()
End Sub
End Class
",
// Test0.vb(3,13): warning CA1030: Consider making 'Fire' an event.
GetBasicResultAt(3, 13, "Fire"),
// Test0.vb(6,13): warning CA1030: Consider making 'Raise' an event.
GetBasicResultAt(6, 13, "Raise"),
// Test0.vb(9,13): warning CA1030: Consider making 'RaiseFileEvent' an event.
GetBasicResultAt(9, 13, "RaiseFileEvent"),
// Test0.vb(12,13): warning CA1030: Consider making 'FireFileEvent' an event.
GetBasicResultAt(12, 13, "FireFileEvent"),
// Test0.vb(15,13): warning CA1030: Consider making 'AddOnFileEvent' an event.
GetBasicResultAt(15, 13, "AddOnFileEvent"),
// Test0.vb(18,13): warning CA1030: Consider making 'RemoveOnFileEvent' an event.
GetBasicResultAt(18, 13, "RemoveOnFileEvent"),
// Test0.vb(21,13): warning CA1030: Consider making 'Add_OnFileEvent' an event.
GetBasicResultAt(21, 13, "Add_OnFileEvent"),
// Test0.vb(24,13): warning CA1030: Consider making 'Remove_OnFileEvent' an event.
GetBasicResultAt(24, 13, "Remove_OnFileEvent"));
}
[WorkItem(380, "https://github.com/dotnet/roslyn-analyzers/issues/380")]
[Fact]
public async Task Diagnostic_LowerCaseMethodNamesAsync()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class EventsClassLowercase
{
public void fire() { }
public void raise() { }
public void raiseFileEvent() { }
public void fireFileEvent() { }
public void addOnFileEvent() { }
public void removeOnFileEvent() { }
public void add_onFileEvent() { }
public void remove_onFileEvent() { }
}
",
// Test0.cs(4,17): warning CA1030: Consider making 'fire' an event.
GetCSharpResultAt(4, 17, "fire"),
// Test0.cs(6,17): warning CA1030: Consider making 'raise' an event.
GetCSharpResultAt(6, 17, "raise"),
// Test0.cs(8,17): warning CA1030: Consider making 'raiseFileEvent' an event.
GetCSharpResultAt(8, 17, "raiseFileEvent"),
// Test0.cs(10,17): warning CA1030: Consider making 'fireFileEvent' an event.
GetCSharpResultAt(10, 17, "fireFileEvent"),
// Test0.cs(12,17): warning CA1030: Consider making 'addOnFileEvent' an event.
GetCSharpResultAt(12, 17, "addOnFileEvent"),
// Test0.cs(14,17): warning CA1030: Consider making 'removeOnFileEvent' an event.
GetCSharpResultAt(14, 17, "removeOnFileEvent"),
// Test0.cs(16,17): warning CA1030: Consider making 'add_onFileEvent' an event.
GetCSharpResultAt(16, 17, "add_onFileEvent"),
// Test0.cs(18,17): warning CA1030: Consider making 'remove_onFileEvent' an event.
GetCSharpResultAt(18, 17, "remove_onFileEvent"));
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class EventsClassLowercase
Public Sub fire()
End Sub
Public Sub raise()
End Sub
Public Sub raiseFileEvent()
End Sub
Public Sub fireFileEvent()
End Sub
Public Sub addOnFileEvent()
End Sub
Public Sub removeOnFileEvent()
End Sub
Public Sub add_onFileEvent()
End Sub
Public Sub remove_onFileEvent()
End Sub
End Class
",
// Test0.vb(3,13): warning CA1030: Consider making 'fire' an event.
GetBasicResultAt(3, 13, "fire"),
// Test0.vb(6,13): warning CA1030: Consider making 'raise' an event.
GetBasicResultAt(6, 13, "raise"),
// Test0.vb(9,13): warning CA1030: Consider making 'raiseFileEvent' an event.
GetBasicResultAt(9, 13, "raiseFileEvent"),
// Test0.vb(12,13): warning CA1030: Consider making 'fireFileEvent' an event.
GetBasicResultAt(12, 13, "fireFileEvent"),
// Test0.vb(15,13): warning CA1030: Consider making 'addOnFileEvent' an event.
GetBasicResultAt(15, 13, "addOnFileEvent"),
// Test0.vb(18,13): warning CA1030: Consider making 'removeOnFileEvent' an event.
GetBasicResultAt(18, 13, "removeOnFileEvent"),
// Test0.vb(21,13): warning CA1030: Consider making 'add_onFileEvent' an event.
GetBasicResultAt(21, 13, "add_onFileEvent"),
// Test0.vb(24,13): warning CA1030: Consider making 'remove_onFileEvent' an event.
GetBasicResultAt(24, 13, "remove_onFileEvent"));
}
#endregion
private static DiagnosticResult GetCSharpResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
private static DiagnosticResult GetBasicResultAt(int line, int column, params string[] arguments)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic()
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(arguments);
}
}
| |
/**
* (C) Copyright IBM Corp. 2019, 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.
*
*/
/**
* IBM OpenAPI SDK Code Generator Version: 3.38.0-07189efd-20210827-205025
*/
using System.Collections.Generic;
using System.Text;
using IBM.Cloud.SDK;
using IBM.Cloud.SDK.Authentication;
using IBM.Cloud.SDK.Connection;
using IBM.Cloud.SDK.Utilities;
using IBM.Watson.LanguageTranslator.V3.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using UnityEngine.Networking;
namespace IBM.Watson.LanguageTranslator.V3
{
public partial class LanguageTranslatorService : BaseService
{
private const string defaultServiceName = "language_translator";
private const string defaultServiceUrl = "https://api.us-south.language-translator.watson.cloud.ibm.com";
#region Version
private string version;
/// <summary>
/// Gets and sets the version of the service.
/// Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD format. The current
/// version is `2018-05-01`.
/// </summary>
public string Version
{
get { return version; }
set { version = value; }
}
#endregion
#region DisableSslVerification
private bool disableSslVerification = false;
/// <summary>
/// Gets and sets the option to disable ssl verification
/// </summary>
public bool DisableSslVerification
{
get { return disableSslVerification; }
set { disableSslVerification = value; }
}
#endregion
/// <summary>
/// LanguageTranslatorService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-05-01`.</param>
public LanguageTranslatorService(string version) : this(version, defaultServiceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(defaultServiceName)) {}
/// <summary>
/// LanguageTranslatorService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-05-01`.</param>
/// <param name="authenticator">The service authenticator.</param>
public LanguageTranslatorService(string version, Authenticator authenticator) : this(version, defaultServiceName, authenticator) {}
/// <summary>
/// LanguageTranslatorService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-05-01`.</param>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
public LanguageTranslatorService(string version, string serviceName) : this(version, serviceName, ConfigBasedAuthenticatorFactory.GetAuthenticator(serviceName)) {}
/// <summary>
/// LanguageTranslatorService constructor.
/// </summary>
/// <param name="version">Release date of the version of the API you want to use. Specify dates in YYYY-MM-DD
/// format. The current version is `2018-05-01`.</param>
/// <param name="serviceName">The service name to be used when configuring the client instance</param>
/// <param name="authenticator">The service authenticator.</param>
public LanguageTranslatorService(string version, string serviceName, Authenticator authenticator) : base(authenticator, serviceName)
{
Authenticator = authenticator;
if (string.IsNullOrEmpty(version))
{
throw new ArgumentNullException("`version` is required");
}
else
{
Version = version;
}
if (string.IsNullOrEmpty(GetServiceUrl()))
{
SetServiceUrl(defaultServiceUrl);
}
}
/// <summary>
/// List supported languages.
///
/// Lists all supported languages for translation. The method returns an array of supported languages with
/// information about each language. Languages are listed in alphabetical order by language code (for example,
/// `af`, `ar`). In addition to basic information about each language, the response indicates whether the
/// language is `supported_as_source` for translation and `supported_as_target` for translation. It also lists
/// whether the language is `identifiable`.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <returns><see cref="Languages" />Languages</returns>
public bool ListLanguages(Callback<Languages> callback)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListLanguages`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<Languages> req = new RequestObject<Languages>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListLanguages"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnListLanguagesResponse;
Connector.URL = GetServiceUrl() + "/v3/languages";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<Languages> response = new DetailedResponse<Languages>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<Languages>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnListLanguagesResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<Languages>)req).Callback != null)
((RequestObject<Languages>)req).Callback(response, resp.Error);
}
/// <summary>
/// Translate.
///
/// Translates the input text from the source language to the target language. Specify a model ID that indicates
/// the source and target languages, or specify the source and target languages individually. You can omit the
/// source language to have the service attempt to detect the language from the input text. If you omit the
/// source language, the request must contain sufficient input text for the service to identify the source
/// language.
///
/// You can translate a maximum of 50 KB (51,200 bytes) of text with a single request. All input text must be
/// encoded in UTF-8 format.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="text">Input text in UTF-8 encoding. Submit a maximum of 50 KB (51,200 bytes) of text with a
/// single request. Multiple elements result in multiple translations in the response.</param>
/// <param name="modelId">The model to use for translation. For example, `en-de` selects the IBM-provided base
/// model for English-to-German translation. A model ID overrides the `source` and `target` parameters and is
/// required if you use a custom model. If no model ID is specified, you must specify at least a target
/// language. (optional)</param>
/// <param name="source">Language code that specifies the language of the input text. If omitted, the service
/// derives the source language from the input text. The input must contain sufficient text for the service to
/// identify the language reliably. (optional)</param>
/// <param name="target">Language code that specifies the target language for translation. Required if model ID
/// is not specified. (optional)</param>
/// <returns><see cref="TranslationResult" />TranslationResult</returns>
public bool Translate(Callback<TranslationResult> callback, List<string> text, string modelId = null, string source = null, string target = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `Translate`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (text == null)
throw new ArgumentNullException("`text` is required for `Translate`");
RequestObject<TranslationResult> req = new RequestObject<TranslationResult>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "Translate"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.Headers["Content-Type"] = "application/json";
req.Headers["Accept"] = "application/json";
JObject bodyObject = new JObject();
if (text != null && text.Count > 0)
bodyObject["text"] = JToken.FromObject(text);
if (!string.IsNullOrEmpty(modelId))
bodyObject["model_id"] = modelId;
if (!string.IsNullOrEmpty(source))
bodyObject["source"] = source;
if (!string.IsNullOrEmpty(target))
bodyObject["target"] = target;
req.Send = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(bodyObject));
req.OnResponse = OnTranslateResponse;
Connector.URL = GetServiceUrl() + "/v3/translate";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnTranslateResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<TranslationResult> response = new DetailedResponse<TranslationResult>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<TranslationResult>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnTranslateResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<TranslationResult>)req).Callback != null)
((RequestObject<TranslationResult>)req).Callback(response, resp.Error);
}
/// <summary>
/// List identifiable languages.
///
/// Lists the languages that the service can identify. Returns the language code (for example, `en` for English
/// or `es` for Spanish) and name of each language.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <returns><see cref="IdentifiableLanguages" />IdentifiableLanguages</returns>
public bool ListIdentifiableLanguages(Callback<IdentifiableLanguages> callback)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListIdentifiableLanguages`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<IdentifiableLanguages> req = new RequestObject<IdentifiableLanguages>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListIdentifiableLanguages"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnListIdentifiableLanguagesResponse;
Connector.URL = GetServiceUrl() + "/v3/identifiable_languages";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListIdentifiableLanguagesResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<IdentifiableLanguages> response = new DetailedResponse<IdentifiableLanguages>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<IdentifiableLanguages>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnListIdentifiableLanguagesResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<IdentifiableLanguages>)req).Callback != null)
((RequestObject<IdentifiableLanguages>)req).Callback(response, resp.Error);
}
/// <summary>
/// Identify language.
///
/// Identifies the language of the input text.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="text">Input text in UTF-8 format.</param>
/// <returns><see cref="IdentifiedLanguages" />IdentifiedLanguages</returns>
public bool Identify(Callback<IdentifiedLanguages> callback, string text)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `Identify`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(text))
throw new ArgumentNullException("`text` is required for `Identify`");
RequestObject<IdentifiedLanguages> req = new RequestObject<IdentifiedLanguages>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "Identify"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.Headers["Content-Type"] = "text/plain";
req.Headers["Accept"] = "application/json";
req.Send = Encoding.UTF8.GetBytes(text);
req.OnResponse = OnIdentifyResponse;
Connector.URL = GetServiceUrl() + "/v3/identify";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnIdentifyResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<IdentifiedLanguages> response = new DetailedResponse<IdentifiedLanguages>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<IdentifiedLanguages>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnIdentifyResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<IdentifiedLanguages>)req).Callback != null)
((RequestObject<IdentifiedLanguages>)req).Callback(response, resp.Error);
}
/// <summary>
/// List models.
///
/// Lists available translation models.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="source">Specify a language code to filter results by source language. (optional)</param>
/// <param name="target">Specify a language code to filter results by target language. (optional)</param>
/// <param name="_default">If the `default` parameter isn't specified, the service returns all models (default
/// and non-default) for each language pair. To return only default models, set this parameter to `true`. To
/// return only non-default models, set this parameter to `false`. There is exactly one default model, the
/// IBM-provided base model, per language pair. (optional)</param>
/// <returns><see cref="TranslationModels" />TranslationModels</returns>
public bool ListModels(Callback<TranslationModels> callback, string source = null, string target = null, bool? _default = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListModels`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<TranslationModels> req = new RequestObject<TranslationModels>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListModels"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(source))
{
req.Parameters["source"] = source;
}
if (!string.IsNullOrEmpty(target))
{
req.Parameters["target"] = target;
}
if (_default != null)
{
req.Parameters["default"] = (bool)_default ? "true" : "false";
}
req.OnResponse = OnListModelsResponse;
Connector.URL = GetServiceUrl() + "/v3/models";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListModelsResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<TranslationModels> response = new DetailedResponse<TranslationModels>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<TranslationModels>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnListModelsResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<TranslationModels>)req).Callback != null)
((RequestObject<TranslationModels>)req).Callback(response, resp.Error);
}
/// <summary>
/// Create model.
///
/// Uploads training files to customize a translation model. You can customize a model with a forced glossary or
/// with a parallel corpus:
/// * Use a *forced glossary* to force certain terms and phrases to be translated in a specific way. You can
/// upload only a single forced glossary file for a model. The size of a forced glossary file for a custom model
/// is limited to 10 MB.
/// * Use a *parallel corpus* when you want your custom model to learn from general translation patterns in
/// parallel sentences in your samples. What your model learns from a parallel corpus can improve translation
/// results for input text that the model has not been trained on. You can upload multiple parallel corpora
/// files with a request. To successfully train with parallel corpora, the corpora files must contain a
/// cumulative total of at least 5000 parallel sentences. The cumulative size of all uploaded corpus files for a
/// custom model is limited to 250 MB.
///
/// Depending on the type of customization and the size of the uploaded files, training time can range from
/// minutes for a glossary to several hours for a large parallel corpus. To create a model that is customized
/// with a parallel corpus and a forced glossary, customize the model with a parallel corpus first and then
/// customize the resulting model with a forced glossary.
///
/// You can create a maximum of 10 custom models per language pair. For more information about customizing a
/// translation model, including the formatting and character restrictions for data files, see [Customizing your
/// model](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing).
///
/// #### Supported file formats
///
/// You can provide your training data for customization in the following document formats:
/// * **TMX** (`.tmx`) - Translation Memory eXchange (TMX) is an XML specification for the exchange of
/// translation memories.
/// * **XLIFF** (`.xliff`) - XML Localization Interchange File Format (XLIFF) is an XML specification for the
/// exchange of translation memories.
/// * **CSV** (`.csv`) - Comma-separated values (CSV) file with two columns for aligned sentences and phrases.
/// The first row must have two language codes. The first column is for the source language code, and the second
/// column is for the target language code.
/// * **TSV** (`.tsv` or `.tab`) - Tab-separated values (TSV) file with two columns for aligned sentences and
/// phrases. The first row must have two language codes. The first column is for the source language code, and
/// the second column is for the target language code.
/// * **JSON** (`.json`) - Custom JSON format for specifying aligned sentences and phrases.
/// * **Microsoft Excel** (`.xls` or `.xlsx`) - Excel file with the first two columns for aligned sentences and
/// phrases. The first row contains the language code.
///
/// You must encode all text data in UTF-8 format. For more information, see [Supported document formats for
/// training
/// data](https://cloud.ibm.com/docs/language-translator?topic=language-translator-customizing#supported-document-formats-for-training-data).
///
///
/// #### Specifying file formats
///
/// You can indicate the format of a file by including the file extension with the file name. Use the file
/// extensions shown in **Supported file formats**.
///
/// Alternatively, you can omit the file extension and specify one of the following `content-type`
/// specifications for the file:
/// * **TMX** - `application/x-tmx+xml`
/// * **XLIFF** - `application/xliff+xml`
/// * **CSV** - `text/csv`
/// * **TSV** - `text/tab-separated-values`
/// * **JSON** - `application/json`
/// * **Microsoft Excel** - `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
///
/// For example, with `curl`, use the following `content-type` specification to indicate the format of a CSV
/// file named **glossary**:
///
/// `--form "forced_glossary=@glossary;type=text/csv"`.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="baseModelId">The ID of the translation model to use as the base for customization. To see
/// available models and IDs, use the `List models` method. Most models that are provided with the service are
/// customizable. In addition, all models that you create with parallel corpora customization can be further
/// customized with a forced glossary.</param>
/// <param name="forcedGlossary">A file with forced glossary terms for the source and target languages. The
/// customizations in the file completely overwrite the domain translation data, including high frequency or
/// high confidence phrase translations.
///
/// You can upload only one glossary file for a custom model, and the glossary can have a maximum size of 10 MB.
/// A forced glossary must contain single words or short phrases. For more information, see **Supported file
/// formats** in the method description.
///
/// *With `curl`, use `--form forced_glossary=@{filename}`.*. (optional)</param>
/// <param name="parallelCorpus">A file with parallel sentences for the source and target languages. You can
/// upload multiple parallel corpus files in one request by repeating the parameter. All uploaded parallel
/// corpus files combined must contain at least 5000 parallel sentences to train successfully. You can provide a
/// maximum of 500,000 parallel sentences across all corpora.
///
/// A single entry in a corpus file can contain a maximum of 80 words. All corpora files for a custom model can
/// have a cumulative maximum size of 250 MB. For more information, see **Supported file formats** in the method
/// description.
///
/// *With `curl`, use `--form parallel_corpus=@{filename}`.*. (optional)</param>
/// <param name="name">An optional model name that you can use to identify the model. Valid characters are
/// letters, numbers, dashes, underscores, spaces, and apostrophes. The maximum length of the name is 32
/// characters. (optional)</param>
/// <returns><see cref="TranslationModel" />TranslationModel</returns>
public bool CreateModel(Callback<TranslationModel> callback, string baseModelId, System.IO.MemoryStream forcedGlossary = null, System.IO.MemoryStream parallelCorpus = null, string name = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `CreateModel`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(baseModelId))
throw new ArgumentNullException("`baseModelId` is required for `CreateModel`");
RequestObject<TranslationModel> req = new RequestObject<TranslationModel>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "CreateModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (forcedGlossary != null)
{
req.Forms["forced_glossary"] = new RESTConnector.Form(forcedGlossary, "filename", "application/octet-stream");
}
if (parallelCorpus != null)
{
req.Forms["parallel_corpus"] = new RESTConnector.Form(parallelCorpus, "filename", "application/octet-stream");
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
if (!string.IsNullOrEmpty(baseModelId))
{
req.Parameters["base_model_id"] = baseModelId;
}
if (!string.IsNullOrEmpty(name))
{
req.Parameters["name"] = name;
}
req.OnResponse = OnCreateModelResponse;
Connector.URL = GetServiceUrl() + "/v3/models";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnCreateModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<TranslationModel> response = new DetailedResponse<TranslationModel>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<TranslationModel>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnCreateModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<TranslationModel>)req).Callback != null)
((RequestObject<TranslationModel>)req).Callback(response, resp.Error);
}
/// <summary>
/// Delete model.
///
/// Deletes a custom translation model.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="modelId">Model ID of the model to delete.</param>
/// <returns><see cref="DeleteModelResult" />DeleteModelResult</returns>
public bool DeleteModel(Callback<DeleteModelResult> callback, string modelId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `DeleteModel`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(modelId))
throw new ArgumentNullException("`modelId` is required for `DeleteModel`");
RequestObject<DeleteModelResult> req = new RequestObject<DeleteModelResult>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbDELETE,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "DeleteModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnDeleteModelResponse;
Connector.URL = GetServiceUrl() + string.Format("/v3/models/{0}", modelId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnDeleteModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<DeleteModelResult> response = new DetailedResponse<DeleteModelResult>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<DeleteModelResult>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnDeleteModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<DeleteModelResult>)req).Callback != null)
((RequestObject<DeleteModelResult>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get model details.
///
/// Gets information about a translation model, including training status for custom models. Use this API call
/// to poll the status of your customization request. A successfully completed training has a status of
/// `available`.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="modelId">Model ID of the model to get.</param>
/// <returns><see cref="TranslationModel" />TranslationModel</returns>
public bool GetModel(Callback<TranslationModel> callback, string modelId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetModel`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(modelId))
throw new ArgumentNullException("`modelId` is required for `GetModel`");
RequestObject<TranslationModel> req = new RequestObject<TranslationModel>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "GetModel"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnGetModelResponse;
Connector.URL = GetServiceUrl() + string.Format("/v3/models/{0}", modelId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetModelResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<TranslationModel> response = new DetailedResponse<TranslationModel>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<TranslationModel>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnGetModelResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<TranslationModel>)req).Callback != null)
((RequestObject<TranslationModel>)req).Callback(response, resp.Error);
}
/// <summary>
/// List documents.
///
/// Lists documents that have been submitted for translation.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <returns><see cref="DocumentList" />DocumentList</returns>
public bool ListDocuments(Callback<DocumentList> callback)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `ListDocuments`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
RequestObject<DocumentList> req = new RequestObject<DocumentList>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "ListDocuments"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnListDocumentsResponse;
Connector.URL = GetServiceUrl() + "/v3/documents";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnListDocumentsResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<DocumentList> response = new DetailedResponse<DocumentList>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<DocumentList>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnListDocumentsResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<DocumentList>)req).Callback != null)
((RequestObject<DocumentList>)req).Callback(response, resp.Error);
}
/// <summary>
/// Translate document.
///
/// Submit a document for translation. You can submit the document contents in the `file` parameter, or you can
/// reference a previously submitted document by document ID. The maximum file size for document translation is
/// * 20 MB for service instances on the Standard, Advanced, and Premium plans
/// * 2 MB for service instances on the Lite plan.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="file">The contents of the source file to translate. The maximum file size for document
/// translation is 20 MB for service instances on the Standard, Advanced, and Premium plans, and 2 MB for
/// service instances on the Lite plan. For more information, see [Supported file formats
/// (Beta)](https://cloud.ibm.com/docs/language-translator?topic=language-translator-document-translator-tutorial#supported-file-formats).</param>
/// <param name="filename">The filename for file.</param>
/// <param name="fileContentType">The content type of file. (optional)</param>
/// <param name="modelId">The model to use for translation. For example, `en-de` selects the IBM-provided base
/// model for English-to-German translation. A model ID overrides the `source` and `target` parameters and is
/// required if you use a custom model. If no model ID is specified, you must specify at least a target
/// language. (optional)</param>
/// <param name="source">Language code that specifies the language of the source document. If omitted, the
/// service derives the source language from the input text. The input must contain sufficient text for the
/// service to identify the language reliably. (optional)</param>
/// <param name="target">Language code that specifies the target language for translation. Required if model ID
/// is not specified. (optional)</param>
/// <param name="documentId">To use a previously submitted document as the source for a new translation, enter
/// the `document_id` of the document. (optional)</param>
/// <returns><see cref="DocumentStatus" />DocumentStatus</returns>
public bool TranslateDocument(Callback<DocumentStatus> callback, System.IO.MemoryStream file, string filename, string fileContentType = null, string modelId = null, string source = null, string target = null, string documentId = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `TranslateDocument`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (file == null)
throw new ArgumentNullException("`file` is required for `TranslateDocument`");
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException("`filename` is required for `TranslateDocument`");
RequestObject<DocumentStatus> req = new RequestObject<DocumentStatus>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbPOST,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "TranslateDocument"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
req.Forms = new Dictionary<string, RESTConnector.Form>();
if (file != null)
{
req.Forms["file"] = new RESTConnector.Form(file, filename, fileContentType);
}
if (!string.IsNullOrEmpty(modelId))
{
req.Forms["model_id"] = new RESTConnector.Form(modelId);
}
if (!string.IsNullOrEmpty(source))
{
req.Forms["source"] = new RESTConnector.Form(source);
}
if (!string.IsNullOrEmpty(target))
{
req.Forms["target"] = new RESTConnector.Form(target);
}
if (!string.IsNullOrEmpty(documentId))
{
req.Forms["document_id"] = new RESTConnector.Form(documentId);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnTranslateDocumentResponse;
Connector.URL = GetServiceUrl() + "/v3/documents";
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnTranslateDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<DocumentStatus> response = new DetailedResponse<DocumentStatus>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<DocumentStatus>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnTranslateDocumentResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<DocumentStatus>)req).Callback != null)
((RequestObject<DocumentStatus>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get document status.
///
/// Gets the translation status of a document.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="documentId">The document ID of the document.</param>
/// <returns><see cref="DocumentStatus" />DocumentStatus</returns>
public bool GetDocumentStatus(Callback<DocumentStatus> callback, string documentId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetDocumentStatus`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(documentId))
throw new ArgumentNullException("`documentId` is required for `GetDocumentStatus`");
RequestObject<DocumentStatus> req = new RequestObject<DocumentStatus>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "GetDocumentStatus"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnGetDocumentStatusResponse;
Connector.URL = GetServiceUrl() + string.Format("/v3/documents/{0}", documentId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetDocumentStatusResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<DocumentStatus> response = new DetailedResponse<DocumentStatus>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<DocumentStatus>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnGetDocumentStatusResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<DocumentStatus>)req).Callback != null)
((RequestObject<DocumentStatus>)req).Callback(response, resp.Error);
}
/// <summary>
/// Delete document.
///
/// Deletes a document.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="documentId">Document ID of the document to delete.</param>
/// <returns><see cref="object" />object</returns>
public bool DeleteDocument(Callback<object> callback, string documentId)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `DeleteDocument`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(documentId))
throw new ArgumentNullException("`documentId` is required for `DeleteDocument`");
RequestObject<object> req = new RequestObject<object>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbDELETE,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "DeleteDocument"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnDeleteDocumentResponse;
Connector.URL = GetServiceUrl() + string.Format("/v3/documents/{0}", documentId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnDeleteDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<object> response = new DetailedResponse<object>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
try
{
string json = Encoding.UTF8.GetString(resp.Data);
response.Result = JsonConvert.DeserializeObject<object>(json);
response.Response = json;
}
catch (Exception e)
{
Log.Error("LanguageTranslatorService.OnDeleteDocumentResponse()", "Exception: {0}", e.ToString());
resp.Success = false;
}
if (((RequestObject<object>)req).Callback != null)
((RequestObject<object>)req).Callback(response, resp.Error);
}
/// <summary>
/// Get translated document.
///
/// Gets the translated document associated with the given document ID.
/// </summary>
/// <param name="callback">The callback function that is invoked when the operation completes.</param>
/// <param name="documentId">The document ID of the document that was submitted for translation.</param>
/// <param name="accept">The type of the response: application/powerpoint, application/mspowerpoint,
/// application/x-rtf, application/json, application/xml, application/vnd.ms-excel,
/// application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-powerpoint,
/// application/vnd.openxmlformats-officedocument.presentationml.presentation, application/msword,
/// application/vnd.openxmlformats-officedocument.wordprocessingml.document,
/// application/vnd.oasis.opendocument.spreadsheet, application/vnd.oasis.opendocument.presentation,
/// application/vnd.oasis.opendocument.text, application/pdf, application/rtf, text/html, text/json, text/plain,
/// text/richtext, text/rtf, or text/xml. A character encoding can be specified by including a `charset`
/// parameter. For example, 'text/html;charset=utf-8'. (optional)</param>
/// <returns><see cref="byte[]" />byte[]</returns>
public bool GetTranslatedDocument(Callback<byte[]> callback, string documentId, string accept = null)
{
if (callback == null)
throw new ArgumentNullException("`callback` is required for `GetTranslatedDocument`");
if (string.IsNullOrEmpty(Version))
throw new ArgumentNullException("`Version` is required");
if (string.IsNullOrEmpty(documentId))
throw new ArgumentNullException("`documentId` is required for `GetTranslatedDocument`");
RequestObject<byte[]> req = new RequestObject<byte[]>
{
Callback = callback,
HttpMethod = UnityWebRequest.kHttpVerbGET,
DisableSslVerification = DisableSslVerification
};
foreach (KeyValuePair<string, string> kvp in customRequestHeaders)
{
req.Headers.Add(kvp.Key, kvp.Value);
}
ClearCustomRequestHeaders();
foreach (KeyValuePair<string, string> kvp in Common.GetSdkHeaders("language_translator", "V3", "GetTranslatedDocument"))
{
req.Headers.Add(kvp.Key, kvp.Value);
}
if (!string.IsNullOrEmpty(Version))
{
req.Parameters["version"] = Version;
}
req.OnResponse = OnGetTranslatedDocumentResponse;
Connector.URL = GetServiceUrl() + string.Format("/v3/documents/{0}/translated_document", documentId);
Authenticator.Authenticate(Connector);
return Connector.Send(req);
}
private void OnGetTranslatedDocumentResponse(RESTConnector.Request req, RESTConnector.Response resp)
{
DetailedResponse<byte[]> response = new DetailedResponse<byte[]>();
foreach (KeyValuePair<string, string> kvp in resp.Headers)
{
response.Headers.Add(kvp.Key, kvp.Value);
}
response.StatusCode = resp.HttpResponseCode;
response.Result = resp.Data;
if (((RequestObject<byte[]>)req).Callback != null)
((RequestObject<byte[]>)req).Callback(response, resp.Error);
}
}
}
| |
using System;
using System.Diagnostics;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Framework;
using Microsoft.Build.Shared;
namespace Microsoft.Build.BackEnd.Logging
{
/// <summary>
/// This object encapsulates the logging service plus the current BuildEventContext and
/// hides the requirement to pass BuildEventContexts to the logging service or query the
/// host for the logging service all of the time.
/// </summary>
internal class LoggingContext
{
/// <summary>
/// The logging service to which this context is attached
/// </summary>
private readonly ILoggingService _loggingService;
/// <summary>
/// The build event context understood by the logging service.
/// </summary>
private BuildEventContext _eventContext;
/// <summary>
/// True if this context is still valid (i.e. hasn't been "finished")
/// </summary>
private bool _isValid;
protected bool _hasLoggedErrors;
/// <summary>
/// Constructs the logging context from a logging service and an event context.
/// </summary>
/// <param name="loggingService">The logging service to use</param>
/// <param name="eventContext">The event context</param>
public LoggingContext(ILoggingService loggingService, BuildEventContext eventContext)
{
ErrorUtilities.VerifyThrowArgumentNull(loggingService, nameof(loggingService));
ErrorUtilities.VerifyThrowArgumentNull(eventContext, nameof(eventContext));
_loggingService = loggingService;
_eventContext = eventContext;
_isValid = false;
_hasLoggedErrors = false;
}
/// <summary>
/// Constructs a logging context from another logging context. This is used primarily in
/// the constructors for other logging contexts to populate the logging service parameter,
/// while the event context will come from a call into the logging service itself.
/// </summary>
/// <param name="baseContext">The context from which this context is being created.</param>
public LoggingContext(LoggingContext baseContext)
{
_loggingService = baseContext._loggingService;
_eventContext = null;
_isValid = baseContext._isValid;
}
/// <summary>
/// Retrieves the logging service
/// </summary>
public ILoggingService LoggingService
{
[DebuggerStepThrough]
get
{ return _loggingService; }
}
/// <summary>
/// Retrieves the build event context
/// UNDONE: (Refactor) We eventually want to remove this because all logging should go
/// through a context object. This exists only so we can make certain
/// logging calls in code which has not yet been fully refactored.
/// </summary>
public BuildEventContext BuildEventContext
{
[DebuggerStepThrough]
get
{
return _eventContext;
}
protected set
{
ErrorUtilities.VerifyThrow(_eventContext == null, "eventContext should be null");
_eventContext = value;
}
}
/// <summary>
/// Returns true if the context is still valid, false if the
/// appropriate 'Finished' call has been invoked.
/// </summary>
public bool IsValid
{
[DebuggerStepThrough]
get
{
return _isValid;
}
[DebuggerStepThrough]
protected set
{
_isValid = value;
}
}
internal bool HasLoggedErrors { get { return _hasLoggedErrors; } set { _hasLoggedErrors = value; } }
/// <summary>
/// Helper method to create a message build event from a string resource and some parameters
/// </summary>
/// <param name="importance">Importance level of the message</param>
/// <param name="messageResourceName">string within the resource which indicates the format string to use</param>
/// <param name="messageArgs">string resource arguments</param>
internal void LogComment(MessageImportance importance, string messageResourceName, params object[] messageArgs)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogComment(_eventContext, importance, messageResourceName, messageArgs);
}
/// <summary>
/// Helper method to create a message build event from a string
/// </summary>
/// <param name="importance">Importance level of the message</param>
/// <param name="message">message to log</param>
internal void LogCommentFromText(MessageImportance importance, string message)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogCommentFromText(_eventContext, importance, message);
}
/// <summary>
/// Log an error
/// </summary>
/// <param name="file">The file in which the error occurred</param>
/// <param name="messageResourceName">The resource name for the error</param>
/// <param name="messageArgs">Parameters for the resource string</param>
internal void LogError(BuildEventFileInfo file, string messageResourceName, params object[] messageArgs)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogError(_eventContext, file, messageResourceName, messageArgs);
_hasLoggedErrors = true;
}
/// <summary>
/// Log an error
/// </summary>
/// <param name="subcategoryResourceName">The resource name which indicates the subCategory</param>
/// <param name="file">The file in which the error occurred</param>
/// <param name="messageResourceName">The resource name for the error</param>
/// <param name="messageArgs">Parameters for the resource string</param>
internal void LogErrorWithSubcategory(string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogError(_eventContext, subcategoryResourceName, file, messageResourceName, messageArgs);
_hasLoggedErrors = true;
}
/// <summary>
/// Log an error
/// </summary>
/// <param name="subcategoryResourceName">The resource name which indicates the subCategory</param>
/// <param name="errorCode"> Error code</param>
/// <param name="helpKeyword">Help keyword</param>
/// <param name="file">The file in which the error occurred</param>
/// <param name="message">Error message</param>
internal void LogErrorFromText(string subcategoryResourceName, string errorCode, string helpKeyword, BuildEventFileInfo file, string message)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogErrorFromText(_eventContext, subcategoryResourceName, errorCode, helpKeyword, file, message);
_hasLoggedErrors = true;
}
/// <summary>
/// Log an invalid project file exception
/// </summary>
/// <param name="invalidProjectFileException">The invalid Project File Exception which is to be logged</param>
internal void LogInvalidProjectFileError(InvalidProjectFileException invalidProjectFileException)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogInvalidProjectFileError(_eventContext, invalidProjectFileException);
_hasLoggedErrors = true;
}
/// <summary>
/// Log an error based on an exception
/// </summary>
/// <param name="exception">The exception wich is to be logged</param>
/// <param name="file">The file in which the error occurred</param>
/// <param name="messageResourceName">The string resource which has the formatting string for the error</param>
/// <param name="messageArgs">The arguments for the error message</param>
internal void LogFatalError(Exception exception, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogFatalError(_eventContext, exception, file, messageResourceName, messageArgs);
_hasLoggedErrors = true;
}
/// <summary>
/// Log a warning
/// </summary>
/// <param name="subcategoryResourceName">The subcategory resource name</param>
/// <param name="file">The file in which the warning occurred</param>
/// <param name="messageResourceName">The string resource which contains the formatted warning string</param>
/// <param name="messageArgs">parameters for the string resource</param>
internal void LogWarning(string subcategoryResourceName, BuildEventFileInfo file, string messageResourceName, params object[] messageArgs)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogWarning(_eventContext, subcategoryResourceName, file, messageResourceName, messageArgs);
}
/// <summary>
/// Log a warning based on a text message
/// </summary>
/// <param name="subcategoryResourceName">The subcategory resource name</param>
/// <param name="warningCode"> Warning code</param>
/// <param name="helpKeyword"> Help keyword</param>
/// <param name="file">The file in which the warning occurred</param>
/// <param name="message">The message to be logged as a warning</param>
internal void LogWarningFromText(string subcategoryResourceName, string warningCode, string helpKeyword, BuildEventFileInfo file, string message)
{
ErrorUtilities.VerifyThrow(_isValid, "must be valid");
_loggingService.LogWarningFromText(_eventContext, subcategoryResourceName, warningCode, helpKeyword, file, message);
}
/// <summary>
/// Will Log a build Event. Will also take into account OnlyLogCriticalEvents when determining if to drop the event or to log it.
/// </summary>
/// <param name="buildEvent">The event to log</param>
internal void LogBuildEvent(BuildEventArgs buildEvent)
{
ErrorUtilities.VerifyThrow(IsValid, "must be valid");
LoggingService.LogBuildEvent(buildEvent);
}
/// <summary>
/// Log an error based on an exception
/// </summary>
/// <param name="exception">The exception to be logged</param>
/// <param name="file">The file in which the error occurred</param>
internal void LogFatalBuildError(Exception exception, BuildEventFileInfo file)
{
ErrorUtilities.VerifyThrow(IsValid, "must be valid");
LoggingService.LogFatalBuildError(BuildEventContext, exception, file);
_hasLoggedErrors = true;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.