context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System.Collections.Generic;
using System.Diagnostics;
namespace CocosSharp
{
public class CCAnimationCache
{
static CCAnimationCache sharedAnimationCache;
Dictionary<string, CCAnimation> animations;
#region Properties
public static CCAnimationCache SharedAnimationCache
{
get
{
if (sharedAnimationCache == null)
{
sharedAnimationCache = new CCAnimationCache();
}
return sharedAnimationCache;
}
}
public CCAnimation this[string index]
{
get
{
CCAnimation retValue;
animations.TryGetValue(index, out retValue);
return retValue;
}
set
{
animations[index] = value;
}
}
#endregion Properties
#region Constructors
public CCAnimationCache()
{
animations = new Dictionary<string, CCAnimation>();
}
#endregion Constructors
#region Cleaning up
public static void PurgeSharedAnimationCached()
{
sharedAnimationCache = null;
}
#endregion Cleaning up
public void AddAnimation(CCAnimation animation, string name)
{
if (!animations.ContainsKey(name))
{
animations.Add(name, animation);
}
}
public void RemoveAnimation(string animationName)
{
if (string.IsNullOrEmpty(animationName))
{
return;
}
animations.Remove(animationName);
}
internal void AddAnimations(PlistDictionary animationDict)
{
PlistDictionary animations = animationDict["animations"].AsDictionary;
if (animations == null)
{
CCLog.Log("CocosSharp: CCAnimationCache: No animations were found in provided dictionary.");
return;
}
PlistDictionary properties = animationDict["properties"].AsDictionary;
if (properties != null)
{
int version = properties["format"].AsInt;
PlistArray spritesheets = properties["spritesheets"].AsArray;
foreach (PlistObjectBase pObj in spritesheets)
{
string name = pObj.AsString;
CCSpriteFrameCache.SharedSpriteFrameCache.AddSpriteFrames(name);
}
switch (version)
{
case 1:
ParseVersion1(animations);
break;
case 2:
ParseVersion2(animations);
break;
default:
Debug.Assert(false, "Invalid animation format");
break;
}
}
}
public void AddAnimations(string plistFilename)
{
Debug.Assert(!string.IsNullOrEmpty(plistFilename), "Invalid texture file name");
PlistDocument document = CCContentManager.SharedContentManager.Load<PlistDocument>(plistFilename);
PlistDictionary dict = document.Root.AsDictionary;
Debug.Assert(dict != null, "CCAnimationCache: File could not be found");
this.AddAnimations(dict);
}
#region Parsing plist animation dict
void ParseVersion1(PlistDictionary animations)
{
CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;
foreach (var pElement in animations)
{
PlistDictionary animationDict = pElement.Value.AsDictionary;
PlistArray frameNames = animationDict["frames"].AsArray;
float delay = animationDict["delay"].AsFloat;
if (frameNames == null)
{
CCLog.Log(
"CocosSharp: CCAnimationCache: Animation '{0}' found in dictionary without any frames - cannot add to animation cache.",
pElement.Key);
continue;
}
var frames = new List<CCAnimationFrame>(frameNames.Count);
foreach (PlistObjectBase pObj in frameNames)
{
string frameName = pObj.AsString;
CCSpriteFrame spriteFrame = frameCache[frameName];
if (spriteFrame == null)
{
CCLog.Log(
"cocos2d: CCAnimationCache: Animation '{0}' refers to frame '%s' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
pElement.Key, frameName);
continue;
}
var animFrame = new CCAnimationFrame(spriteFrame, 1, null);
frames.Add(animFrame);
}
if (frames.Count == 0)
{
CCLog.Log(
"CocosSharp: CCAnimationCache: None of the frames for animation '{0}' were found in the CCSpriteFrameCache. Animation is not being added to the Animation Cache.",
pElement.Key);
continue;
}
else if (frames.Count != frameNames.Count)
{
CCLog.Log(
"CocosSharp: CCAnimationCache: An animation in your dictionary refers to a frame which is not in the CCSpriteFrameCache. Some or all of the frames for the animation '{0}' may be missing.",
pElement.Key);
}
CCAnimation animation = new CCAnimation(frames, delay, 1);
this.AddAnimation(animation, pElement.Key);
}
}
void ParseVersion2(PlistDictionary animations)
{
CCSpriteFrameCache frameCache = CCSpriteFrameCache.SharedSpriteFrameCache;
foreach (var pElement in animations)
{
string name = pElement.Key;
PlistDictionary animationDict = pElement.Value.AsDictionary;
int loops = animationDict["loops"].AsInt;
bool restoreOriginalFrame = animationDict["restoreOriginalFrame"].AsBool;
PlistArray frameArray = animationDict["frames"].AsArray;
if (frameArray == null)
{
CCLog.Log(
"CocosSharp: CCAnimationCache: Animation '{0}' found in dictionary without any frames - cannot add to animation cache.",
name);
continue;
}
// Array of AnimationFrames
var array = new List<CCAnimationFrame>(frameArray.Count);
foreach (PlistObjectBase pObj in frameArray)
{
PlistDictionary entry = pObj.AsDictionary;
string spriteFrameName = entry["spriteframe"].AsString;
CCSpriteFrame spriteFrame = frameCache[spriteFrameName];
if (spriteFrame == null)
{
CCLog.Log(
"cocos2d: CCAnimationCache: Animation '{0}' refers to frame '{1}' which is not currently in the CCSpriteFrameCache. This frame will not be added to the animation.",
name, spriteFrameName);
continue;
}
float delayUnits = entry["delayUnits"].AsFloat;
PlistDictionary userInfo = entry["notification"].AsDictionary;
var animFrame = new CCAnimationFrame(spriteFrame, delayUnits, userInfo);
array.Add(animFrame);
}
float delayPerUnit = animationDict["delayPerUnit"].AsFloat;
var animation = new CCAnimation(array, delayPerUnit, (uint) loops);
animation.RestoreOriginalFrame = restoreOriginalFrame;
this.AddAnimation(animation, name);
}
}
#endregion Parsing plist animation dict
}
}
| |
#region Apache License
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
// .NET Compact Framework 1.0 has no support for Marshal.StringToHGlobalAnsi
// SSCLI 1.0 has no support for Marshal.StringToHGlobalAnsi
#if !NETCF && !SSCLI
using System;
using System.Runtime.InteropServices;
using log4net.Core;
using log4net.Appender;
using log4net.Util;
using log4net.Layout;
namespace log4net.Appender
{
/// <summary>
/// Logs events to a local syslog service.
/// </summary>
/// <remarks>
/// <note>
/// This appender uses the POSIX libc library functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c>.
/// If these functions are not available on the local system then this appender will not work!
/// </note>
/// <para>
/// The functions <c>openlog</c>, <c>syslog</c>, and <c>closelog</c> are specified in SUSv2 and
/// POSIX 1003.1-2001 standards. These are used to log messages to the local syslog service.
/// </para>
/// <para>
/// This appender talks to a local syslog service. If you need to log to a remote syslog
/// daemon and you cannot configure your local syslog service to do this you may be
/// able to use the <see cref="RemoteSyslogAppender"/> to log via UDP.
/// </para>
/// <para>
/// Syslog messages must have a facility and and a severity. The severity
/// is derived from the Level of the logging event.
/// The facility must be chosen from the set of defined syslog
/// <see cref="SyslogFacility"/> values. The facilities list is predefined
/// and cannot be extended.
/// </para>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
/// <author>Rob Lyon</author>
/// <author>Nicko Cadell</author>
public class LocalSyslogAppender : AppenderSkeleton
{
#region Enumerations
/// <summary>
/// syslog severities
/// </summary>
/// <remarks>
/// <para>
/// The log4net Level maps to a syslog severity using the
/// <see cref="LocalSyslogAppender.AddMapping"/> method and the <see cref="LevelSeverity"/>
/// class. The severity is set on <see cref="LevelSeverity.Severity"/>.
/// </para>
/// </remarks>
public enum SyslogSeverity
{
/// <summary>
/// system is unusable
/// </summary>
Emergency = 0,
/// <summary>
/// action must be taken immediately
/// </summary>
Alert = 1,
/// <summary>
/// critical conditions
/// </summary>
Critical = 2,
/// <summary>
/// error conditions
/// </summary>
Error = 3,
/// <summary>
/// warning conditions
/// </summary>
Warning = 4,
/// <summary>
/// normal but significant condition
/// </summary>
Notice = 5,
/// <summary>
/// informational
/// </summary>
Informational = 6,
/// <summary>
/// debug-level messages
/// </summary>
Debug = 7
};
/// <summary>
/// syslog facilities
/// </summary>
/// <remarks>
/// <para>
/// The syslog facility defines which subsystem the logging comes from.
/// This is set on the <see cref="Facility"/> property.
/// </para>
/// </remarks>
public enum SyslogFacility
{
/// <summary>
/// kernel messages
/// </summary>
Kernel = 0,
/// <summary>
/// random user-level messages
/// </summary>
User = 1,
/// <summary>
/// mail system
/// </summary>
Mail = 2,
/// <summary>
/// system daemons
/// </summary>
Daemons = 3,
/// <summary>
/// security/authorization messages
/// </summary>
Authorization = 4,
/// <summary>
/// messages generated internally by syslogd
/// </summary>
Syslog = 5,
/// <summary>
/// line printer subsystem
/// </summary>
Printer = 6,
/// <summary>
/// network news subsystem
/// </summary>
News = 7,
/// <summary>
/// UUCP subsystem
/// </summary>
Uucp = 8,
/// <summary>
/// clock (cron/at) daemon
/// </summary>
Clock = 9,
/// <summary>
/// security/authorization messages (private)
/// </summary>
Authorization2 = 10,
/// <summary>
/// ftp daemon
/// </summary>
Ftp = 11,
/// <summary>
/// NTP subsystem
/// </summary>
Ntp = 12,
/// <summary>
/// log audit
/// </summary>
Audit = 13,
/// <summary>
/// log alert
/// </summary>
Alert = 14,
/// <summary>
/// clock daemon
/// </summary>
Clock2 = 15,
/// <summary>
/// reserved for local use
/// </summary>
Local0 = 16,
/// <summary>
/// reserved for local use
/// </summary>
Local1 = 17,
/// <summary>
/// reserved for local use
/// </summary>
Local2 = 18,
/// <summary>
/// reserved for local use
/// </summary>
Local3 = 19,
/// <summary>
/// reserved for local use
/// </summary>
Local4 = 20,
/// <summary>
/// reserved for local use
/// </summary>
Local5 = 21,
/// <summary>
/// reserved for local use
/// </summary>
Local6 = 22,
/// <summary>
/// reserved for local use
/// </summary>
Local7 = 23
}
#endregion // Enumerations
#region Public Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="LocalSyslogAppender" /> class.
/// </summary>
/// <remarks>
/// This instance of the <see cref="LocalSyslogAppender" /> class is set up to write
/// to a local syslog service.
/// </remarks>
public LocalSyslogAppender()
{
}
#endregion // Public Instance Constructors
#region Public Instance Properties
/// <summary>
/// Message identity
/// </summary>
/// <remarks>
/// <para>
/// An identifier is specified with each log message. This can be specified
/// by setting the <see cref="Identity"/> property. The identity (also know
/// as the tag) must not contain white space. The default value for the
/// identity is the application name (from <see cref="SystemInfo.ApplicationFriendlyName"/>).
/// </para>
/// </remarks>
public string Identity
{
get { return m_identity; }
set { m_identity = value; }
}
/// <summary>
/// Syslog facility
/// </summary>
/// <remarks>
/// Set to one of the <see cref="SyslogFacility"/> values. The list of
/// facilities is predefined and cannot be extended. The default value
/// is <see cref="SyslogFacility.User"/>.
/// </remarks>
public SyslogFacility Facility
{
get { return m_facility; }
set { m_facility = value; }
}
#endregion // Public Instance Properties
/// <summary>
/// Add a mapping of level to severity
/// </summary>
/// <param name="mapping">The mapping to add</param>
/// <remarks>
/// <para>
/// Adds a <see cref="LevelSeverity"/> to this appender.
/// </para>
/// </remarks>
public void AddMapping(LevelSeverity mapping)
{
m_levelMapping.Add(mapping);
}
#region IOptionHandler Implementation
/// <summary>
/// Initialize the appender based on the options set.
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
[System.Security.SecuritySafeCritical]
#endif
public override void ActivateOptions()
{
base.ActivateOptions();
m_levelMapping.ActivateOptions();
string identString = m_identity;
if (identString == null)
{
// Set to app name by default
identString = SystemInfo.ApplicationFriendlyName;
}
// create the native heap ansi string. Note this is a copy of our string
// so we do not need to hold on to the string itself, holding on to the
// handle will keep the heap ansi string alive.
m_handleToIdentity = Marshal.StringToHGlobalAnsi(identString);
// open syslog
openlog(m_handleToIdentity, 1, m_facility);
}
#endregion // IOptionHandler Implementation
#region AppenderSkeleton Implementation
/// <summary>
/// This method is called by the <see cref="M:AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">The event to log.</param>
/// <remarks>
/// <para>
/// Writes the event to a remote syslog daemon.
/// </para>
/// <para>
/// The format of the output will depend on the appender's layout.
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
[System.Security.SecuritySafeCritical]
#endif
#if !NETSTANDARD1_3
[System.Security.Permissions.SecurityPermission(System.Security.Permissions.SecurityAction.Demand, UnmanagedCode = true)]
#endif
protected override void Append(LoggingEvent loggingEvent)
{
int priority = GeneratePriority(m_facility, GetSeverity(loggingEvent.Level));
string message = RenderLoggingEvent(loggingEvent);
// Call the local libc syslog method
// The second argument is a printf style format string
syslog(priority, "%s", message);
}
/// <summary>
/// Close the syslog when the appender is closed
/// </summary>
/// <remarks>
/// <para>
/// Close the syslog when the appender is closed
/// </para>
/// </remarks>
#if NET_4_0 || MONO_4_0 || NETSTANDARD1_3
[System.Security.SecuritySafeCritical]
#endif
protected override void OnClose()
{
base.OnClose();
try
{
// close syslog
closelog();
}
catch(DllNotFoundException)
{
// Ignore dll not found at this point
}
if (m_handleToIdentity != IntPtr.Zero)
{
// free global ident
Marshal.FreeHGlobal(m_handleToIdentity);
}
}
/// <summary>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </summary>
/// <value><c>true</c></value>
/// <remarks>
/// <para>
/// This appender requires a <see cref="AppenderSkeleton.Layout"/> to be set.
/// </para>
/// </remarks>
override protected bool RequiresLayout
{
get { return true; }
}
#endregion // AppenderSkeleton Implementation
#region Protected Members
/// <summary>
/// Translates a log4net level to a syslog severity.
/// </summary>
/// <param name="level">A log4net level.</param>
/// <returns>A syslog severity.</returns>
/// <remarks>
/// <para>
/// Translates a log4net level to a syslog severity.
/// </para>
/// </remarks>
virtual protected SyslogSeverity GetSeverity(Level level)
{
LevelSeverity levelSeverity = m_levelMapping.Lookup(level) as LevelSeverity;
if (levelSeverity != null)
{
return levelSeverity.Severity;
}
//
// Fallback to sensible default values
//
if (level >= Level.Alert)
{
return SyslogSeverity.Alert;
}
else if (level >= Level.Critical)
{
return SyslogSeverity.Critical;
}
else if (level >= Level.Error)
{
return SyslogSeverity.Error;
}
else if (level >= Level.Warn)
{
return SyslogSeverity.Warning;
}
else if (level >= Level.Notice)
{
return SyslogSeverity.Notice;
}
else if (level >= Level.Info)
{
return SyslogSeverity.Informational;
}
// Default setting
return SyslogSeverity.Debug;
}
#endregion // Protected Members
#region Public Static Members
/// <summary>
/// Generate a syslog priority.
/// </summary>
/// <param name="facility">The syslog facility.</param>
/// <param name="severity">The syslog severity.</param>
/// <returns>A syslog priority.</returns>
private static int GeneratePriority(SyslogFacility facility, SyslogSeverity severity)
{
return ((int)facility * 8) + (int)severity;
}
#endregion // Public Static Members
#region Private Instances Fields
/// <summary>
/// The facility. The default facility is <see cref="SyslogFacility.User"/>.
/// </summary>
private SyslogFacility m_facility = SyslogFacility.User;
/// <summary>
/// The message identity
/// </summary>
private string m_identity;
/// <summary>
/// Marshaled handle to the identity string. We have to hold on to the
/// string as the <c>openlog</c> and <c>syslog</c> APIs just hold the
/// pointer to the ident and dereference it for each log message.
/// </summary>
private IntPtr m_handleToIdentity = IntPtr.Zero;
/// <summary>
/// Mapping from level object to syslog severity
/// </summary>
private LevelMapping m_levelMapping = new LevelMapping();
#endregion // Private Instances Fields
#region External Members
/// <summary>
/// Open connection to system logger.
/// </summary>
[DllImport("libc")]
private static extern void openlog(IntPtr ident, int option, SyslogFacility facility);
/// <summary>
/// Generate a log message.
/// </summary>
/// <remarks>
/// <para>
/// The libc syslog method takes a format string and a variable argument list similar
/// to the classic printf function. As this type of vararg list is not supported
/// by C# we need to specify the arguments explicitly. Here we have specified the
/// format string with a single message argument. The caller must set the format
/// string to <c>"%s"</c>.
/// </para>
/// </remarks>
[DllImport("libc", CharSet=CharSet.Ansi, CallingConvention=CallingConvention.Cdecl)]
private static extern void syslog(int priority, string format, string message);
/// <summary>
/// Close descriptor used to write to system logger.
/// </summary>
[DllImport("libc")]
private static extern void closelog();
#endregion // External Members
#region LevelSeverity LevelMapping Entry
/// <summary>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </summary>
/// <remarks>
/// <para>
/// A class to act as a mapping between the level that a logging call is made at and
/// the syslog severity that is should be logged at.
/// </para>
/// </remarks>
public class LevelSeverity : LevelMappingEntry
{
private SyslogSeverity m_severity;
/// <summary>
/// The mapped syslog severity for the specified level
/// </summary>
/// <remarks>
/// <para>
/// Required property.
/// The mapped syslog severity for the specified level
/// </para>
/// </remarks>
public SyslogSeverity Severity
{
get { return m_severity; }
set { m_severity = value; }
}
}
#endregion // LevelSeverity LevelMapping Entry
}
}
#endif
| |
// 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 gagvr = Google.Ads.GoogleAds.V8.Resources;
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V8.Resources
{
/// <summary>Resource name for the <c>Campaign</c> resource.</summary>
public sealed partial class CampaignName : gax::IResourceName, sys::IEquatable<CampaignName>
{
/// <summary>The possible contents of <see cref="CampaignName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>A resource name with pattern <c>customers/{customer_id}/campaigns/{campaign_id}</c>.</summary>
CustomerCampaign = 1,
}
private static gax::PathTemplate s_customerCampaign = new gax::PathTemplate("customers/{customer_id}/campaigns/{campaign_id}");
/// <summary>Creates a <see cref="CampaignName"/> 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="CampaignName"/> containing the provided <paramref name="unparsedResourceName"/>
/// .
/// </returns>
public static CampaignName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignName"/> with the pattern <c>customers/{customer_id}/campaigns/{campaign_id}</c>
/// .
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignName"/> constructed from the provided ids.</returns>
public static CampaignName FromCustomerCampaign(string customerId, string campaignId) =>
new CampaignName(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignName"/> with pattern
/// <c>customers/{customer_id}/campaigns/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignName"/> with pattern
/// <c>customers/{customer_id}/campaigns/{campaign_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId) => FormatCustomerCampaign(customerId, campaignId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignName"/> with pattern
/// <c>customers/{customer_id}/campaigns/{campaign_id}</c>.
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignName"/> with pattern
/// <c>customers/{customer_id}/campaigns/{campaign_id}</c>.
/// </returns>
public static string FormatCustomerCampaign(string customerId, string campaignId) =>
s_customerCampaign.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)));
/// <summary>Parses the given resource name string into a new <see cref="CampaignName"/> instance.</summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaigns/{campaign_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="campaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignName"/> if successful.</returns>
public static CampaignName Parse(string campaignName) => Parse(campaignName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignName"/> 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>customers/{customer_id}/campaigns/{campaign_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignName">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="CampaignName"/> if successful.</returns>
public static CampaignName Parse(string campaignName, bool allowUnparsed) =>
TryParse(campaignName, allowUnparsed, out CampaignName 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="CampaignName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>customers/{customer_id}/campaigns/{campaign_id}</c></description></item>
/// </list>
/// </remarks>
/// <param name="campaignName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignName"/>, 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 campaignName, out CampaignName result) => TryParse(campaignName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignName"/> 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>customers/{customer_id}/campaigns/{campaign_id}</c></description></item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignName">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="CampaignName"/>, 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 campaignName, bool allowUnparsed, out CampaignName result)
{
gax::GaxPreconditions.CheckNotNull(campaignName, nameof(campaignName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaign.TryParseName(campaignName, out resourceName))
{
result = FromCustomerCampaign(resourceName[0], resourceName[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private CampaignName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/campaigns/{campaign_id}</c>
/// </summary>
/// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="campaignId">The <c>Campaign</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignName(string customerId, string campaignId) : this(ResourceNameType.CustomerCampaign, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))
{
}
/// <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>Campaign</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CampaignId { get; }
/// <summary>
/// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string CustomerId { 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.CustomerCampaign: return s_customerCampaign.Expand(CustomerId, CampaignId);
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 CampaignName);
/// <inheritdoc/>
public bool Equals(CampaignName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignName a, CampaignName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignName a, CampaignName b) => !(a == b);
}
public partial class Campaign
{
/// <summary>
/// <see cref="gagvr::CampaignName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CampaignName ResourceNameAsCampaignName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::CampaignName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CampaignName"/>-typed view over the <see cref="BaseCampaign"/> resource name property.
/// </summary>
internal CampaignName BaseCampaignAsCampaignName
{
get => string.IsNullOrEmpty(BaseCampaign) ? null : gagvr::CampaignName.Parse(BaseCampaign, allowUnparsed: true);
set => BaseCampaign = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="gagvr::CampaignName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
internal CampaignName CampaignName
{
get => string.IsNullOrEmpty(Name) ? null : gagvr::CampaignName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignLabelName"/>-typed view over the <see cref="Labels"/> resource name property.
/// </summary>
internal gax::ResourceNameList<CampaignLabelName> LabelsAsCampaignLabelNames
{
get => new gax::ResourceNameList<CampaignLabelName>(Labels, s => string.IsNullOrEmpty(s) ? null : CampaignLabelName.Parse(s, allowUnparsed: true));
}
/// <summary>
/// <see cref="CampaignBudgetName"/>-typed view over the <see cref="CampaignBudget"/> resource name property.
/// </summary>
internal CampaignBudgetName CampaignBudgetAsCampaignBudgetName
{
get => string.IsNullOrEmpty(CampaignBudget) ? null : CampaignBudgetName.Parse(CampaignBudget, allowUnparsed: true);
set => CampaignBudget = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="BiddingStrategyName"/>-typed view over the <see cref="BiddingStrategy"/> resource name property.
/// </summary>
internal BiddingStrategyName BiddingStrategyAsBiddingStrategyName
{
get => string.IsNullOrEmpty(BiddingStrategy) ? null : BiddingStrategyName.Parse(BiddingStrategy, allowUnparsed: true);
set => BiddingStrategy = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="AccessibleBiddingStrategyName"/>-typed view over the <see cref="AccessibleBiddingStrategy"/>
/// resource name property.
/// </summary>
internal AccessibleBiddingStrategyName AccessibleBiddingStrategyAsAccessibleBiddingStrategyName
{
get => string.IsNullOrEmpty(AccessibleBiddingStrategy) ? null : AccessibleBiddingStrategyName.Parse(AccessibleBiddingStrategy, allowUnparsed: true);
set => AccessibleBiddingStrategy = value?.ToString() ?? "";
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans;
using Orleans.Configuration;
using Orleans.Runtime;
using Orleans.Runtime.Services;
using Orleans.Timers;
using UnitTests.GrainInterfaces;
#pragma warning disable 612,618
namespace UnitTests.Grains
{
// NOTE: if you make any changes here, copy them to ReminderTestCopyGrain
public class ReminderTestGrain2 : Grain, IReminderTestGrain2, IRemindable
{
private readonly IReminderTable reminderTable;
private readonly IReminderRegistry unvalidatedReminderRegistry;
Dictionary<string, IGrainReminder> allReminders;
Dictionary<string, long> sequence;
private TimeSpan period;
private static long aCCURACY = 50 * TimeSpan.TicksPerMillisecond; // when we use ticks to compute sequence numbers, we might get wrong results as timeouts don't happen with precision of ticks ... we keep this as a leeway
private IOptions<ReminderOptions> reminderOptions;
private ILogger logger;
private string myId; // used to distinguish during debugging between multiple activations of the same grain
private string filePrefix;
public ReminderTestGrain2(IServiceProvider services, IReminderTable reminderTable, ILoggerFactory loggerFactory)
{
this.reminderTable = reminderTable;
this.unvalidatedReminderRegistry = new UnvalidatedReminderRegistry(services);
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
this.reminderOptions = services.GetService<IOptions<ReminderOptions>>();
}
public override Task OnActivateAsync()
{
this.myId = this.Data.ActivationId.ToString();// new Random().Next();
this.allReminders = new Dictionary<string, IGrainReminder>();
this.sequence = new Dictionary<string, long>();
this.period = GetDefaultPeriod(this.logger);
this.logger.Info("OnActivateAsync.");
this.filePrefix = "g" + this.GrainId.ToString().Replace('/', '_') + "_";
return GetMissingReminders();
}
public override Task OnDeactivateAsync()
{
this.logger.Info("OnDeactivateAsync");
return Task.CompletedTask;
}
public async Task<IGrainReminder> StartReminder(string reminderName, TimeSpan? p = null, bool validate = false)
{
TimeSpan usePeriod = p ?? this.period;
this.logger.Info("Starting reminder {0}.", reminderName);
TimeSpan dueTime;
if (reminderOptions.Value.MinimumReminderPeriod < TimeSpan.FromSeconds(2))
dueTime = TimeSpan.FromSeconds(2) - reminderOptions.Value.MinimumReminderPeriod;
else dueTime = usePeriod - TimeSpan.FromSeconds(2);
IGrainReminder r;
if (validate)
r = await RegisterOrUpdateReminder(reminderName, dueTime, usePeriod);
else
r = await this.unvalidatedReminderRegistry.RegisterOrUpdateReminder(reminderName, dueTime, usePeriod);
this.allReminders[reminderName] = r;
this.sequence[reminderName] = 0;
string fileName = GetFileName(reminderName);
File.Delete(fileName); // if successfully started, then remove any old data
this.logger.Info("Started reminder {0}", r);
return r;
}
public Task ReceiveReminder(string reminderName, TickStatus status)
{
// it can happen that due to failure, when a new activation is created,
// it doesn't know which reminders were registered against the grain
// hence, this activation may receive a reminder that it didn't register itself, but
// the previous activation (incarnation of the grain) registered... so, play it safe
if (!this.sequence.ContainsKey(reminderName))
{
// allReminders.Add(reminderName, r); // not using allReminders at the moment
//counters.Add(reminderName, 0);
this.sequence.Add(reminderName, 0); // we'll get upto date to the latest sequence number while processing this tick
}
// calculating tick sequence number
// we do all arithmetics on DateTime by converting into long because we dont have divide operation on DateTime
// using dateTime.Ticks is not accurate as between two invocations of ReceiveReminder(), there maybe < period.Ticks
// if # of ticks between two consecutive ReceiveReminder() is larger than period.Ticks, everything is fine... the problem is when its less
// thus, we reduce our accuracy by ACCURACY ... here, we are preparing all used variables for the given accuracy
long now = status.CurrentTickTime.Ticks / aCCURACY; //DateTime.UtcNow.Ticks / ACCURACY;
long first = status.FirstTickTime.Ticks / aCCURACY;
long per = status.Period.Ticks / aCCURACY;
long sequenceNumber = 1 + ((now - first) / per);
// end of calculating tick sequence number
// do switch-ing here
if (sequenceNumber < this.sequence[reminderName])
{
this.logger.Info("ReceiveReminder: {0} Incorrect tick {1} vs. {2} with status {3}.", reminderName, this.sequence[reminderName], sequenceNumber, status);
return Task.CompletedTask;
}
this.sequence[reminderName] = sequenceNumber;
this.logger.Info("ReceiveReminder: {0} Sequence # {1} with status {2}.", reminderName, this.sequence[reminderName], status);
string fileName = GetFileName(reminderName);
string counterValue = this.sequence[reminderName].ToString(CultureInfo.InvariantCulture);
File.WriteAllText(fileName, counterValue);
return Task.CompletedTask;
}
public async Task StopReminder(string reminderName)
{
this.logger.Info("Stopping reminder {0}.", reminderName);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
//return UnregisterReminder(allReminders[reminderName]);
IGrainReminder reminder;
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
// during failures, there may be reminders registered by an earlier activation that we dont have cached locally
// therefore, we need to update our local cache
await GetMissingReminders();
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
//var reminders = await this.GetRemindersList();
throw new OrleansException(string.Format(
"Could not find reminder {0} in grain {1}", reminderName, this.IdentityString));
}
}
}
private async Task GetMissingReminders()
{
List<IGrainReminder> reminders = await base.GetReminders();
this.logger.Info("Got missing reminders {0}", Utils.EnumerableToString(reminders));
foreach (IGrainReminder l in reminders)
{
if (!this.allReminders.ContainsKey(l.ReminderName))
{
this.allReminders.Add(l.ReminderName, l);
}
}
}
public async Task StopReminder(IGrainReminder reminder)
{
this.logger.Info("Stopping reminder (using ref) {0}.", reminder);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
await UnregisterReminder(reminder);
}
public Task<TimeSpan> GetReminderPeriod(string reminderName)
{
return Task.FromResult(this.period);
}
public Task<long> GetCounter(string name)
{
string fileName = GetFileName(name);
string data = File.ReadAllText(fileName);
long counterValue = long.Parse(data);
return Task.FromResult(counterValue);
}
public Task<IGrainReminder> GetReminderObject(string reminderName)
{
return base.GetReminder(reminderName);
}
public async Task<List<IGrainReminder>> GetRemindersList()
{
return await base.GetReminders();
}
private string GetFileName(string reminderName)
{
return string.Format("{0}{1}", this.filePrefix, reminderName);
}
public static TimeSpan GetDefaultPeriod(ILogger log)
{
int period = 12; // Seconds
var reminderPeriod = TimeSpan.FromSeconds(period);
log.Info("Using reminder period of {0} in ReminderTestGrain", reminderPeriod);
return reminderPeriod;
}
public async Task EraseReminderTable()
{
await this.reminderTable.TestOnlyClearTable();
}
}
// NOTE: do not make changes here ... this is a copy of ReminderTestGrain
// changes to make when copying:
// 1. rename logger to ReminderCopyGrain
// 2. filePrefix should start with "gc", instead of "g"
public class ReminderTestCopyGrain : Grain, IReminderTestCopyGrain, IRemindable
{
private readonly IReminderRegistry unvalidatedReminderRegistry;
Dictionary<string, IGrainReminder> allReminders;
Dictionary<string, long> sequence;
private TimeSpan period;
private static long aCCURACY = 50 * TimeSpan.TicksPerMillisecond; // when we use ticks to compute sequence numbers, we might get wrong results as timeouts don't happen with precision of ticks ... we keep this as a leeway
private ILogger logger;
private long myId; // used to distinguish during debugging between multiple activations of the same grain
private string filePrefix;
public ReminderTestCopyGrain(IServiceProvider services, ILoggerFactory loggerFactory)
{
this.unvalidatedReminderRegistry = new UnvalidatedReminderRegistry(services); ;
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override async Task OnActivateAsync()
{
this.myId = new Random().Next();
this.allReminders = new Dictionary<string, IGrainReminder>();
this.sequence = new Dictionary<string, long>();
this.period = ReminderTestGrain2.GetDefaultPeriod(this.logger);
this.logger.Info("OnActivateAsync.");
this.filePrefix = "gc" + this.GrainId.Key + "_";
await GetMissingReminders();
}
public override Task OnDeactivateAsync()
{
this.logger.Info("OnDeactivateAsync.");
return Task.CompletedTask;
}
public async Task<IGrainReminder> StartReminder(string reminderName, TimeSpan? p = null, bool validate = false)
{
TimeSpan usePeriod = p ?? this.period;
this.logger.Info("Starting reminder {0} for {1}", reminderName, this.GrainId);
IGrainReminder r;
if (validate)
r = await RegisterOrUpdateReminder(reminderName, /*TimeSpan.FromSeconds(3)*/usePeriod - TimeSpan.FromSeconds(2), usePeriod);
else
r = await this.unvalidatedReminderRegistry.RegisterOrUpdateReminder(
reminderName,
usePeriod - TimeSpan.FromSeconds(2),
usePeriod);
if (this.allReminders.ContainsKey(reminderName))
{
this.allReminders[reminderName] = r;
this.sequence[reminderName] = 0;
}
else
{
this.allReminders.Add(reminderName, r);
this.sequence.Add(reminderName, 0);
}
File.Delete(GetFileName(reminderName)); // if successfully started, then remove any old data
this.logger.Info("Started reminder {0}.", r);
return r;
}
public Task ReceiveReminder(string reminderName, TickStatus status)
{
// it can happen that due to failure, when a new activation is created,
// it doesn't know which reminders were registered against the grain
// hence, this activation may receive a reminder that it didn't register itself, but
// the previous activation (incarnation of the grain) registered... so, play it safe
if (!this.sequence.ContainsKey(reminderName))
{
// allReminders.Add(reminderName, r); // not using allReminders at the moment
//counters.Add(reminderName, 0);
this.sequence.Add(reminderName, 0); // we'll get upto date to the latest sequence number while processing this tick
}
// calculating tick sequence number
// we do all arithmetics on DateTime by converting into long because we dont have divide operation on DateTime
// using dateTime.Ticks is not accurate as between two invocations of ReceiveReminder(), there maybe < period.Ticks
// if # of ticks between two consecutive ReceiveReminder() is larger than period.Ticks, everything is fine... the problem is when its less
// thus, we reduce our accuracy by ACCURACY ... here, we are preparing all used variables for the given accuracy
long now = status.CurrentTickTime.Ticks / aCCURACY; //DateTime.UtcNow.Ticks / ACCURACY;
long first = status.FirstTickTime.Ticks / aCCURACY;
long per = status.Period.Ticks / aCCURACY;
long sequenceNumber = 1 + ((now - first) / per);
// end of calculating tick sequence number
// do switch-ing here
if (sequenceNumber < this.sequence[reminderName])
{
this.logger.Info("{0} Incorrect tick {1} vs. {2} with status {3}.", reminderName, this.sequence[reminderName], sequenceNumber, status);
return Task.CompletedTask;
}
this.sequence[reminderName] = sequenceNumber;
this.logger.Info("{0} Sequence # {1} with status {2}.", reminderName, this.sequence[reminderName], status);
File.WriteAllText(GetFileName(reminderName), this.sequence[reminderName].ToString());
return Task.CompletedTask;
}
public async Task StopReminder(string reminderName)
{
this.logger.Info("Stopping reminder {0}.", reminderName);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
//return UnregisterReminder(allReminders[reminderName]);
IGrainReminder reminder;
if (this.allReminders.TryGetValue(reminderName, out reminder))
{
await UnregisterReminder(reminder);
}
else
{
// during failures, there may be reminders registered by an earlier activation that we dont have cached locally
// therefore, we need to update our local cache
await GetMissingReminders();
await UnregisterReminder(this.allReminders[reminderName]);
}
}
private async Task GetMissingReminders()
{
List<IGrainReminder> reminders = await base.GetReminders();
foreach (IGrainReminder l in reminders)
{
if (!this.allReminders.ContainsKey(l.ReminderName))
{
this.allReminders.Add(l.ReminderName, l);
}
}
}
public async Task StopReminder(IGrainReminder reminder)
{
this.logger.Info("Stopping reminder (using ref) {0}.", reminder);
// we dont reset counter as we want the test methods to be able to read it even after stopping the reminder
await UnregisterReminder(reminder);
}
public Task<TimeSpan> GetReminderPeriod(string reminderName)
{
return Task.FromResult(this.period);
}
public Task<long> GetCounter(string name)
{
return Task.FromResult(long.Parse(File.ReadAllText(GetFileName(name))));
}
public async Task<IGrainReminder> GetReminderObject(string reminderName)
{
return await base.GetReminder(reminderName);
}
public async Task<List<IGrainReminder>> GetRemindersList()
{
return await base.GetReminders();
}
private string GetFileName(string reminderName)
{
return string.Format("{0}{1}", this.filePrefix, reminderName);
}
}
public class WrongReminderGrain : Grain, IReminderGrainWrong
{
private ILogger logger;
public WrongReminderGrain(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}");
}
public override Task OnActivateAsync()
{
this.logger.Info("OnActivateAsync.");
return Task.CompletedTask;
}
public async Task<bool> StartReminder(string reminderName)
{
this.logger.Info("Starting reminder {0}.", reminderName);
IGrainReminder r = await RegisterOrUpdateReminder(reminderName, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(3));
this.logger.Info("Started reminder {0}. It shouldn't have succeeded!", r);
return true;
}
}
internal class UnvalidatedReminderRegistry : GrainServiceClient<IReminderService>, IReminderRegistry
{
public UnvalidatedReminderRegistry(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
public Task<IGrainReminder> RegisterOrUpdateReminder(string reminderName, TimeSpan dueTime, TimeSpan period)
{
return this.GrainService.RegisterOrUpdateReminder(this.CallingGrainReference, reminderName, dueTime, period);
}
public Task UnregisterReminder(IGrainReminder reminder)
{
return this.GrainService.UnregisterReminder(reminder);
}
public Task<IGrainReminder> GetReminder(string reminderName)
{
return this.GrainService.GetReminder(this.CallingGrainReference, reminderName);
}
public Task<List<IGrainReminder>> GetReminders()
{
return this.GrainService.GetReminders(this.CallingGrainReference);
}
}
}
#pragma warning restore 612,618
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Axiom.Core;
using Tao.DevIl;
namespace Axiom.Media {
/// <summary>
/// Base DevIL (OpenIL) implementation for loading images.
/// </summary>
public class ILImageCodec : ImageCodec {
#region Fields
/// <summary>
/// Flag used to ensure DevIL gets initialized once.
/// </summary>
protected static bool isInitialized = false;
protected static bool isILUInitialized = false;
protected string type;
protected int ilType;
#endregion
#region Constructor
public ILImageCodec(string type, int ilType) {
this.type = type;
this.ilType = ilType;
InitializeIL();
}
#endregion Constructor
#region ImageCodec Implementation
public override void Encode(Stream input, Stream output, params object[] args) {
throw new NotImplementedException("Encode to memory not implemented");
}
// TODO: Fix this to be like Ogre
public override void EncodeToFile(Stream input, string fileName, object codecData) {
int imageID;
// create and bind a new image
Il.ilGenImages(1, out imageID);
Il.ilBindImage(imageID);
byte[] buffer = new byte[input.Length];
input.Read(buffer, 0, buffer.Length);
ImageData data = (ImageData)codecData;
ILFormat ilfmt = ILUtil.ConvertToILFormat(data.format);
// stuff the data into the image
Il.ilTexImage(data.width, data.height, 1, (byte)ilfmt.channels, ilfmt.format, ilfmt.type, buffer);
if (data.flip) {
// flip the image
Ilu.iluFlipImage();
}
// save the image to file
Il.ilSaveImage(fileName);
// delete the image
Il.ilDeleteImages(1, ref imageID);
}
public override object Decode(Stream input, Stream output, params object[] args) {
ImageData data = new ImageData();
int imageID;
int format, bytesPerPixel, imageType;
// create and bind a new image
Il.ilGenImages(1, out imageID);
Il.ilBindImage(imageID);
// Put it right side up
Il.ilEnable(Il.IL_ORIGIN_SET);
Il.ilSetInteger(Il.IL_ORIGIN_MODE, Il.IL_ORIGIN_UPPER_LEFT);
// Keep DXTC(compressed) data if present
Il.ilSetInteger(Il.IL_KEEP_DXTC_DATA, Il.IL_TRUE);
// create a temp buffer and write the stream into it
byte[] buffer = new byte[input.Length];
input.Read(buffer, 0, buffer.Length);
// load the data into DevIL
Il.ilLoadL(this.ILType, buffer, buffer.Length);
// check for an error
int ilError = Il.ilGetError();
if(ilError != Il.IL_NO_ERROR) {
throw new AxiomException("Error while decoding image data: '{0}'", Ilu.iluErrorString(ilError));
}
format = Il.ilGetInteger(Il.IL_IMAGE_FORMAT);
imageType = Il.ilGetInteger(Il.IL_IMAGE_TYPE);
//bytesPerPixel = Math.Max(Il.ilGetInteger(Il.IL_IMAGE_BPC),
// Il.ilGetInteger(Il.IL_IMAGE_BYTES_PER_PIXEL));
// Convert image if ImageType is incompatible with us (double or long)
if (imageType != Il.IL_BYTE && imageType != Il.IL_UNSIGNED_BYTE &&
imageType != Il.IL_FLOAT &&
imageType != Il.IL_UNSIGNED_SHORT && imageType != Il.IL_SHORT) {
Il.ilConvertImage(format, Il.IL_FLOAT);
imageType = Il.IL_FLOAT;
}
// Converted paletted images
if (format == Il.IL_COLOUR_INDEX) {
Il.ilConvertImage(Il.IL_BGRA, Il.IL_UNSIGNED_BYTE);
format = Il.IL_BGRA;
imageType = Il.IL_UNSIGNED_BYTE;
}
bytesPerPixel = Il.ilGetInteger(Il.IL_IMAGE_BYTES_PER_PIXEL);
// populate the image data
data.format = ILUtil.ConvertFromILFormat(format, imageType);
data.width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
data.height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
data.depth = Il.ilGetInteger(Il.IL_IMAGE_DEPTH);
data.numMipMaps = Il.ilGetInteger(Il.IL_NUM_MIPMAPS);
data.flags = 0;
if (data.format == PixelFormat.Unknown) {
Il.ilDeleteImages(1, ref imageID);
throw new AxiomException("Unsupported DevIL format: ImageFormat = {0:x} ImageType = {1:x}", format, imageType);
}
// Check for cubemap
// int cubeflags = Il.ilGetInteger(Il.IL_IMAGE_CUBEFLAGS);
int numFaces = Il.ilGetInteger(Il.IL_NUM_IMAGES) + 1;
if (numFaces == 6)
data.flags |= ImageFlags.CubeMap;
else
numFaces = 1; // Support only 1 or 6 face images for now
// Keep DXT data (if present at all and the GPU supports it)
int dxtFormat = Il.ilGetInteger(Il.IL_DXTC_DATA_FORMAT);
if (dxtFormat != Il.IL_DXT_NO_COMP &&
Root.Instance.RenderSystem.Caps.CheckCap(Axiom.Graphics.Capabilities.TextureCompressionDXT))
{
data.format = ILUtil.ConvertFromILFormat(dxtFormat, imageType);
data.flags |= ImageFlags.Compressed;
// Validate that this devil version saves DXT mipmaps
if (data.numMipMaps > 0)
{
Il.ilBindImage(imageID);
Il.ilActiveMipmap(1);
if (Il.ilGetInteger(Il.IL_DXTC_DATA_FORMAT) != dxtFormat)
{
data.numMipMaps = 0;
LogManager.Instance.Write("Warning: Custom mipmaps for compressed image were ignored because they are not loaded by this DevIL version");
}
}
}
// Calculate total size from number of mipmaps, faces and size
data.size = Image.CalculateSize(data.numMipMaps, numFaces,
data.width, data.height,
data.depth, data.format);
// set up buffer for the decoded data
buffer = new byte[data.size];
// Pin the buffer, so we can use our PixelBox methods on it
GCHandle bufGCHandle = new GCHandle();
bufGCHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
IntPtr bufPtr = bufGCHandle.AddrOfPinnedObject();
int offset = 0;
// Dimensions of current mipmap
int width = data.width;
int height = data.height;
int depth = data.depth;
// Transfer data
for (int mip=0; mip <= data.numMipMaps; ++mip)
{
for (int i = 0; i < numFaces; ++i)
{
Il.ilBindImage(imageID);
if (numFaces > 1)
Il.ilActiveImage(i);
if (data.numMipMaps > 0)
Il.ilActiveMipmap(mip);
/// Size of this face
int imageSize = PixelUtil.GetMemorySize(width, height, depth, data.format);
if ((data.flags & ImageFlags.Compressed) != 0)
{
// Compare DXT size returned by DevIL with our idea of the compressed size
if (imageSize == Il.ilGetDXTCData(IntPtr.Zero, 0, dxtFormat))
{
// Retrieve data from DevIL
byte[] tmpBuffer = new byte[imageSize];
Il.ilGetDXTCData(tmpBuffer, imageSize, dxtFormat);
// Copy the data into our output buffer
Array.Copy(tmpBuffer, 0, buffer, offset, tmpBuffer.Length);
} else {
LogManager.Instance.Write("Warning: compressed image size mismatch, devilsize={0} oursize={1}",
Il.ilGetDXTCData(IntPtr.Zero, 0, dxtFormat), imageSize);
}
}
else
{
/// Retrieve data from DevIL
PixelBox dst = new PixelBox(width, height, depth, data.format, bufPtr);
dst.Offset = offset;
ILUtil.ToAxiom(dst);
}
offset += imageSize;
}
/// Next mip
if (width != 1) width /= 2;
if (height != 1) height /= 2;
if (depth != 1) depth /= 2;
}
// Restore IL state
Il.ilDisable(Il.IL_ORIGIN_SET);
Il.ilDisable(Il.IL_FORMAT_SET);
// we won't be needing this anymore
Il.ilDeleteImages(1, ref imageID);
output.Write(buffer, 0, buffer.Length);
// Free the buffer we allocated for the conversion.
// I used bufPtr to store my data while I converted it.
// I need to free it here. This invalidates bufPtr.
// My data has already been copied to output.
if (bufGCHandle.IsAllocated)
bufGCHandle.Free();
return data;
}
#endregion ImageCodec Implementation
#region Methods
/// <summary>
/// One time DevIL initialization.
/// </summary>
public static void InitializeIL() {
if(!isInitialized) {
// fire it up!
Il.ilInit();
// enable automatic file overwriting
Il.ilEnable(Il.IL_FILE_OVERWRITE);
isInitialized = true;
}
}
public static void InitializeILU() {
if(!isILUInitialized) {
// init Il utils
Ilu.iluInit();
isILUInitialized = true;
}
}
public static bool ReshapeToPowersOf2AndSave(Stream input, int size, string outputFileName)
{
InitializeIL();
InitializeILU();
// load the image
ImageData data = new ImageData();
int imageID;
// create and bind a new image
Il.ilGenImages(1, out imageID);
Il.ilBindImage(imageID);
// create a temp buffer and copy the stream into it
byte[] buffer = new byte[size];
int bytesRead = 0, byteOffset = 0, bytes = buffer.Length;
do {
bytesRead = input.Read(buffer, byteOffset, bytes);
bytes -= bytesRead;
byteOffset += bytesRead;
} while (bytes > 0 && bytesRead > 0);
Il.ilLoadL(Il.IL_TYPE_UNKNOWN, buffer, buffer.Length);
// check errors
int ilError = Il.ilGetError();
if (ilError != Il.IL_NO_ERROR) {
throw new AxiomException("Error while loading image data: '{0}'", Ilu.iluErrorString(ilError));
}
// determine dimensions & compute powers-of-2 reshape if needed
int width = Il.ilGetInteger(Il.IL_IMAGE_WIDTH);
int height = Il.ilGetInteger(Il.IL_IMAGE_HEIGHT);
int newWidth = (int)Math.Pow(2, Math.Floor(Math.Log(width, 2)));
int newHeight = (int)Math.Pow(2, Math.Floor(Math.Log(height, 2)));
if (width != newWidth || height != newHeight) {
// reshape
// set the scale function filter & scale
Ilu.iluImageParameter(Ilu.ILU_FILTER, Ilu.ILU_BILINEAR); // .ILU_SCALE_BSPLINE);
Ilu.iluScale(newWidth, newHeight, 1);
}
// save
Il.ilSetInteger(Il.IL_JPG_QUALITY, 50);
Il.ilSaveImage(outputFileName);
// drop image
Il.ilDeleteImages(1, ref imageID);
return true;
}
#endregion Methods
#region Properties
/// <summary>
/// Implemented by subclasses to return the IL type enum value for this
/// images file type.
/// </summary>
public int ILType {
get {
return ilType;
}
}
public override string Type {
get {
return type;
}
}
#endregion Properties
}
}
| |
using Tibia.Addresses;
namespace Tibia
{
public partial class Version
{
public static void SetVersion850()
{
BattleList.Start = 0x632F30;
BattleList.End = 0x632F30 + 0xA0 * 250;
BattleList.StepCreatures = 0xA0;
BattleList.MaxCreatures = 250;
Client.StartTime = 0x7913F8;
Client.XTeaKey = 0x78BF34;
Client.SocketStruct = 0x78BF08;
Client.RecvPointer = 0x5B05DC;
Client.SendPointer = 0x5B0608;
Client.FrameRatePointer = 0x7900DC;
Client.FrameRateCurrentOffset = 0x60;
Client.FrameRateLimitOffset = 0x58;
Client.MultiClient = 0x506794;
Client.Status = 0x78F598;
Client.SafeMode = 0x78C35C;
Client.FollowMode = Client.SafeMode + 4;
Client.AttackMode = Client.FollowMode + 4;
Client.ActionState = 0x78F5F8;
Client.LastMSGText = 0x791668;
Client.LastMSGAuthor = Client.LastMSGText - 0x28;
Client.StatusbarText = 0x791418;
Client.StatusbarTime = Client.StatusbarText - 4;
Client.ClickId = 0x78F634;
Client.ClickCount = Client.ClickId + 4;
Client.ClickZ = Client.ClickId - 0x68;
Client.SeeId = Client.ClickId + 12;
Client.SeeCount = Client.SeeId + 4;
Client.SeeZ = Client.SeeId - 0x68;
Client.ClickContextMenuItemId = 0x78F640;
Client.ClickContextMenuItemGroundId = 0x78F64C;
Client.ClickContextMenuCreatureId = 0x78F59C;
Client.SeeText = 0;
Client.LoginServerStart = 0x786E70;
Client.StepLoginServer = 112;
Client.DistancePort = 100;
Client.MaxLoginServers = 10;
Client.RSA = 0x5B0610;
Client.LoginCharList = 0x78F54C;
Client.LoginCharListLength = Client.LoginCharList + 4;
Client.LoginSelectedChar = 0x78F548;
Client.GameWindowRectPointer = 0x63E8D4;
Client.GameWindowBar = 0x641C40;
Client.DatPointer = 0x78BF54;
Client.EventTriggerPointer = 0x519770;
Client.DialogPointer = 0x641C3C;
Client.DialogLeft = 0x14;
Client.DialogTop = 0x18;
Client.DialogWidth = 0x1C;
Client.DialogHeight = 0x20;
Client.DialogCaption = 0x50;
Client.LastRcvPacket = 0x7876E8;
Client.DecryptCall = 0x45B845;
Client.LoginAccountNum = 0;
Client.LoginPassword = 0x78F554;
Client.LoginAccount = Client.LoginPassword + 32;
Client.LoginPatch = 0;
Client.LoginPatch2 = 0;
Client.LoginPatchOrig = new byte[] { 0xE8, 0x0D, 0x1D, 0x09, 0x00 };
Client.LoginPatchOrig2 = new byte[] { 0xE8, 0xC8, 0x15, 0x09, 0x00 };
Client.ParserFunc = 0x45B810;
Client.GetNextPacketCall = 0x45B845;
Client.RecvStream = 0x78BF24;
Container.Start = 0x63F388;
Container.StepContainer = 492;
Container.StepSlot = 12;
Container.MaxContainers = 16;
Container.MaxStack = 100;
Container.DistanceIsOpen = 0;
Container.DistanceId = 4;
Container.DistanceName = 16;
Container.DistanceVolume = 48;
Container.DistanceAmount = 56;
Container.DistanceItemId = 60;
Container.DistanceItemCount = 64;
Container.End = Container.Start + (Container.MaxContainers * Container.StepContainer);
ContextMenus.AddContextMenuPtr = 0x451830;
ContextMenus.OnClickContextMenuPtr = 0x44DFD0;
ContextMenus.OnClickContextMenuVf = 0x5B5B98;
ContextMenus.AddSetOutfitContextMenu = 0x452762;
ContextMenus.AddPartyActionContextMenu = 0x4527B3;
ContextMenus.AddCopyNameContextMenu = 0x4527CA;
ContextMenus.AddTradeWithContextMenu = 0x4523D9;
ContextMenus.AddLookContextMenu = 0x45228F;
Creature.DistanceId = 0;
Creature.DistanceType = 3;
Creature.DistanceName = 4;
Creature.DistanceX = 36;
Creature.DistanceY = 40;
Creature.DistanceZ = 44;
Creature.DistanceScreenOffsetHoriz = 48;
Creature.DistanceScreenOffsetVert = 52;
Creature.DistanceIsWalking = 76;
Creature.DistanceWalkSpeed = 140;
Creature.DistanceDirection = 80;
Creature.DistanceIsVisible = 144;
Creature.DistanceBlackSquare = 132;
Creature.DistanceLight = 120;
Creature.DistanceLightColor = 124;
Creature.DistanceHPBar = 136;
Creature.DistanceSkull = 148;
Creature.DistanceParty = 152;
Creature.DistanceOutfit = 96;
Creature.DistanceColorHead = 100;
Creature.DistanceColorBody = 104;
Creature.DistanceColorLegs = 108;
Creature.DistanceColorFeet = 112;
Creature.DistanceAddon = 116;
DatItem.StepItems = 0x50;
DatItem.Width = 0;
DatItem.Height = 4;
DatItem.MaxSizeInPixels = 8;
DatItem.Layers = 12;
DatItem.PatternX = 16;
DatItem.PatternY = 20;
DatItem.PatternDepth = 24;
DatItem.Phase = 28;
DatItem.Sprite = 32;
DatItem.Flags = 36;
DatItem.CanLookAt = 40;
DatItem.WalkSpeed = 44;
DatItem.TextLimit = 48;
DatItem.LightRadius = 52;
DatItem.LightColor = 56;
DatItem.ShiftX = 60;
DatItem.ShiftY = 64;
DatItem.WalkHeight = 68;
DatItem.Automap = 72;
DatItem.LensHelp = 76;
DrawItem.DrawItemFunc = 0x4B0BC0;
DrawSkin.DrawSkinFunc = 0x4B4860;
Hotkey.SendAutomaticallyStart = 0x78C558;
Hotkey.SendAutomaticallyStep = 0x01;
Hotkey.TextStart = 0x78C580;
Hotkey.TextStep = 0x100;
Hotkey.ObjectStart = 0x78C4C8;
Hotkey.ObjectStep = 0x04;
Hotkey.ObjectUseTypeStart = 0x78C3A8;
Hotkey.ObjectUseTypeStep = 0x04;
Hotkey.MaxHotkeys = 36;
Map.MapPointer = 0x646790;
Map.StepTile = 168;
Map.StepTileObject = 12;
Map.DistanceTileObjectCount = 0;
Map.DistanceTileObjects = 4;
Map.DistanceObjectId = 0;
Map.DistanceObjectData = 4;
Map.DistanceObjectDataEx = 8;
Map.MaxTileObjects = 10;
Map.MaxX = 18;
Map.MaxY = 14;
Map.MaxZ = 8;
Map.MaxTiles = 2016;
Map.ZAxisDefault = 7;
Map.NameSpy1 = 0x4ED239;
Map.NameSpy2 = 0x4ED243;
Map.NameSpy1Default = 19061;
Map.NameSpy2Default = 16501;
Map.LevelSpy1 = 0x4EF0EA;
Map.LevelSpy2 = 0x4EF1EF;
Map.LevelSpy3 = 0x4EF270;
Map.LevelSpyPtr = 0x63E8D4;
Map.LevelSpyAdd1 = 28;
Map.LevelSpyAdd2 = 0x2A88;
Map.LevelSpyDefault = new byte[] { 0x89, 0x86, 0x88, 0x2A, 0x00, 0x00 };
Map.RevealInvisible1 = 0x45F6F3;
Map.RevealInvisible2 = 0x4EC505;
Map.FullLightNop = 0x4E59C9;
Map.FullLightAdr = 0x4E59CC;
Map.FullLightNopDefault = new byte[] { 0x7E, 0x05 };
Map.FullLightNopEdited = new byte[] { 0x90, 0x90 };
Map.FullLightAdrDefault = 0x80;
Map.FullLightAdrEdited = 0xFF;
Player.Experience = 0x632EC4;
Player.Flags = Player.Experience - 108;
Player.Id = Player.Experience + 12;
Player.Health = Player.Experience + 8;
Player.HealthMax = Player.Experience + 4;
Player.Level = Player.Experience - 4;
Player.MagicLevel = Player.Experience - 8;
Player.LevelPercent = Player.Experience - 12;
Player.MagicLevelPercent = Player.Experience - 16;
Player.Mana = Player.Experience - 20;
Player.ManaMax = Player.Experience - 24;
Player.Soul = Player.Experience - 28;
Player.Stamina = Player.Experience - 32;
Player.Capacity = Player.Experience - 36;
Player.FistPercent = 0x632E5C;
Player.ClubPercent = Player.FistPercent + 4;
Player.SwordPercent = Player.FistPercent + 8;
Player.AxePercent = Player.FistPercent + 12;
Player.DistancePercent = Player.FistPercent + 16;
Player.ShieldingPercent = Player.FistPercent + 20;
Player.FishingPercent = Player.FistPercent + 24;
Player.Fist = Player.FistPercent + 28;
Player.Club = Player.FistPercent + 32;
Player.Sword = Player.FistPercent + 36;
Player.Axe = Player.FistPercent + 40;
Player.Distance = Player.FistPercent + 44;
Player.Shielding = Player.FistPercent + 48;
Player.Fishing = Player.FistPercent + 52;
Player.SlotHead = 0x63F310;
Player.SlotNeck = Player.SlotHead + 12;
Player.SlotBackpack = Player.SlotHead + 24;
Player.SlotArmor = Player.SlotHead + 36;
Player.SlotRight = Player.SlotHead + 48;
Player.SlotLeft = Player.SlotHead + 60;
Player.SlotLegs = Player.SlotHead + 72;
Player.SlotFeet = Player.SlotHead + 84;
Player.SlotRing = Player.SlotHead + 96;
Player.SlotAmmo = Player.SlotHead + 108;
Player.MaxSlots = 10;
Player.DistanceSlotCount = 4;
Player.CurrentTileToGo = 0x632ED8;
Player.TilesToGo = 0x632EDC;
Player.GoToX = Player.Experience + 80;
Player.GoToY = Player.GoToX - 4;
Player.GoToZ = Player.GoToX - 8;
Player.RedSquare = 0x632E9C;
Player.GreenSquare = Player.RedSquare - 4;
Player.WhiteSquare = Player.GreenSquare - 8;
Player.AccessN = 0;
Player.AccessS = 0;
Player.TargetId = Player.RedSquare;
Player.TargetBattlelistId = Player.TargetId - 8;
Player.TargetBattlelistType = Player.TargetId - 5;
Player.TargetType = Player.TargetId + 3;
Player.Z = 0x641C78;
TextDisplay.PrintName = 0x4F0221;
TextDisplay.PrintFPS = 0x459728;
TextDisplay.ShowFPS = 0x630B74;
TextDisplay.PrintTextFunc = 0x4B0000;
TextDisplay.NopFPS = 0x459664;
Vip.Start = 0x630BF0;
Vip.StepPlayers = 0x2C;
Vip.MaxPlayers = 200;
Vip.DistanceId = 0;
Vip.DistanceName = 4;
Vip.DistanceStatus = 34;
Vip.DistanceIcon = 40;
Vip.End = Vip.Start + (Vip.StepPlayers * Vip.MaxPlayers);
}
}
}
| |
using System;
using System.Collections;
namespace RemoteWindowsAgent
{
public class QueryClause
{
private string AttributeDisplay;
private string Attribute;
private string OperatorDisplay;
private string Operator;
private string ValueDisplay;
private string Value;
private string AttributeType;
public const string QUERY_BOOLEAN_OP_AND = "AND";
public const string QUERY_BOOLEAN_OP_OR = "OR";
public QueryClause(string AttributeDisplay, string Attribute,
string OperatorDisplay, string Operator,
string ValueDisplay, string Value, string AttributeType)
{
this.AttributeDisplay = AttributeDisplay;
this.Attribute = Attribute;
this.OperatorDisplay = OperatorDisplay;
this.Operator = Operator;
this.ValueDisplay = ValueDisplay;
this.Value = Value;
this.AttributeType = AttributeType;
}
public QueryClause(string attribute, string op, string val, string attributeType)
{
this.AttributeDisplay = attribute;
this.Attribute = attribute;
this.OperatorDisplay = op;
this.Operator = op;
this.ValueDisplay = val;
this.Value = val;
this.AttributeType = attributeType;
}
public string GetAttributeDisplay()
{
return AttributeDisplay;
}
public void SetAttributeDisplay(string strValue)
{
AttributeDisplay = strValue;
}
public string GetAttribute()
{
return Attribute;
}
public void SetAttribute(string strValue)
{
Attribute = strValue;
}
public string GetOperatorDisplay()
{
return OperatorDisplay;
}
public void SetOperatorDisplay(string strValue)
{
OperatorDisplay = strValue;
}
public string GetOperator()
{
return Operator;
}
public void SetOperator(string strValue)
{
Operator = strValue;
}
public string GetValueDisplay()
{
return ValueDisplay;
}
public void SetValueDisplay(string strValue)
{
ValueDisplay = strValue;
}
public string GetValue()
{
return Value;
}
public void SetValue(string strValue)
{
Value = strValue;
}
public string GetAttributeType()
{
return AttributeType;
}
public void SetAttributeType(string strValue)
{
AttributeType = strValue;
}
public static void PrepareQueryRequest(
string objectType,
IList arFieldList,
IList arQueryList,
string strAttribute,
int maxrows,
bool bPicklist,
string strBooleanOp,
bool OnlyUniversalGroups, // applies to AD groups only
ref ReturnValues rvsQual,
ref ReturnValues rvsAttr
)
{
ReturnValue rvtemp = new ReturnValue(0);
// Pass in object type
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_OBJECT_TYPE);
rvtemp.SetValue(objectType);
rvsAttr.AddReturnValue(rvtemp);
if (OnlyUniversalGroups) // applies to AD groups only
{
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_GROUP_TYPE);
rvtemp.SetValue(((int)ADGroupScopeEnum.Universal).ToString());
rvsAttr.AddReturnValue(rvtemp);
}
// Load optional secondary attributes to be returned
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FIELDLIST);
rvtemp.SetList(arFieldList);
rvsAttr.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_PRIMARYATTRIBUTE);
rvtemp.SetValue(strAttribute);
rvsAttr.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FILTERBOOLEANOP);
rvtemp.SetValue(strBooleanOp);
rvsAttr.AddReturnValue(rvtemp);
// Load picklist mode
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_PICKLISTMODE);
rvtemp.SetType(ReturnValueTypes.BOOLEAN);
if (bPicklist)
{
rvtemp.SetValue("true");
}
else
{
rvtemp.SetValue("false");
}
rvsAttr.AddReturnValue(rvtemp);
// Load query filter
IList arFieldName = new ArrayList();
IList arOperator = new ArrayList();
IList arValue = new ArrayList();
IList arFieldType = new ArrayList();
foreach (QueryClause qi in arQueryList)
{
arFieldName.Add(qi.GetAttribute());
arFieldType.Add(qi.GetAttributeType());
arOperator.Add(qi.GetOperator());
arValue.Add(qi.GetValue());
}
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FILTERFIELDLIST);
rvtemp.SetList(arFieldName);
rvsQual.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FILTERFIELDTYPELIST);
rvtemp.SetList(arFieldType);
rvsQual.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FILTEROPERATORLIST);
rvtemp.SetList(arOperator);
rvsQual.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_FILTERVALUELIST);
rvtemp.SetList(arValue);
rvsQual.AddReturnValue(rvtemp);
rvtemp = new ReturnValue(0);
rvtemp.SetName(Parameter.QUERY_MAXROWS);
rvtemp.SetType(ReturnValueTypes.STRING);
rvtemp.SetValue(maxrows.ToString());
rvsQual.AddReturnValue(rvtemp);
}
public override bool Equals(object obj)
{
if (obj == null || (GetType() != obj.GetType()))
{
return false;
}
QueryClause o = (QueryClause)obj;
if (!String.Equals(this.AttributeDisplay, o.AttributeDisplay)) return false;
if (!String.Equals(this.Attribute, o.Attribute)) return false;
if (!String.Equals(this.OperatorDisplay, o.OperatorDisplay)) return false;
if (!String.Equals(this.Operator, o.Operator)) return false;
if (!String.Equals(this.ValueDisplay, o.ValueDisplay)) return false;
if (!String.Equals(this.Value, o.Value)) return false;
if (!String.Equals(this.AttributeType, o.AttributeType)) return false;
return true;
}
public override int GetHashCode()
{
int hashCode = 0;
if (AttributeDisplay != null) hashCode += AttributeDisplay.GetHashCode();
if (Attribute != null) hashCode += Attribute.GetHashCode();
if (OperatorDisplay != null) hashCode += OperatorDisplay.GetHashCode();
if (Operator != null) hashCode += Operator.GetHashCode();
if (ValueDisplay != null) hashCode += ValueDisplay.GetHashCode();
if (Value != null) hashCode += Value.GetHashCode();
if (AttributeType != null) hashCode += AttributeType.GetHashCode();
return hashCode;
}
}
}
| |
using System;
using UnityEngine;
namespace DarkMultiPlayer
{
public class OptionsWindow
{
private static OptionsWindow singleton = new OptionsWindow();
public bool loadEventHandled = true;
public bool display;
private bool isWindowLocked = false;
private bool safeDisplay;
private bool initialized;
//GUI Layout
private Rect windowRect;
private Rect moveRect;
private GUILayoutOption[] layoutOptions;
private GUILayoutOption[] smallOption;
//Styles
private GUIStyle windowStyle;
private GUIStyle buttonStyle;
//const
private const float WINDOW_HEIGHT = 400;
private const float WINDOW_WIDTH = 300;
//TempColour
private Color tempColor = new Color(1f, 1f, 1f, 1f);
private GUIStyle tempColorLabelStyle;
//Cache size
private string newCacheSize = "";
//Keybindings
private bool settingChat;
private bool settingScreenshot;
private string toolbarMode;
public OptionsWindow()
{
Client.updateEvent.Add(this.Update);
Client.drawEvent.Add(this.Draw);
}
public static OptionsWindow fetch
{
get
{
return singleton;
}
}
private void InitGUI()
{
//Setup GUI stuff
windowRect = new Rect(Screen.width / 2f - WINDOW_WIDTH / 2f, Screen.height / 2f - WINDOW_HEIGHT / 2f, WINDOW_WIDTH, WINDOW_HEIGHT);
moveRect = new Rect(0, 0, 10000, 20);
windowStyle = new GUIStyle(GUI.skin.window);
buttonStyle = new GUIStyle(GUI.skin.button);
layoutOptions = new GUILayoutOption[4];
layoutOptions[0] = GUILayout.Width(WINDOW_WIDTH);
layoutOptions[1] = GUILayout.Height(WINDOW_HEIGHT);
layoutOptions[2] = GUILayout.ExpandWidth(true);
layoutOptions[3] = GUILayout.ExpandHeight(true);
smallOption = new GUILayoutOption[2];
smallOption[0] = GUILayout.Width(100);
smallOption[1] = GUILayout.ExpandWidth(false);
tempColor = new Color();
tempColorLabelStyle = new GUIStyle(GUI.skin.label);
UpdateToolbarString();
}
private void UpdateToolbarString()
{
switch (Settings.fetch.toolbarType)
{
case DMPToolbarType.DISABLED:
toolbarMode = "Disabled";
break;
case DMPToolbarType.FORCE_STOCK:
toolbarMode = "Stock";
break;
case DMPToolbarType.BLIZZY_IF_INSTALLED:
toolbarMode = "Blizzy if installed";
break;
case DMPToolbarType.BOTH_IF_INSTALLED:
toolbarMode = "Both if installed";
break;
}
}
private void Update()
{
safeDisplay = display;
}
private void Draw()
{
if (!initialized)
{
initialized = true;
InitGUI();
}
if (safeDisplay)
{
windowRect = DMPGuiUtil.PreventOffscreenWindow(GUILayout.Window(6711 + Client.WINDOW_OFFSET, windowRect, DrawContent, "DarkMultiPlayer - Options", windowStyle, layoutOptions));
}
CheckWindowLock();
}
private void DrawContent(int windowID)
{
if (!loadEventHandled)
{
loadEventHandled = true;
tempColor = Settings.fetch.playerColor;
newCacheSize = Settings.fetch.cacheSize.ToString();
}
//Player color
GUILayout.BeginVertical();
GUI.DragWindow(moveRect);
GUILayout.BeginHorizontal();
GUILayout.Label("Player name color: ");
GUILayout.Label(Settings.fetch.playerName, tempColorLabelStyle);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("R: ");
tempColor.r = GUILayout.HorizontalScrollbar(tempColor.r, 0, 0, 1);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("G: ");
tempColor.g = GUILayout.HorizontalScrollbar(tempColor.g, 0, 0, 1);
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
GUILayout.Label("B: ");
tempColor.b = GUILayout.HorizontalScrollbar(tempColor.b, 0, 0, 1);
GUILayout.EndHorizontal();
tempColorLabelStyle.active.textColor = tempColor;
tempColorLabelStyle.normal.textColor = tempColor;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Random", buttonStyle))
{
tempColor = PlayerColorWorker.GenerateRandomColor();
}
if (GUILayout.Button("Set", buttonStyle))
{
PlayerStatusWindow.fetch.colorEventHandled = false;
Settings.fetch.playerColor = tempColor;
Settings.fetch.SaveSettings();
if (NetworkWorker.fetch.state == DarkMultiPlayerCommon.ClientState.RUNNING)
{
PlayerColorWorker.fetch.SendPlayerColorToServer();
}
}
GUILayout.EndHorizontal();
GUILayout.Space(10);
//Cache
GUILayout.Label("Cache size");
GUILayout.Label("Current size: " + Math.Round((UniverseSyncCache.fetch.currentCacheSize / (float)(1024 * 1024)), 3) + "MB.");
GUILayout.Label("Max size: " + Settings.fetch.cacheSize + "MB.");
newCacheSize = GUILayout.TextArea(newCacheSize);
GUILayout.BeginHorizontal();
if (GUILayout.Button("Set", buttonStyle))
{
int tempCacheSize;
if (Int32.TryParse(newCacheSize, out tempCacheSize))
{
if (tempCacheSize < 1)
{
tempCacheSize = 1;
newCacheSize = tempCacheSize.ToString();
}
if (tempCacheSize > 1000)
{
tempCacheSize = 1000;
newCacheSize = tempCacheSize.ToString();
}
Settings.fetch.cacheSize = tempCacheSize;
Settings.fetch.SaveSettings();
}
else
{
newCacheSize = Settings.fetch.cacheSize.ToString();
}
}
if (GUILayout.Button("Expire cache"))
{
UniverseSyncCache.fetch.ExpireCache();
}
if (GUILayout.Button("Delete cache"))
{
UniverseSyncCache.fetch.DeleteCache();
}
GUILayout.EndHorizontal();
//Key bindings
GUILayout.Space(10);
string chatDescription = "Set chat key (current: " + Settings.fetch.chatKey + ")";
if (settingChat)
{
chatDescription = "Setting chat key (click to cancel)...";
if (Event.current.isKey)
{
if (Event.current.keyCode != KeyCode.Escape)
{
Settings.fetch.chatKey = Event.current.keyCode;
Settings.fetch.SaveSettings();
settingChat = false;
}
else
{
settingChat = false;
}
}
}
if (GUILayout.Button(chatDescription))
{
settingChat = !settingChat;
}
string screenshotDescription = "Set screenshot key (current: " + Settings.fetch.screenshotKey.ToString() + ")";
if (settingScreenshot)
{
screenshotDescription = "Setting screenshot key (click to cancel)...";
if (Event.current.isKey)
{
if (Event.current.keyCode != KeyCode.Escape)
{
Settings.fetch.screenshotKey = Event.current.keyCode;
Settings.fetch.SaveSettings();
settingScreenshot = false;
}
else
{
settingScreenshot = false;
}
}
}
if (GUILayout.Button(screenshotDescription))
{
settingScreenshot = !settingScreenshot;
}
GUILayout.Space(10);
GUILayout.Label("Generate a server DMPModControl:");
if (GUILayout.Button("Generate blacklist DMPModControl.txt"))
{
ModWorker.fetch.GenerateModControlFile(false);
}
if (GUILayout.Button("Generate whitelist DMPModControl.txt"))
{
ModWorker.fetch.GenerateModControlFile(true);
}
UniverseConverterWindow.fetch.display = GUILayout.Toggle(UniverseConverterWindow.fetch.display, "Generate Universe from saved game", buttonStyle);
if (GUILayout.Button("Reset disclaimer"))
{
Settings.fetch.disclaimerAccepted = 0;
Settings.fetch.SaveSettings();
}
bool settingCompression = GUILayout.Toggle(Settings.fetch.compressionEnabled, "Enable compression", buttonStyle);
if (settingCompression != Settings.fetch.compressionEnabled)
{
Settings.fetch.compressionEnabled = settingCompression;
Settings.fetch.SaveSettings();
}
bool settingRevert = GUILayout.Toggle(Settings.fetch.revertEnabled, "Enable revert", buttonStyle);
if (settingRevert != Settings.fetch.revertEnabled)
{
Settings.fetch.revertEnabled = settingRevert;
Settings.fetch.SaveSettings();
}
GUILayout.BeginHorizontal();
GUILayout.Label("Toolbar:", smallOption);
if (GUILayout.Button(toolbarMode, buttonStyle))
{
int newSetting = (int)Settings.fetch.toolbarType + 1;
//Overflow to 0
if (!Enum.IsDefined(typeof(DMPToolbarType), newSetting))
{
newSetting = 0;
}
Settings.fetch.toolbarType = (DMPToolbarType)newSetting;
Settings.fetch.SaveSettings();
UpdateToolbarString();
ToolbarSupport.fetch.DetectSettingsChange();
}
GUILayout.EndHorizontal();
#if DEBUG
if (GUILayout.Button("Check Common.dll stock parts"))
{
ModWorker.fetch.CheckCommonStockParts();
}
#endif
GUILayout.FlexibleSpace();
if (GUILayout.Button("Close", buttonStyle))
{
display = false;
}
GUILayout.EndVertical();
}
private void CheckWindowLock()
{
if (!Client.fetch.gameRunning)
{
RemoveWindowLock();
return;
}
if (HighLogic.LoadedSceneIsFlight)
{
RemoveWindowLock();
return;
}
if (safeDisplay)
{
Vector2 mousePos = Input.mousePosition;
mousePos.y = Screen.height - mousePos.y;
bool shouldLock = windowRect.Contains(mousePos);
if (shouldLock && !isWindowLocked)
{
InputLockManager.SetControlLock(ControlTypes.ALLBUTCAMERAS, "DMP_OptionsLock");
isWindowLocked = true;
}
if (!shouldLock && isWindowLocked)
{
RemoveWindowLock();
}
}
if (!safeDisplay && isWindowLocked)
{
RemoveWindowLock();
}
}
private void RemoveWindowLock()
{
if (isWindowLocked)
{
isWindowLocked = false;
InputLockManager.RemoveControlLock("DMP_OptionsLock");
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyDateTimeRfc1123
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Datetimerfc1123 operations.
/// </summary>
public partial class Datetimerfc1123 : IServiceOperations<AutoRestRFC1123DateTimeTestService>, IDatetimerfc1123
{
/// <summary>
/// Initializes a new instance of the Datetimerfc1123 class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the AutoRestRFC1123DateTimeTestService
/// </summary>
public AutoRestRFC1123DateTimeTestService Client { get; private set; }
/// <summary>
/// Get null datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetNullWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetNull", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/null").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get invalid datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetInvalidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetInvalid", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/invalid").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get overflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetOverflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetOverflow", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/overflow").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get underflow datetime value
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetUnderflowWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUnderflow", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/underflow").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutUtcMaxDateTimeWithHttpMessagesAsync(DateTime datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("datetimeBody", datetimeBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutUtcMaxDateTime", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter());
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get max datetime value fri, 31 dec 9999 23:59:59 gmt
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetUtcLowercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUtcLowercaseMaxDateTime", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max/lowercase").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetUtcUppercaseMaxDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUtcUppercaseMaxDateTime", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/max/uppercase").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='datetimeBody'>
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse> PutUtcMinDateTimeWithHttpMessagesAsync(DateTime datetimeBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("datetimeBody", datetimeBody);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutUtcMinDateTime", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/min").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
_requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter());
_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8);
_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT
/// </summary>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<DateTime?>> GetUtcMinDateTimeWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetUtcMinDateTime", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datetimerfc1123/min").ToString();
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<DateTime?>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<DateTime?>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Reflection;
[CustomEditor (typeof (EasyFontTextMesh))]
public class EasyFontCustomEditor : Editor {
private bool wasPrefabModified;
private bool isFirstTime = true;
void OnEnable()
{
EasyFontTextMesh customFont = target as EasyFontTextMesh;
if (customFont.GUIChanged || isFirstTime)
{
//customFont.RefreshMeshEditor();
RefreshAllSceneText(); //Refresh all test to solve the duplicate command issue (Text is not seeing when duplicating). Comment this line an use line above if you have a lot of text
// and are sufferig slowdonws in the editor when selecting texts
isFirstTime = false; //This is a hack because on enable is called a lot of times because of the porpertie font
}
}
void OnDisable()
{
EasyFontTextMesh customFont = target as EasyFontTextMesh;
if (customFont.GUIChanged) //Hack because of the properties is calling this even if there is no OnDisable
isFirstTime = true;
}
public override void OnInspectorGUI()
{
EditorGUIUtility.LookLikeInspector();
DrawDefaultInspector();
EasyFontTextMesh customFont = target as EasyFontTextMesh;
SerializedObject serializedObject = new SerializedObject(customFont);
SerializedProperty serializedText = serializedObject.FindProperty("_privateProperties.text");
SerializedProperty serializedFontType = serializedObject.FindProperty("_privateProperties.font");
SerializedProperty serializedFontFillMaterial = serializedObject.FindProperty("_privateProperties.customFillMaterial");
SerializedProperty serializedFontSize = serializedObject.FindProperty("_privateProperties.fontSize");
SerializedProperty serializedCharacterSize = serializedObject.FindProperty("_privateProperties.size");
SerializedProperty serializedTextAnchor = serializedObject.FindProperty("_privateProperties.textAnchor");
SerializedProperty serializedTextAlignment = serializedObject.FindProperty("_privateProperties.textAlignment");
SerializedProperty serializedLineSpacing = serializedObject.FindProperty("_privateProperties.lineSpacing");
SerializedProperty serializedFontColorTop = serializedObject.FindProperty("_privateProperties.fontColorTop");
SerializedProperty serializedFontColorBottom = serializedObject.FindProperty("_privateProperties.fontColorBottom");
SerializedProperty serializedEnableShadow = serializedObject.FindProperty("_privateProperties.enableShadow");
SerializedProperty serializedShadowColor = serializedObject.FindProperty("_privateProperties.shadowColor");
SerializedProperty serializedShadowDistance = serializedObject.FindProperty("_privateProperties.shadowDistance");
SerializedProperty serializedEnableOutline = serializedObject.FindProperty("_privateProperties.enableOutline");
SerializedProperty serializedOutlineColor = serializedObject.FindProperty("_privateProperties.outlineColor");
SerializedProperty serializedOutlineWidth = serializedObject.FindProperty("_privateProperties.outLineWidth");
SerializedProperty serializedHQOutline = serializedObject.FindProperty("_privateProperties.highQualityOutline");
SerializedProperty[] allSerializedProperties = new SerializedProperty[17]
{
serializedText, serializedFontType, serializedFontFillMaterial , serializedFontSize, serializedCharacterSize,serializedTextAnchor, serializedTextAlignment,
serializedLineSpacing, serializedFontColorTop, serializedFontColorBottom, serializedEnableShadow, serializedShadowColor, serializedShadowDistance,
serializedEnableOutline, serializedOutlineColor, serializedOutlineWidth, serializedHQOutline
};
#region properties
//Text
if(serializedText.isInstantiatedPrefab)
SetBoldDefaultFont(serializedText.prefabOverride);
EditorGUILayout.LabelField(new GUIContent("Text", "This is the text that is going to be used"));
EditorGUILayout.BeginVertical("box");
customFont.Text = EditorGUILayout.TextArea(customFont.Text);
//customFont.Text = EditorGUILayout.TextField("Text", customFont.Text); //Old way of inserting text
EditorGUILayout.EndVertical();
//Font
if(serializedFontType.isInstantiatedPrefab)
SetBoldDefaultFont(serializedFontType.prefabOverride);
customFont.FontType = EditorGUILayout.ObjectField(new GUIContent("Font","The desired font type"), customFont.FontType, typeof(Font), false) as Font;
if (customFont.FontType == null)
{
customFont.FontType = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
}
//Font material
if(serializedFontFillMaterial.isInstantiatedPrefab)
SetBoldDefaultFont(serializedFontFillMaterial.prefabOverride);
customFont.CustomFillMaterial = EditorGUILayout.ObjectField(new GUIContent("Custom Fill material", "Use a material different form the one deffined by the font"), customFont.CustomFillMaterial, typeof(Material), false) as Material;
if (customFont.FontType == null)
{
customFont.FontType = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
}
//Font Size
if(serializedFontSize.isInstantiatedPrefab)
SetBoldDefaultFont(serializedFontSize.prefabOverride);
customFont.FontSize = EditorGUILayout.IntField(new GUIContent("Font size", "This is the actual font size. It will set the texture size"), customFont.FontSize);
//CharacterSize
if(serializedCharacterSize.isInstantiatedPrefab)
SetBoldDefaultFont(serializedCharacterSize.prefabOverride);
customFont.Size = EditorGUILayout.FloatField(new GUIContent("Character size", "How big the characters are going to be renderer"), customFont.Size);
//Text acnhor
if(serializedTextAnchor.isInstantiatedPrefab)
SetBoldDefaultFont(serializedTextAnchor.prefabOverride);
customFont.Textanchor = (EasyFontTextMesh.TEXT_ANCHOR)EditorGUILayout.EnumPopup(new GUIContent("Text Anchor", "Position of the texts pivot's point"), customFont.Textanchor);
//Text alignment
if(serializedTextAlignment.isInstantiatedPrefab)
SetBoldDefaultFont(serializedTextAlignment.prefabOverride);
customFont.Textalignment = (EasyFontTextMesh.TEXT_ALIGNMENT)EditorGUILayout.EnumPopup(new GUIContent("Text alignment", "Line alignment"), customFont.Textalignment);
//Line spacing
if(serializedLineSpacing .isInstantiatedPrefab)
SetBoldDefaultFont(serializedLineSpacing.prefabOverride);
customFont.LineSpacing = EditorGUILayout.FloatField(new GUIContent("Line spacing", "Distance between lines"), customFont.LineSpacing);
// Font color
if(serializedFontColorTop.isInstantiatedPrefab)
SetBoldDefaultFont(serializedFontColorTop.prefabOverride);
customFont.FontColorTop = EditorGUILayout.ColorField (new GUIContent("Top Color", "Color for the top"), customFont.FontColorTop);
if(serializedFontColorBottom.isInstantiatedPrefab)
SetBoldDefaultFont(serializedFontColorBottom.prefabOverride);
customFont.FontColorBottom = EditorGUILayout.ColorField (new GUIContent("Bottom Color", "Color for the bottom"), customFont.FontColorBottom);
// Shadow
if(serializedEnableShadow.isInstantiatedPrefab)
SetBoldDefaultFont(serializedEnableShadow.prefabOverride);
customFont.EnableShadow = EditorGUILayout.Toggle(new GUIContent("Enable Shadow", "Enable/Disable shadow"), customFont.EnableShadow);
if (customFont.EnableShadow) //Only show the options when enabled
{
EditorGUILayout.BeginVertical("box");
if(serializedShadowColor.isInstantiatedPrefab)
SetBoldDefaultFont(serializedShadowColor.prefabOverride);
customFont.ShadowColor = EditorGUILayout.ColorField(new GUIContent("Shadow color", "Sets the sahdow's color"), customFont.ShadowColor);
if(serializedShadowDistance.isInstantiatedPrefab)
SetBoldDefaultFont(serializedShadowDistance.prefabOverride);
customFont.ShadowDistance = EditorGUILayout.Vector3Field("Shadow distance", customFont.ShadowDistance);
EditorGUILayout.EndVertical();
}
//Outline
if(serializedEnableOutline.isInstantiatedPrefab)
SetBoldDefaultFont(serializedEnableOutline.prefabOverride);
customFont.EnableOutline = EditorGUILayout.Toggle(new GUIContent("Enable Outline", "Enable/Disable the text's outline"), customFont.EnableOutline);
if (customFont.EnableOutline) //Only show the options when enabled
{
EditorGUILayout.BeginVertical("box");
if(serializedOutlineColor.isInstantiatedPrefab)
SetBoldDefaultFont(serializedOutlineColor.prefabOverride);
customFont.OutlineColor = EditorGUILayout.ColorField(new GUIContent("Outline color", "Sets the ouline color"), customFont.OutlineColor);
if(serializedOutlineWidth.isInstantiatedPrefab)
SetBoldDefaultFont(serializedOutlineWidth.prefabOverride);
customFont.OutLineWidth = EditorGUILayout.FloatField(new GUIContent("Outline width", "Sets the outline width"), customFont.OutLineWidth);
if(serializedHQOutline.isInstantiatedPrefab)
SetBoldDefaultFont(serializedHQOutline.prefabOverride);
customFont.HighQualityOutline = EditorGUILayout.Toggle(new GUIContent("High Quality", "Increase the number of vertex but gives better results"), customFont.HighQualityOutline);
EditorGUILayout.EndVertical();
}
#endregion
#region buttons and info
if (GUILayout.Button("Refresh"))
{
Debug.Log("Refreshing Text mesh");
customFont.RefreshMeshEditor();
}
if (GUILayout.Button("Refresh all"))
{
RefreshAllSceneText();
//OnPlayModeChanged();
}
GUIStyle buttonStyleRed = new GUIStyle("button");
buttonStyleRed.normal.textColor = Color.red;
if (GUILayout.Button("Destroy Text component",buttonStyleRed))
{
Renderer tempRenderer = customFont.gameObject.renderer;
MeshFilter tempMeshFilter = customFont.GetComponent<MeshFilter>();
DestroyImmediate(customFont);
DestroyImmediate(tempRenderer);
DestroyImmediate(tempMeshFilter.sharedMesh);
DestroyImmediate(tempMeshFilter);
return;
}
GUIStyle greenText = new GUIStyle();
greenText.normal.textColor = Color.green;
EditorGUILayout.LabelField (string.Format("Vertex count {0}", customFont.GetVertexCount().ToString()),greenText);
EditorGUILayout.LabelField (string.Format("Font Texture Size {0} x {1}", customFont.renderer.sharedMaterial.mainTexture.width.ToString(),customFont.renderer.sharedMaterial.mainTexture.height.ToString()),greenText);
#endregion
#region prefab checks
//Check if the prefab has changed to refresh the text
bool checkCurrentPrefabModification = false;
PropertyModification[] modifiedProperties = PrefabUtility.GetPropertyModifications((Object)customFont);
if (modifiedProperties != null && modifiedProperties.Length > 0)
{
for (int i = 0; i<modifiedProperties.Length; i++)
{
foreach (SerializedProperty serializerPropertyIterator in allSerializedProperties)
{
if (serializerPropertyIterator.propertyPath == modifiedProperties[i].propertyPath)
{
wasPrefabModified = true;
checkCurrentPrefabModification = true;
}
}
}
}
else
{
checkCurrentPrefabModification = false;
}
if (wasPrefabModified && !checkCurrentPrefabModification)
{
RefreshAllSceneText();
wasPrefabModified = false;
}
//Security check. If the mesh is null a prefab revert has been made
if (customFont.GetComponent<MeshFilter>().sharedMesh == null)
customFont.RefreshMeshEditor();
#endregion
customFont.GUIChanged = GUI.changed;
if (customFont.GUIChanged)
{
customFont.RefreshMeshEditor();
EditorUtility.SetDirty(customFont);
}
}
void RefreshAllSceneText()
{
Object[] customFonts = Resources.FindObjectsOfTypeAll(typeof(EasyFontTextMesh));
if (customFonts.Length > 0)
{
for (int i= 0; i < customFonts.Length; i++)
{
if (AssetDatabase.GetAssetPath(customFonts[i]) == "") //Only affect the scene assets
{
EasyFontTextMesh tempCustomFont = (EasyFontTextMesh)customFonts[i];
tempCustomFont.RefreshMeshEditor();
}
}
}
//GameObject.Find("Perrete2").GetComponent<CustomTextMesh>().name = "Perrete1";
}
private MethodInfo boldFontMethodInfo = null;
private void SetBoldDefaultFont(bool value) {
boldFontMethodInfo = typeof(EditorGUIUtility).GetMethod("SetBoldDefaultFont", BindingFlags.Static | BindingFlags.NonPublic);
boldFontMethodInfo.Invoke(null, new[] { value as object });
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// SpriteEffects.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace SpriteEffects
{
/// <summary>
/// Sample demonstrating how shaders can be used to
/// apply special effects to sprite rendering.
/// </summary>
public class SpriteEffectsGame : Microsoft.Xna.Framework.Game
{
#region Fields
GraphicsDeviceManager graphics;
KeyboardState lastKeyboardState = new KeyboardState();
GamePadState lastGamePadState = new GamePadState();
KeyboardState currentKeyboardState = new KeyboardState();
GamePadState currentGamePadState = new GamePadState();
// Enum describes all the rendering techniques used in this demo.
enum DemoEffect
{
Desaturate,
Disappear,
RefractCat,
RefractGlacier,
Normalmap,
}
DemoEffect currentEffect = 0;
// Effects used by this sample.
Effect desaturateEffect;
Effect disappearEffect;
Effect normalmapEffect;
Effect refractionEffect;
// Textures used by this sample.
Texture2D catTexture;
Texture2D catNormalmapTexture;
Texture2D glacierTexture;
Texture2D waterfallTexture;
// SpriteBatch instance used to render all the effects.
SpriteBatch spriteBatch;
#endregion
#region Initialization
public SpriteEffectsGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
}
/// <summary>
/// Loads graphics content.
/// </summary>
protected override void LoadContent()
{
desaturateEffect = Content.Load<Effect>("desaturate");
disappearEffect = Content.Load<Effect>("disappear");
normalmapEffect = Content.Load<Effect>("normalmap");
refractionEffect = Content.Load<Effect>("refraction");
catTexture = Content.Load<Texture2D>("cat");
catNormalmapTexture = Content.Load<Texture2D>("cat_normalmap");
glacierTexture = Content.Load<Texture2D>("glacier");
waterfallTexture = Content.Load<Texture2D>("waterfall");
spriteBatch = new SpriteBatch(graphics.GraphicsDevice);
}
#endregion
#region Update and Draw
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
if (NextButtonPressed())
{
currentEffect++;
if (currentEffect > DemoEffect.Normalmap)
currentEffect = 0;
}
base.Update(gameTime);
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
switch (currentEffect)
{
case DemoEffect.Desaturate:
DrawDesaturate(gameTime);
break;
case DemoEffect.Disappear:
DrawDisappear(gameTime);
break;
case DemoEffect.Normalmap:
DrawNormalmap(gameTime);
break;
case DemoEffect.RefractCat:
DrawRefractCat(gameTime);
break;
case DemoEffect.RefractGlacier:
DrawRefractGlacier(gameTime);
break;
}
base.Draw(gameTime);
}
/// <summary>
/// Effect dynamically changes color saturation.
/// </summary>
void DrawDesaturate(GameTime gameTime)
{
// Begin the sprite batch, using our custom effect.
spriteBatch.Begin(0, null, null, null, null, desaturateEffect);
// Draw four copies of the same sprite with different saturation levels.
// The saturation amount is passed into the effect using the alpha of the
// SpriteBatch.Draw color parameter. This isn't as flexible as using a
// regular effect parameter, but makes it easy to draw many sprites with
// a different saturation amount for each. If we had used an effect
// parameter for this, we would have to end the sprite batch, then begin
// a new one, each time we wanted to change the saturation setting.
byte pulsate = (byte)Pulsate(gameTime, 4, 0, 255);
spriteBatch.Draw(glacierTexture,
QuarterOfScreen(0, 0),
new Color(255, 255, 255, 0));
spriteBatch.Draw(glacierTexture,
QuarterOfScreen(1, 0),
new Color(255, 255, 255, 64));
spriteBatch.Draw(glacierTexture,
QuarterOfScreen(0, 1),
new Color(255, 255, 255, 255));
spriteBatch.Draw(glacierTexture,
QuarterOfScreen(1, 1),
new Color(255, 255, 255, pulsate));
// End the sprite batch.
spriteBatch.End();
}
/// <summary>
/// Effect uses a scrolling overlay texture to make different parts of
/// an image fade in or out at different speeds.
/// </summary>
void DrawDisappear(GameTime gameTime)
{
// Draw the background image.
spriteBatch.Begin();
spriteBatch.Draw(glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();
// Set an effect parameter to make our overlay
// texture scroll in a giant circle.
disappearEffect.Parameters["OverlayScroll"].SetValue(
MoveInCircle(gameTime, 0.8f) * 0.25f);
// Set the overlay texture (as texture 1,
// because 0 will be the main sprite texture).
graphics.GraphicsDevice.Textures[1] = waterfallTexture;
// Begin the sprite batch.
spriteBatch.Begin(0, null, null, null, null, disappearEffect);
// Draw the sprite, passing the fade amount as the
// alpha of the SpriteBatch.Draw color parameter.
byte fade = (byte)Pulsate(gameTime, 2, 0, 255);
spriteBatch.Draw(catTexture,
MoveInCircle(gameTime, catTexture, 1),
new Color(255, 255, 255, fade));
// End the sprite batch.
spriteBatch.End();
}
/// <summary>
// Effect uses a scrolling displacement texture to offset the position of
// the main texture.
/// </summary>
void DrawRefractCat(GameTime gameTime)
{
// Draw the background image.
spriteBatch.Begin();
spriteBatch.Draw(glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();
// Set an effect parameter to make the
// displacement texture scroll in a giant circle.
refractionEffect.Parameters["DisplacementScroll"].SetValue(
MoveInCircle(gameTime, 0.1f));
// Set the displacement texture.
graphics.GraphicsDevice.Textures[1] = waterfallTexture;
// Begin the sprite batch.
spriteBatch.Begin(0, null, null, null, null, refractionEffect);
// Draw the sprite.
spriteBatch.Draw(catTexture,
MoveInCircle(gameTime, catTexture, 1),
Color.White);
// End the sprite batch.
spriteBatch.End();
}
/// <summary>
// Effect uses a scrolling displacement texture to offset the position of
// the main texture.
/// </summary>
void DrawRefractGlacier(GameTime gameTime)
{
// Set an effect parameter to make the
// displacement texture scroll in a giant circle.
refractionEffect.Parameters["DisplacementScroll"].SetValue(
MoveInCircle(gameTime, 0.2f));
// Set the displacement texture.
graphics.GraphicsDevice.Textures[1] = waterfallTexture;
// Begin the sprite batch.
spriteBatch.Begin(0, null, null, null, null, refractionEffect);
// Because the effect will displace the texture coordinates before
// sampling the main texture, the coordinates could sometimes go right
// off the edges of the texture, which looks ugly. To prevent this, we
// adjust our sprite source region to leave a little border around the
// edge of the texture. The displacement effect will then just move the
// texture coordinates into this border region, without ever hitting
// the edge of the texture.
Rectangle croppedGlacier = new Rectangle(32, 32,
glacierTexture.Width - 64,
glacierTexture.Height - 64);
spriteBatch.Draw(glacierTexture,
GraphicsDevice.Viewport.Bounds,
croppedGlacier,
Color.White);
// End the sprite batch.
spriteBatch.End();
}
/// <summary>
/// Effect uses a normalmap texture to apply realtime lighting while
/// drawing a 2D sprite.
/// </summary>
void DrawNormalmap(GameTime gameTime)
{
// Draw the background image.
spriteBatch.Begin();
spriteBatch.Draw(glacierTexture, GraphicsDevice.Viewport.Bounds, Color.White);
spriteBatch.End();
// Animate the light direction.
Vector2 spinningLight = MoveInCircle(gameTime, 1.5f);
double time = gameTime.TotalGameTime.TotalSeconds;
float tiltUpAndDown = 0.5f + (float)Math.Cos(time * 0.75) * 0.1f;
Vector3 lightDirection = new Vector3(spinningLight * tiltUpAndDown,
1 - tiltUpAndDown);
lightDirection.Normalize();
normalmapEffect.Parameters["LightDirection"].SetValue(lightDirection);
// Set the normalmap texture.
graphics.GraphicsDevice.Textures[1] = catNormalmapTexture;
// Begin the sprite batch.
spriteBatch.Begin(0, null, null, null, null, normalmapEffect);
// Draw the sprite.
spriteBatch.Draw(catTexture, CenterOnScreen(catTexture), Color.White);
// End the sprite batch.
spriteBatch.End();
}
/// <summary>
/// Helper calculates the destination rectangle needed
/// to draw a sprite to one quarter of the screen.
/// </summary>
Rectangle QuarterOfScreen(int x, int y)
{
Viewport viewport = graphics.GraphicsDevice.Viewport;
int w = viewport.Width / 2;
int h = viewport.Height / 2;
return new Rectangle(w * x, h * y, w, h);
}
/// <summary>
/// Helper calculates the destination position needed
/// to center a sprite in the middle of the screen.
/// </summary>
Vector2 CenterOnScreen(Texture2D texture)
{
Viewport viewport = graphics.GraphicsDevice.Viewport;
int x = (viewport.Width - texture.Width) / 2;
int y = (viewport.Height - texture.Height) / 2;
return new Vector2(x, y);
}
/// <summary>
/// Helper computes a value that oscillates over time.
/// </summary>
static float Pulsate(GameTime gameTime, float speed, float min, float max)
{
double time = gameTime.TotalGameTime.TotalSeconds * speed;
return min + ((float)Math.Sin(time) + 1) / 2 * (max - min);
}
/// <summary>
/// Helper for moving a value around in a circle.
/// </summary>
static Vector2 MoveInCircle(GameTime gameTime, float speed)
{
double time = gameTime.TotalGameTime.TotalSeconds * speed;
float x = (float)Math.Cos(time);
float y = (float)Math.Sin(time);
return new Vector2(x, y);
}
/// <summary>
/// Helper for moving a sprite around in a circle.
/// </summary>
Vector2 MoveInCircle(GameTime gameTime, Texture2D texture, float speed)
{
Viewport viewport = graphics.GraphicsDevice.Viewport;
float x = (viewport.Width - texture.Width) / 2;
float y = (viewport.Height - texture.Height) / 2;
return MoveInCircle(gameTime, speed) * 128 + new Vector2(x, y);
}
#endregion
#region Handle Input
/// <summary>
/// Handles input for quitting the game.
/// </summary>
private void HandleInput()
{
lastKeyboardState = currentKeyboardState;
lastGamePadState = currentGamePadState;
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (currentKeyboardState.IsKeyDown(Keys.Escape) ||
currentGamePadState.Buttons.Back == ButtonState.Pressed)
{
Exit();
}
}
/// <summary>
/// Checks whether the user wants to advance to the next rendering effect.
/// </summary>
bool NextButtonPressed()
{
// Have they pressed the space bar?
if (currentKeyboardState.IsKeyDown(Keys.Space) &&
!lastKeyboardState.IsKeyDown(Keys.Space))
return true;
// Have they pressed the gamepad A button?
if (currentGamePadState.Buttons.A == ButtonState.Pressed &&
lastGamePadState.Buttons.A == ButtonState.Released)
return true;
return false;
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (SpriteEffectsGame game = new SpriteEffectsGame())
{
game.Run();
}
}
}
#endregion
}
| |
/* Copyright (c) 2007 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using Google.GData.Apps.Groups;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.GData.Extensions.Apps;
namespace Google.GData.Apps
{
/// <summary>
/// The AppsService class provides a simpler interface
/// for executing common Google Apps provisioning
/// requests.
/// </summary>
public class AppsService
{
private EmailListRecipientService emailListRecipientService;
private EmailListService emailListService;
private NicknameService nicknameService;
private UserService userAccountService;
private GroupsService groupsService;
private string applicationName;
private string domain;
/// <summary>
/// Constructs an AppsService with the specified credentials
/// for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="adminEmailAddress">the administrator's email address</param>
/// <param name="adminPassword">the administrator's password</param>
public AppsService(string domain, string adminEmailAddress, string adminPassword)
{
this.domain = domain;
this.applicationName = "apps-" + domain;
emailListRecipientService = new EmailListRecipientService(applicationName);
emailListRecipientService.setUserCredentials(adminEmailAddress, adminPassword);
emailListService = new EmailListService(applicationName);
emailListService.setUserCredentials(adminEmailAddress, adminPassword);
nicknameService = new NicknameService(applicationName);
nicknameService.setUserCredentials(adminEmailAddress, adminPassword);
userAccountService = new UserService(applicationName);
userAccountService.setUserCredentials(adminEmailAddress, adminPassword);
groupsService = new GroupsService(domain, applicationName);
groupsService.setUserCredentials(adminEmailAddress, adminPassword);
}
/// <summary>
/// Constructs an AppsService with the specified Authentication Token
/// for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="authenticationToken">the administrator's Authentication Token</param>
public AppsService(string domain, string authenticationToken)
{
this.domain = domain;
this.applicationName = "apps-" + domain;
emailListRecipientService = new EmailListRecipientService(applicationName);
emailListRecipientService.SetAuthenticationToken(authenticationToken);
emailListService = new EmailListService(applicationName);
emailListService.SetAuthenticationToken(authenticationToken);
nicknameService = new NicknameService(applicationName);
nicknameService.SetAuthenticationToken(authenticationToken);
userAccountService = new UserService(applicationName);
userAccountService.SetAuthenticationToken(authenticationToken);
groupsService = new GroupsService(domain, applicationName);
groupsService.SetAuthenticationToken(authenticationToken);
}
/// <summary>indicates if the connection should be kept alive,
/// default is true
/// </summary>
/// <param name="keepAlive">bool to set if the connection should be keptalive</param>
public void KeepAlive(bool keepAlive)
{
((GDataRequestFactory)emailListRecipientService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory)emailListService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory)nicknameService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory)userAccountService.RequestFactory).KeepAlive = keepAlive;
((GDataRequestFactory)groupsService.RequestFactory).KeepAlive = keepAlive;
}
/// <summary>
/// Generates a new Authentication Toklen for AppsService
/// with the specified credentials for accessing provisioning feeds on the specified domain.
/// </summary>
/// <param name="domain">the domain to access</param>
/// <param name="adminEmailAddress">the administrator's email address</param>
/// <param name="adminPassword">the administrator's password</param>
/// <returns>the newly generated authentication token</returns>
public static String GetNewAuthenticationToken(string domain, string adminEmailAddress, string adminPassword)
{
Service service = new Service(AppsNameTable.GAppsService,"apps-"+domain);
service.setUserCredentials(adminEmailAddress, adminPassword);
return service.QueryClientLoginToken();
}
/// <summary>
/// ApplicationName property accessor
/// </summary>
public string ApplicationName
{
get { return applicationName; }
set { applicationName = value; }
}
/// <summary>
/// Domain property accessor
/// </summary>
public string Domain
{
get { return domain; }
set { domain = value; }
}
/// <summary>
/// GroupsService accessor
/// </summary>
public GroupsService Groups
{
get { return groupsService; }
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="quotaLimitInMb">the account's quota, in MB</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
int quotaLimitInMb)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false);
entry.Quota = new QuotaElement(quotaLimitInMb);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="passwordHashFunction">the name of the hash function to hash the password</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
string passwordHashFunction)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false, passwordHashFunction);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Creates a new user account.
/// </summary>
/// <param name="username">the account's username</param>
/// <param name="givenName">the user's first (given) name</param>
/// <param name="familyName">the user's last (family) name</param>
/// <param name="password">the account's password</param>
/// <param name="passwordHashFunction">the name of the hash function to hash the password</param>
/// <param name="quotaLimitInMb">the account's quota, in MB</param>
/// <returns>the newly created UserEntry</returns>
public UserEntry CreateUser(string username,
string givenName,
string familyName,
string password,
string passwordHashFunction,
int quotaLimitInMb)
{
UserEntry entry = new UserEntry();
entry.Name = new NameElement(familyName, givenName);
entry.Login = new LoginElement(username, password, false, false, passwordHashFunction);
entry.Quota = new QuotaElement(quotaLimitInMb);
UserQuery query = new UserQuery(Domain);
return userAccountService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves all user account entries on this domain.
/// </summary>
/// <returns>the feed containing all user account entries</returns>
public UserFeed RetrieveAllUsers()
{
UserQuery query = new UserQuery(domain);
return userAccountService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 users beginning with the
/// specified username. Usernames are ordered case-insensitively
/// by ASCII value.
/// </summary>
/// <param name="startUsername">the first username that should appear
/// in your result set</param>
/// <returns>the feed containing the matching user account entries</returns>
public UserFeed RetrievePageOfUsers(string startUsername)
{
UserQuery query = new UserQuery(domain);
query.StartUserName = startUsername;
query.RetrieveAllUsers = false;
return userAccountService.Query(query);
}
/// <summary>
/// Retrieves the entry for the specified user.
/// </summary>
/// <param name="username">the username to retrieve</param>
/// <returns>the UserEntry for this user</returns>
public UserEntry RetrieveUser(string username)
{
UserQuery query = new UserQuery(domain);
query.UserName = username;
UserFeed feed = userAccountService.Query(query);
// It's safe to access Entries[0] here, because the service will
// have already thrown an exception if the username was invalid.
return feed.Entries[0] as UserEntry;
}
/// <summary>
/// Updates the specified user account.
/// </summary>
/// <param name="entry">The updated entry; modified properties
/// can include the user's first name, last name, username and
/// password.</param>
/// <returns>the updated UserEntry</returns>
public UserEntry UpdateUser(UserEntry entry)
{
return entry.Update();
}
/// <summary>
/// the appsservice is an application object holding several
/// real services object. To allow the setting of advanced http properties,
/// proxies and other things, we allow setting the factory class that is used.
///
/// a getter does not make a lot of sense here, as which of the several factories in use
/// are we getting? It also would give the illusion that you could get one object and then
/// modify it's settings.
/// </summary>
/// <param name="factory">The factory to use for the AppsService</param>
/// <returns></returns>
public void SetRequestFactory(IGDataRequestFactory factory)
{
if (factory == null)
{
throw new ArgumentNullException("factory", "The factory object should not be NULL");
}
emailListRecipientService.RequestFactory = factory;
emailListService.RequestFactory = factory;
nicknameService.RequestFactory = factory;
userAccountService.RequestFactory = factory;
groupsService.RequestFactory = factory;
}
/// <summary>
/// this creates a default AppsService Factory object that can be used to
/// be modified and then set using SetRequestFactory()
/// </summary>
/// <returns></returns>
public IGDataRequestFactory CreateRequestFactory()
{
return new GDataGAuthRequestFactory(AppsNameTable.GAppsService, this.applicationName);
}
/// <summary>
/// Suspends a user account.
/// </summary>
/// <param name="username">the username whose account you wish to suspend</param>
/// <returns>the updated UserEntry</returns>
public UserEntry SuspendUser(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Suspended = true;
return UpdateUser(entry);
}
/// <summary>
/// Restores a user account.
/// </summary>
/// <param name="username">the username whose account you wish to restore</param>
/// <returns>the updated UserEntry</returns>
public UserEntry RestoreUser(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Suspended = false;
return UpdateUser(entry);
}
/// <summary>
/// Adds admin privileges for a user. Note that executing this method
/// on a user who is already an admin has no effect.
/// </summary>
/// <param name="username">the user to make an administrator</param>
/// <returns>the updated UserEntry</returns>
public UserEntry AddAdminPrivilege(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Admin = true;
return UpdateUser(entry);
}
/// <summary>
/// Removes admin privileges for a user. Note that executing this method
/// on a user who is not an admin has no effect.
/// </summary>
/// <param name="username">the user from which to revoke admin privileges</param>
/// <returns>the updated UserEntry</returns>
public UserEntry RemoveAdminPrivilege(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.Admin = false;
return UpdateUser(entry);
}
/// <summary>
/// Forces the specified user to change his or her password at the next
/// login.
/// </summary>
/// <param name="username">the user who must change his/her password upon
/// logging in next</param>
/// <returns>the updated UserEntry</returns>
public UserEntry ForceUserToChangePassword(string username)
{
UserEntry entry = RetrieveUser(username);
entry.Login.ChangePasswordAtNextLogin = true;
return UpdateUser(entry);
}
/// <summary>
/// Deletes a user account.
/// </summary>
/// <param name="username">the username whose account you wish to delete</param>
public void DeleteUser(string username)
{
UserQuery query = new UserQuery(domain);
query.UserName = username;
userAccountService.Delete(query.Uri);
}
/// <summary>
/// Creates a nickname for the specified user.
/// </summary>
/// <param name="username">the user account for which you are creating a nickname</param>
/// <param name="nickname">the nickname for the user account</param>
/// <returns>the newly created NicknameEntry object</returns>
public NicknameEntry CreateNickname(string username, string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
NicknameEntry entry = new NicknameEntry();
entry.Login = new LoginElement(username);
entry.Nickname = new NicknameElement(nickname);
return nicknameService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves all nicknames on this domain.
/// </summary>
/// <returns>the feed containing all nickname entries</returns>
public NicknameFeed RetrieveAllNicknames()
{
NicknameQuery query = new NicknameQuery(Domain);
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 nicknames beginning with the
/// specified nickname. Nicknames are ordered case-insensitively
/// by ASCII value.
/// </summary>
/// <param name="startNickname">the first nickname that should appear
/// in your result set</param>
/// <returns>the feed containing the matching nickname entries</returns>
public NicknameFeed RetrievePageOfNicknames(string startNickname)
{
NicknameQuery query = new NicknameQuery(domain);
query.StartNickname = startNickname;
query.RetrieveAllNicknames = false;
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves all nicknames for the specified user.
/// </summary>
/// <param name="username">the username for which you wish to retrieve nicknames</param>
/// <returns>the feed containing all nickname entries for this user</returns>
public NicknameFeed RetrieveNicknames(string username)
{
NicknameQuery query = new NicknameQuery(Domain);
query.UserName = username;
return nicknameService.Query(query);
}
/// <summary>
/// Retrieves the specified nickname.
/// </summary>
/// <param name="nickname">the nickname to retrieve</param>
/// <returns>the resulting NicknameEntry</returns>
public NicknameEntry RetrieveNickname(string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
query.Nickname = nickname;
NicknameFeed feed = nicknameService.Query(query);
// It's safe to access Entries[0] here, because the service will
// have already thrown an exception if the nickname was invalid.
return feed.Entries[0] as NicknameEntry;
}
/// <summary>
/// Deletes the specified nickname.
/// </summary>
/// <param name="nickname">the nickname that you wish to delete</param>
public void DeleteNickname(string nickname)
{
NicknameQuery query = new NicknameQuery(Domain);
query.Nickname = nickname;
nicknameService.Delete(query.Uri);
}
/// <summary>
/// Creates a new email list on this domain.
/// </summary>
/// <param name="emailList">the name of the email list that you wish to create.</param>
/// <returns>the newly created EmailListEntry</returns>
public EmailListEntry CreateEmailList(string emailList)
{
EmailListQuery query = new EmailListQuery(Domain);
EmailListEntry entry = new EmailListEntry(emailList);
return emailListService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves all email lists on the domain.
/// </summary>
/// <returns>the feed containing all email list entries</returns>
public EmailListFeed RetrieveAllEmailLists()
{
EmailListQuery query = new EmailListQuery(Domain);
return emailListService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 email list names beginning with the
/// specified email list name. Email lists are ordered case-insensitively
/// by ASCII value.
/// </summary>
/// <param name="startEmailListName">the first email list name that should
/// appear in your result set</param>
/// <returns>the feed containing the matching email list entries</returns>
public EmailListFeed RetrievePageOfEmailLists(string startEmailListName)
{
EmailListQuery query = new EmailListQuery(Domain);
query.StartEmailListName = startEmailListName;
query.RetrieveAllEmailLists = false;
return emailListService.Query(query);
}
/// <summary>
/// Retrieves the specified email list.
/// </summary>
/// <param name="emailList">is the name of the email list that you wish to retrieve</param>
/// <returns>the resulting EmailListEntry</returns>
public EmailListEntry RetrieveEmailList(string emailList)
{
EmailListQuery query = new EmailListQuery(Domain);
query.EmailListName = emailList;
EmailListFeed feed = emailListService.Query(query);
// It's safe to access Entries[0] here, because the service will have
// already thrown an exception if the email list name was invalid.
return feed.Entries[0] as EmailListEntry;
}
/// <summary>
/// Retrieves all email lists to which the specified user subscribes.
/// </summary>
/// <param name="recipient">the username or email address of a hosted user
/// for which you wish to retrieve email list subscriptions</param>
/// <returns>the feed containing all matching email list entries</returns>
public EmailListFeed RetrieveEmailLists(string recipient)
{
EmailListQuery query = new EmailListQuery(Domain);
query.Recipient = recipient;
return emailListService.Query(query);
}
/// <summary>
/// Deletes the specified email list.
/// </summary>
/// <param name="emailList">the name of the email list that you wish to delete</param>
public void DeleteEmailList(string emailList)
{
EmailListQuery query = new EmailListQuery(Domain);
query.EmailListName = emailList;
emailListService.Delete(query.Uri);
}
/// <summary>
/// Adds the specified recipient to an email list.
/// </summary>
/// <param name="recipientAddress">the email address that is being added</param>
/// <param name="emailList">the email address to which the address is being added</param>
/// <returns>the newly inserted EmailListRecipientEntry</returns>
public EmailListRecipientEntry AddRecipientToEmailList(string recipientAddress, string emailList)
{
EmailListRecipientQuery query = new EmailListRecipientQuery(Domain, emailList);
EmailListRecipientEntry entry = new EmailListRecipientEntry(recipientAddress);
return emailListRecipientService.Insert(query.Uri, entry);
}
/// <summary>
/// Retrieves list of all of the subscribers to an email list.
/// </summary>
/// <param name="emailList">the name of the email list for which you wish to
/// retrieve a subscriber list</param>
/// <returns>a feed containing all of the subscribers to this email list</returns>
public EmailListRecipientFeed RetrieveAllRecipients(string emailList)
{
EmailListRecipientQuery query = new EmailListRecipientQuery(Domain, emailList);
return emailListRecipientService.Query(query);
}
/// <summary>
/// Retrieves a page of at most 100 subscribers to an email list.
/// Email addresses are ordered case-insensitively by ASCII value.
/// </summary>
/// <param name="emailList">the name of the email list for which you
/// are retrieving recipients</param>
/// <param name="startRecipient">the first email address that should
/// appear in your result set</param>
/// <returns>a feed containing the matching subscribers</returns>
public EmailListRecipientFeed RetrievePageOfRecipients(string emailList, string startRecipient)
{
EmailListRecipientQuery query = new EmailListRecipientQuery(Domain, emailList);
query.StartRecipient = startRecipient;
return emailListRecipientService.Query(query);
}
/// <summary>
/// Removes the specified recipient from an email list.
/// </summary>
/// <param name="recipientAddress">the email address that is being removed</param>
/// <param name="emailList">the email address from which the address is being removed</param>
public void RemoveRecipientFromEmailList(string recipientAddress, string emailList)
{
EmailListRecipientQuery query = new EmailListRecipientQuery(Domain, emailList);
query.Recipient = recipientAddress;
emailListRecipientService.Delete(query.Uri);
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.Edm.Library;
namespace Microsoft.Data.Edm.Validation
{
/// <summary>
/// A set of rules to run during validation.
/// </summary>
public sealed class ValidationRuleSet : IEnumerable<ValidationRule>
{
private readonly Dictionary<Type, List<ValidationRule>> rules;
private static readonly ValidationRuleSet BaseRuleSet =
new ValidationRuleSet(new ValidationRule[]
{
ValidationRules.EntityTypeKeyPropertyMustBelongToEntity,
ValidationRules.StructuredTypePropertiesDeclaringTypeMustBeCorrect,
ValidationRules.NamedElementNameMustNotBeEmptyOrWhiteSpace,
ValidationRules.NamedElementNameIsTooLong,
ValidationRules.NamedElementNameIsNotAllowed,
ValidationRules.SchemaElementNamespaceIsNotAllowed,
ValidationRules.SchemaElementNamespaceIsTooLong,
ValidationRules.SchemaElementNamespaceMustNotBeEmptyOrWhiteSpace,
ValidationRules.SchemaElementSystemNamespaceEncountered,
ValidationRules.EntityContainerDuplicateEntityContainerMemberName,
ValidationRules.EntityTypeDuplicatePropertyNameSpecifiedInEntityKey,
ValidationRules.EntityTypeInvalidKeyNullablePart,
ValidationRules.EntityTypeEntityKeyMustBeScalar,
ValidationRules.EntityTypeInvalidKeyKeyDefinedInBaseClass,
ValidationRules.EntityTypeKeyMissingOnEntityType,
ValidationRules.StructuredTypeInvalidMemberNameMatchesTypeName,
ValidationRules.StructuredTypePropertyNameAlreadyDefined,
ValidationRules.StructuralPropertyInvalidPropertyType,
ValidationRules.ComplexTypeInvalidAbstractComplexType,
ValidationRules.ComplexTypeInvalidPolymorphicComplexType,
ValidationRules.FunctionBaseParameterNameAlreadyDefinedDuplicate,
ValidationRules.FunctionImportReturnEntitiesButDoesNotSpecifyEntitySet,
ValidationRules.FunctionImportEntityTypeDoesNotMatchEntitySet,
ValidationRules.ComposableFunctionImportMustHaveReturnType,
ValidationRules.StructuredTypeBaseTypeMustBeSameKindAsDerivedKind,
ValidationRules.RowTypeBaseTypeMustBeNull,
ValidationRules.NavigationPropertyWithRecursiveContainmentTargetMustBeOptional,
ValidationRules.NavigationPropertyWithRecursiveContainmentSourceMustBeFromZeroOrOne,
ValidationRules.NavigationPropertyWithNonRecursiveContainmentSourceMustBeFromOne,
ValidationRules.EntitySetInaccessibleEntityType,
ValidationRules.StructuredTypeInaccessibleBaseType,
ValidationRules.EntityReferenceTypeInaccessibleEntityType,
ValidationRules.TypeReferenceInaccessibleSchemaType,
ValidationRules.EntitySetTypeHasNoKeys,
ValidationRules.FunctionOnlyInputParametersAllowedInFunctions,
ValidationRules.RowTypeMustContainProperties,
ValidationRules.DecimalTypeReferenceScaleOutOfRange,
ValidationRules.BinaryTypeReferenceBinaryMaxLengthNegative,
ValidationRules.StringTypeReferenceStringMaxLengthNegative,
ValidationRules.StructuralPropertyInvalidPropertyTypeConcurrencyMode,
ValidationRules.EnumMemberValueMustHaveSameTypeAsUnderlyingType,
ValidationRules.EnumTypeEnumMemberNameAlreadyDefined,
ValidationRules.FunctionImportBindableFunctionImportMustHaveParameters,
ValidationRules.FunctionImportComposableFunctionImportCannotBeSideEffecting,
ValidationRules.FunctionImportEntitySetExpressionIsInvalid,
ValidationRules.BinaryTypeReferenceBinaryUnboundedNotValidForMaxLength,
ValidationRules.StringTypeReferenceStringUnboundedNotValidForMaxLength,
ValidationRules.ImmediateValueAnnotationElementAnnotationIsValid,
ValidationRules.ValueAnnotationAssertCorrectExpressionType,
ValidationRules.IfExpressionAssertCorrectTestType,
ValidationRules.CollectionExpressionAllElementsCorrectType,
ValidationRules.RecordExpressionPropertiesMatchType,
ValidationRules.NavigationPropertyDependentPropertiesMustBelongToDependentEntity,
ValidationRules.NavigationPropertyInvalidOperationMultipleEndsInAssociation,
ValidationRules.NavigationPropertyEndWithManyMultiplicityCannotHaveOperationsSpecified,
ValidationRules.NavigationPropertyTypeMismatchRelationshipConstraint,
ValidationRules.NavigationPropertyDuplicateDependentProperty,
ValidationRules.NavigationPropertyPrincipalEndMultiplicity,
ValidationRules.NavigationPropertyDependentEndMultiplicity,
ValidationRules.NavigationPropertyCorrectType,
ValidationRules.ImmediateValueAnnotationElementAnnotationHasNameAndNamespace,
ValidationRules.FunctionApplicationExpressionParametersMatchAppliedFunction,
ValidationRules.VocabularyAnnotatableNoDuplicateAnnotations,
ValidationRules.TemporalTypeReferencePrecisionOutOfRange,
ValidationRules.DecimalTypeReferencePrecisionOutOfRange,
ValidationRules.ModelDuplicateEntityContainerName,
ValidationRules.FunctionImportParametersCannotHaveModeOfNone,
ValidationRules.TypeMustNotHaveKindOfNone,
ValidationRules.PrimitiveTypeMustNotHaveKindOfNone,
ValidationRules.PropertyMustNotHaveKindOfNone,
ValidationRules.TermMustNotHaveKindOfNone,
ValidationRules.SchemaElementMustNotHaveKindOfNone,
ValidationRules.EntityContainerElementMustNotHaveKindOfNone,
ValidationRules.PrimitiveValueValidForType,
ValidationRules.EntitySetCanOnlyBeContainedByASingleNavigationProperty,
ValidationRules.EntitySetNavigationMappingMustBeBidirectional,
ValidationRules.EntitySetNavigationPropertyMappingsMustBeUnique,
ValidationRules.TypeAnnotationAssertMatchesTermType,
ValidationRules.TypeAnnotationInaccessibleTerm,
ValidationRules.PropertyValueBindingValueIsCorrectType,
ValidationRules.EnumMustHaveIntegerUnderlyingType,
ValidationRules.ValueAnnotationInaccessibleTerm,
ValidationRules.ElementDirectValueAnnotationFullNameMustBeUnique,
ValidationRules.VocabularyAnnotationInaccessibleTarget,
ValidationRules.ComplexTypeMustContainProperties,
ValidationRules.EntitySetAssociationSetNameMustBeValid,
ValidationRules.NavigationPropertyAssociationEndNameIsValid,
ValidationRules.NavigationPropertyAssociationNameIsValid,
ValidationRules.OnlyEntityTypesCanBeOpen,
ValidationRules.NavigationPropertyEntityMustNotIndirectlyContainItself,
ValidationRules.EntitySetRecursiveNavigationPropertyMappingsMustPointBackToSourceEntitySet,
ValidationRules.EntitySetNavigationPropertyMappingMustPointToValidTargetForProperty,
ValidationRules.DirectValueAnnotationHasXmlSerializableName
});
private static readonly ValidationRuleSet V1RuleSet =
new ValidationRuleSet(
BaseRuleSet,
new ValidationRule[]
{
ValidationRules.NavigationPropertyInvalidToPropertyInRelationshipConstraintBeforeV2,
ValidationRules.FunctionsNotSupportedBeforeV2,
ValidationRules.FunctionImportUnsupportedReturnTypeV1,
ValidationRules.FunctionImportParametersIncorrectTypeBeforeV3,
ValidationRules.FunctionImportIsSideEffectingNotSupportedBeforeV3,
ValidationRules.FunctionImportIsComposableNotSupportedBeforeV3,
ValidationRules.FunctionImportIsBindableNotSupportedBeforeV3,
ValidationRules.EntityTypeEntityKeyMustNotBeBinaryBeforeV2,
ValidationRules.EnumTypeEnumsNotSupportedBeforeV3,
ValidationRules.NavigationPropertyContainsTargetNotSupportedBeforeV3,
ValidationRules.StructuralPropertyNullableComplexType,
ValidationRules.ValueTermsNotSupportedBeforeV3,
ValidationRules.VocabularyAnnotationsNotSupportedBeforeV3,
ValidationRules.OpenTypesNotSupported,
ValidationRules.StreamTypeReferencesNotSupportedBeforeV3,
ValidationRules.SpatialTypeReferencesNotSupportedBeforeV3,
ValidationRules.ModelDuplicateSchemaElementNameBeforeV3,
});
private static readonly ValidationRuleSet V1_1RuleSet =
new ValidationRuleSet(
BaseRuleSet.Where(r => r != ValidationRules.ComplexTypeInvalidAbstractComplexType &&
r != ValidationRules.ComplexTypeInvalidPolymorphicComplexType),
new ValidationRule[]
{
ValidationRules.NavigationPropertyInvalidToPropertyInRelationshipConstraintBeforeV2,
ValidationRules.FunctionsNotSupportedBeforeV2,
ValidationRules.FunctionImportUnsupportedReturnTypeAfterV1,
ValidationRules.FunctionImportIsSideEffectingNotSupportedBeforeV3,
ValidationRules.FunctionImportIsComposableNotSupportedBeforeV3,
ValidationRules.FunctionImportIsBindableNotSupportedBeforeV3,
ValidationRules.EntityTypeEntityKeyMustNotBeBinaryBeforeV2,
ValidationRules.FunctionImportParametersIncorrectTypeBeforeV3,
ValidationRules.EnumTypeEnumsNotSupportedBeforeV3,
ValidationRules.NavigationPropertyContainsTargetNotSupportedBeforeV3,
ValidationRules.ValueTermsNotSupportedBeforeV3,
ValidationRules.VocabularyAnnotationsNotSupportedBeforeV3,
ValidationRules.OpenTypesNotSupported,
ValidationRules.StreamTypeReferencesNotSupportedBeforeV3,
ValidationRules.SpatialTypeReferencesNotSupportedBeforeV3,
ValidationRules.ModelDuplicateSchemaElementNameBeforeV3,
});
private static readonly ValidationRuleSet V1_2RuleSet =
new ValidationRuleSet(
BaseRuleSet.Where(r => r != ValidationRules.ComplexTypeInvalidAbstractComplexType &&
r != ValidationRules.ComplexTypeInvalidPolymorphicComplexType),
new ValidationRule[]
{
ValidationRules.NavigationPropertyInvalidToPropertyInRelationshipConstraintBeforeV2,
ValidationRules.FunctionsNotSupportedBeforeV2,
ValidationRules.FunctionImportUnsupportedReturnTypeAfterV1,
ValidationRules.FunctionImportParametersIncorrectTypeBeforeV3,
ValidationRules.FunctionImportIsSideEffectingNotSupportedBeforeV3,
ValidationRules.FunctionImportIsComposableNotSupportedBeforeV3,
ValidationRules.FunctionImportIsBindableNotSupportedBeforeV3,
ValidationRules.EntityTypeEntityKeyMustNotBeBinaryBeforeV2,
ValidationRules.EnumTypeEnumsNotSupportedBeforeV3,
ValidationRules.NavigationPropertyContainsTargetNotSupportedBeforeV3,
ValidationRules.ValueTermsNotSupportedBeforeV3,
ValidationRules.VocabularyAnnotationsNotSupportedBeforeV3,
ValidationRules.StreamTypeReferencesNotSupportedBeforeV3,
ValidationRules.SpatialTypeReferencesNotSupportedBeforeV3,
ValidationRules.ModelDuplicateSchemaElementNameBeforeV3,
});
private static readonly ValidationRuleSet V2RuleSet =
new ValidationRuleSet(
BaseRuleSet,
new ValidationRule[]
{
ValidationRules.FunctionImportParametersIncorrectTypeBeforeV3,
ValidationRules.FunctionImportUnsupportedReturnTypeAfterV1,
ValidationRules.FunctionImportIsSideEffectingNotSupportedBeforeV3,
ValidationRules.FunctionImportIsComposableNotSupportedBeforeV3,
ValidationRules.FunctionImportIsBindableNotSupportedBeforeV3,
ValidationRules.EnumTypeEnumsNotSupportedBeforeV3,
ValidationRules.NavigationPropertyContainsTargetNotSupportedBeforeV3,
ValidationRules.StructuralPropertyNullableComplexType,
ValidationRules.ValueTermsNotSupportedBeforeV3,
ValidationRules.VocabularyAnnotationsNotSupportedBeforeV3,
ValidationRules.OpenTypesNotSupported,
ValidationRules.StreamTypeReferencesNotSupportedBeforeV3,
ValidationRules.SpatialTypeReferencesNotSupportedBeforeV3,
ValidationRules.ModelDuplicateSchemaElementNameBeforeV3,
});
private static readonly ValidationRuleSet V3RuleSet =
new ValidationRuleSet(
BaseRuleSet,
new ValidationRule[]
{
ValidationRules.FunctionImportUnsupportedReturnTypeAfterV1,
ValidationRules.ModelDuplicateSchemaElementName,
});
/// <summary>
/// Initializes a new instance of the ValidationRuleSet class.
/// </summary>
/// <param name="baseSet">Ruleset whose rules should be contained in this set.</param>
/// <param name="newRules">Additional rules to add to the set.</param>
public ValidationRuleSet(IEnumerable<ValidationRule> baseSet, IEnumerable<ValidationRule> newRules)
: this(EdmUtil.CheckArgumentNull(baseSet, "baseSet").Concat(EdmUtil.CheckArgumentNull(newRules, "newRules")))
{
}
/// <summary>
/// Initializes a new instance of the ValidationRuleSet class.
/// </summary>
/// <param name="rules">Rules to be contained in this ruleset.</param>
public ValidationRuleSet(IEnumerable<ValidationRule> rules)
{
EdmUtil.CheckArgumentNull(rules, "rules");
this.rules = new Dictionary<Type, List<ValidationRule>>();
foreach (ValidationRule rule in rules)
{
this.AddRule(rule);
}
}
/// <summary>
/// Gets the default validation ruleset for the given version.
/// </summary>
/// <param name="version">The EDM version being validated.</param>
/// <returns>The set of rules to validate that the model conforms to the given version.</returns>
public static ValidationRuleSet GetEdmModelRuleSet(Version version)
{
if (version == EdmConstants.EdmVersion1)
{
return V1RuleSet;
}
if (version == EdmConstants.EdmVersion1_1)
{
return V1_1RuleSet;
}
if (version == EdmConstants.EdmVersion1_2)
{
return V1_2RuleSet;
}
if (version == EdmConstants.EdmVersion2)
{
return V2RuleSet;
}
if (version == EdmConstants.EdmVersion3)
{
return V3RuleSet;
}
throw new InvalidOperationException(Edm.Strings.Serializer_UnknownEdmVersion);
}
/// <summary>
/// Gets all of the rules in this ruleset.
/// </summary>
/// <returns>All of the rules in this ruleset.</returns>
public IEnumerator<ValidationRule> GetEnumerator()
{
foreach (List<ValidationRule> ruleList in this.rules.Values)
{
foreach (ValidationRule rule in ruleList)
{
yield return rule;
}
}
}
/// <summary>
/// Gets all of the rules in this ruleset.
/// </summary>
/// <returns>All of the rules in this ruleset.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
internal IEnumerable<ValidationRule> GetRules(Type t)
{
List<ValidationRule> foundRules;
return this.rules.TryGetValue(t, out foundRules) ? foundRules : Enumerable.Empty<ValidationRule>();
}
private void AddRule(ValidationRule rule)
{
List<ValidationRule> typeRules;
if (!this.rules.TryGetValue(rule.ValidatedType, out typeRules))
{
typeRules = new List<ValidationRule>();
this.rules[rule.ValidatedType] = typeRules;
}
if (typeRules.Contains(rule))
{
throw new InvalidOperationException(Edm.Strings.RuleSet_DuplicateRulesExistInRuleSet);
}
typeRules.Add(rule);
}
}
}
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==================================================================== */
using System;
using System.Drawing;
using System.IO;
using NPOI.OpenXml4Net.OPC;
using NPOI.OpenXmlFormats.Dml;
using NPOI.OpenXmlFormats.Dml.Spreadsheet;
using NPOI.OpenXmlFormats.Spreadsheet;
using NPOI.SS.UserModel;
using NPOI.Util;
using System.Xml;
using NPOI.SS.Util;
namespace NPOI.XSSF.UserModel
{
/**
* Represents a picture shape in a SpreadsheetML Drawing.
*
* @author Yegor Kozlov
*/
public class XSSFPicture : XSSFShape, IPicture
{
private static POILogger logger = POILogFactory.GetLogger(typeof(XSSFPicture));
/**
* Column width measured as the number of characters of the maximum digit width of the
* numbers 0, 1, 2, ..., 9 as rendered in the normal style's font. There are 4 pixels of margin
* pAdding (two on each side), plus 1 pixel pAdding for the gridlines.
*
* This value is the same for default font in Office 2007 (Calibry) and Office 2003 and earlier (Arial)
*/
//private static float DEFAULT_COLUMN_WIDTH = 9.140625f;
/**
* A default instance of CTShape used for creating new shapes.
*/
private static CT_Picture prototype = null;
/**
* This object specifies a picture object and all its properties
*/
private CT_Picture ctPicture;
/**
* Construct a new XSSFPicture object. This constructor is called from
* {@link XSSFDrawing#CreatePicture(XSSFClientAnchor, int)}
*
* @param Drawing the XSSFDrawing that owns this picture
*/
public XSSFPicture(XSSFDrawing drawing, CT_Picture ctPicture)
{
this.drawing = drawing;
this.ctPicture = ctPicture;
}
/**
* Returns a prototype that is used to construct new shapes
*
* @return a prototype that is used to construct new shapes
*/
public XSSFPicture(XSSFDrawing drawing, XmlNode ctPicture)
{
this.drawing = drawing;
this.ctPicture =CT_Picture.Parse(ctPicture, POIXMLDocumentPart.NamespaceManager);
}
internal static CT_Picture Prototype()
{
CT_Picture pic = new CT_Picture();
CT_PictureNonVisual nvpr = pic.AddNewNvPicPr();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualDrawingProps nvProps = nvpr.AddNewCNvPr();
nvProps.id = (1);
nvProps.name = ("Picture 1");
nvProps.descr = ("Picture");
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_NonVisualPictureProperties nvPicProps = nvpr.AddNewCNvPicPr();
nvPicProps.AddNewPicLocks().noChangeAspect = true;
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_BlipFillProperties blip = pic.AddNewBlipFill();
blip.AddNewBlip().embed = "";
blip.AddNewStretch().AddNewFillRect();
NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties sppr = pic.AddNewSpPr();
CT_Transform2D t2d = sppr.AddNewXfrm();
CT_PositiveSize2D ext = t2d.AddNewExt();
//should be original picture width and height expressed in EMUs
ext.cx = (0);
ext.cy = (0);
CT_Point2D off = t2d.AddNewOff();
off.x=(0);
off.y=(0);
CT_PresetGeometry2D prstGeom = sppr.AddNewPrstGeom();
prstGeom.prst = (ST_ShapeType.rect);
prstGeom.AddNewAvLst();
prototype = pic;
return prototype;
}
/**
* Link this shape with the picture data
*
* @param rel relationship referring the picture data
*/
internal void SetPictureReference(PackageRelationship rel)
{
ctPicture.blipFill.blip.embed = rel.Id;
}
/**
* Return the underlying CT_Picture bean that holds all properties for this picture
*
* @return the underlying CT_Picture bean
*/
internal CT_Picture GetCTPicture()
{
return ctPicture;
}
/**
* Reset the image to the original size.
*
* <p>
* Please note, that this method works correctly only for workbooks
* with the default font size (Calibri 11pt for .xlsx).
* If the default font is Changed the resized image can be streched vertically or horizontally.
* </p>
*/
public void Resize()
{
Resize(double.MaxValue);
}
/**
* Resize the image proportionally.
*
* @see #resize(double, double)
*/
public void Resize(double scale)
{
Resize(scale, scale);
}
/**
* Resize the image relatively to its current size.
* <p>
* Please note, that this method works correctly only for workbooks
* with the default font size (Calibri 11pt for .xlsx).
* If the default font is changed the resized image can be streched vertically or horizontally.
* </p>
* <p>
* <code>resize(1.0,1.0)</code> keeps the original size,<br/>
* <code>resize(0.5,0.5)</code> resize to 50% of the original,<br/>
* <code>resize(2.0,2.0)</code> resizes to 200% of the original.<br/>
* <code>resize({@link Double#MAX_VALUE},{@link Double#MAX_VALUE})</code> resizes to the dimension of the embedded image.
* </p>
*
* @param scaleX the amount by which the image width is multiplied relative to the original width,
* when set to {@link java.lang.Double#MAX_VALUE} the width of the embedded image is used
* @param scaleY the amount by which the image height is multiplied relative to the original height,
* when set to {@link java.lang.Double#MAX_VALUE} the height of the embedded image is used
*/
public void Resize(double scaleX, double scaleY)
{
IClientAnchor anchor = (XSSFClientAnchor)GetAnchor();
IClientAnchor pref = GetPreferredSize(scaleX, scaleY);
int row2 = anchor.Row1 + (pref.Row2 - pref.Row1);
int col2 = anchor.Col1 + (pref.Col2 - pref.Col1);
anchor.Col2=(col2);
//anchor.Dx1=(0);
anchor.Dx2=(pref.Dx2);
anchor.Row2=(row2);
//anchor.Dy1=(0);
anchor.Dy2=(pref.Dy2);
}
/**
* Calculate the preferred size for this picture.
*
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize()
{
return GetPreferredSize(1);
}
/**
* Calculate the preferred size for this picture.
*
* @param scale the amount by which image dimensions are multiplied relative to the original size.
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize(double scale)
{
return GetPreferredSize(scale, scale);
}
/**
* Calculate the preferred size for this picture.
*
* @param scaleX the amount by which image width is multiplied relative to the original width.
* @param scaleY the amount by which image height is multiplied relative to the original height.
* @return XSSFClientAnchor with the preferred size for this image
*/
public IClientAnchor GetPreferredSize(double scaleX, double scaleY)
{
Size dim = ImageUtils.SetPreferredSize(this, scaleX, scaleY);
CT_PositiveSize2D size2d = ctPicture.spPr.xfrm.ext;
size2d.cx = (dim.Width);
size2d.cy = (dim.Height);
return ClientAnchor;
}
/**
* Return the dimension of this image
*
* @param part the namespace part holding raw picture data
* @param type type of the picture: {@link Workbook#PICTURE_TYPE_JPEG},
* {@link Workbook#PICTURE_TYPE_PNG} or {@link Workbook#PICTURE_TYPE_DIB}
*
* @return image dimension in pixels
*/
protected static Size GetImageDimension(PackagePart part, PictureType type)
{
try
{
//return Image.FromStream(part.GetInputStream()).Size;
//java can only read png,jpeg,dib image
//C# read the image that format defined by PictureType , maybe.
return ImageUtils.GetImageDimension(part.GetInputStream());
}
catch (IOException e)
{
//return a "singulariry" if ImageIO failed to read the image
logger.Log(POILogger.WARN, e);
return new Size();
}
}
/**
* Return the dimension of the embedded image in pixel
*
* @return image dimension in pixels
*/
public Size GetImageDimension()
{
XSSFPictureData picData = PictureData as XSSFPictureData;
return GetImageDimension(picData.GetPackagePart(), picData.PictureType);
}
protected internal override NPOI.OpenXmlFormats.Dml.Spreadsheet.CT_ShapeProperties GetShapeProperties()
{
return ctPicture.spPr;
}
#region IShape Members
public int CountOfAllChildren
{
get { throw new NotImplementedException(); }
}
public int FillColor
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public LineStyle LineStyle
{
get
{
throw new NotImplementedException();
}
set
{
base.LineStyle = value;
}
}
public int LineStyleColor
{
get { throw new NotImplementedException(); }
}
public int LineWidth
{
get
{
throw new NotImplementedException();
}
set
{
base.LineWidth = (value);
}
}
public void SetLineStyleColor(int lineStyleColor)
{
throw new NotImplementedException();
}
#endregion
public IPictureData PictureData
{
get
{
String blipId = ctPicture.blipFill.blip.embed;
return (XSSFPictureData)GetDrawing().GetRelationById(blipId);
}
}
/**
* @return the anchor that is used by this shape.
*/
public IClientAnchor ClientAnchor
{
get
{
XSSFAnchor a = GetAnchor() as XSSFAnchor;
return (a is XSSFClientAnchor) ? (XSSFClientAnchor)a : null;
}
}
/**
* @return the sheet which contains the picture shape
*/
public ISheet Sheet
{
get
{
return (XSSFSheet)this.GetDrawing().GetParent();
}
}
}
}
| |
namespace Fixtures.MirrorRecursiveTypes
{
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Models;
/// <summary>
/// Some cool documentation.
/// </summary>
public partial class RecursiveTypesAPI : ServiceClient<RecursiveTypesAPI>, IRecursiveTypesAPI
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
public RecursiveTypesAPI() : base()
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the RecursiveTypesAPI class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public RecursiveTypesAPI(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.Initialize();
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.BaseUri = new Uri("https://management.azure.com/");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver()
};
DeserializationSettings = new JsonSerializerSettings{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver()
};
}
/// <summary>
/// The Products endpoint returns information about the Uber products offered
/// at a given location. The response includes the display name and other
/// details about each product, and lists the products in the proper display
/// order.
/// </summary>
/// <param name='subscriptionId'>
/// Subscription Id.
/// </param>
/// <param name='resourceGroupName'>
/// Resource Group Id.
/// </param>
/// <param name='apiVersion'>
/// API Id.
/// </param>
/// <param name='body'>
/// API body mody.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<Product>> PostWithHttpMessagesAsync(string subscriptionId, string resourceGroupName, string apiVersion, Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (subscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "subscriptionId");
}
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (apiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "apiVersion");
}
if (body != null)
{
body.Validate();
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("subscriptionId", subscriptionId);
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("body", body);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(invocationId, this, "Post", tracingParameters);
}
// Construct URL
string url = this.BaseUri.AbsoluteUri +
"//subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/Microsoft.Cache/Redis?api-version={apiVersion}";
url = url.Replace("{subscriptionId}", Uri.EscapeDataString(subscriptionId));
url = url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
url = url.Replace("{apiVersion}", Uri.EscapeDataString(apiVersion));
// trim all duplicate forward slashes in the url
url = Regex.Replace(url, "([^:]/)/+", "$1");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = new HttpMethod("POST");
httpRequest.RequestUri = new Uri(url);
// Set Headers
if (customHeaders != null)
{
foreach(var header in customHeaders)
{
httpRequest.Headers.Add(header.Key, header.Value);
}
}
// Serialize Request
string requestContent = JsonConvert.SerializeObject(body, this.SerializationSettings);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
if (!(statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK")))
{
var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", statusCode));
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error errorBody = JsonConvert.DeserializeObject<Error>(responseContent, this.DeserializationSettings);
if (errorBody != null)
{
ex.Body = errorBody;
}
ex.Request = httpRequest;
ex.Response = httpResponse;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
var result = new HttpOperationResponse<Product>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), "OK"))
{
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result.Body = JsonConvert.DeserializeObject<Product>(responseContent, this.DeserializationSettings);
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
using NLog.LayoutRenderers;
using NLog.Targets;
using Xunit.Extensions;
namespace NLog.UnitTests.Config
{
using System;
using System.Globalization;
using System.Threading;
using Xunit;
using NLog.Config;
public class CultureInfoTests : NLogTestBase
{
[Fact]
public void WhenInvariantCultureDefinedThenDefaultCultureIsInvariantCulture()
{
var configuration = XmlLoggingConfiguration.CreateFromXmlString("<nlog useInvariantCulture='true'></nlog>");
Assert.Equal(CultureInfo.InvariantCulture, configuration.DefaultCultureInfo);
}
[Fact]
public void DifferentConfigurations_UseDifferentDefaultCulture()
{
var currentCulture = CultureInfo.CurrentCulture;
try
{
// set the current thread culture to be definitely different from the InvariantCulture
Thread.CurrentThread.CurrentCulture = GetCultureInfo("de-DE");
var configurationTemplate = @"<nlog useInvariantCulture='{0}'>
<targets>
<target name='debug' type='Debug' layout='${{message}}' />
</targets>
<rules>
<logger name='*' writeTo='debug'/>
</rules>
</nlog>";
// configuration with current culture
var configuration1 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, false));
Assert.Null(configuration1.DefaultCultureInfo);
// configuration with invariant culture
var configuration2 = XmlLoggingConfiguration.CreateFromXmlString(string.Format(configurationTemplate, true));
Assert.Equal(CultureInfo.InvariantCulture, configuration2.DefaultCultureInfo);
Assert.NotEqual(configuration1.DefaultCultureInfo, configuration2.DefaultCultureInfo);
var testNumber = 3.14;
var testDate = DateTime.Now;
const string formatString = "{0},{1:d}";
AssertMessageFormattedWithCulture(configuration1, CultureInfo.CurrentCulture, formatString, testNumber, testDate);
AssertMessageFormattedWithCulture(configuration2, CultureInfo.InvariantCulture, formatString, testNumber, testDate);
}
finally
{
// restore current thread culture
Thread.CurrentThread.CurrentCulture = currentCulture;
}
}
private void AssertMessageFormattedWithCulture(LoggingConfiguration configuration, CultureInfo culture, string formatString, params object[] parameters)
{
var expected = string.Format(culture, formatString, parameters);
using (var logFactory = new LogFactory(configuration))
{
var logger = logFactory.GetLogger("test");
logger.Debug(formatString, parameters);
Assert.Equal(expected, GetDebugLastMessage("debug", configuration));
}
}
[Fact]
public void EventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new EventPropertiesLayoutRenderer();
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void EventContextRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
#pragma warning disable 618
var renderer = new EventContextLayoutRenderer();
#pragma warning restore 618
renderer.Item = "ADouble";
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Fact]
public void ProcessInfoLayoutRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "."; // dot as date separator (01.10.2008)
string output = string.Empty;
var logEventInfo = CreateLogEventInfo(cultureName);
if (IsTravis())
{
Console.WriteLine("[SKIP] CultureInfoTests.ProcessInfoLayoutRendererCultureTest because we are running in Travis");
}
else
{
var renderer = new ProcessInfoLayoutRenderer();
renderer.Property = ProcessInfoProperty.StartTime;
renderer.Format = "d";
output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain("/", output);
Assert.DoesNotContain("-", output);
}
var renderer2 = new ProcessInfoLayoutRenderer();
renderer2.Property = ProcessInfoProperty.PriorityClass;
renderer2.Format = "d";
output = renderer2.Render(logEventInfo);
Assert.True(output.Length >= 1);
Assert.True("012345678".IndexOf(output[0]) > 0);
}
[Fact]
public void AllEventPropRendererCultureTest()
{
string cultureName = "de-DE";
string expected = "ADouble=1,23"; // with decimal comma
var logEventInfo = CreateLogEventInfo(cultureName);
logEventInfo.Properties["ADouble"] = 1.23;
var renderer = new AllEventPropertiesLayoutRenderer();
string output = renderer.Render(logEventInfo);
Assert.Equal(expected, output);
}
[Theory]
[InlineData(typeof(TimeLayoutRenderer))]
[InlineData(typeof(ProcessTimeLayoutRenderer))]
public void DateTimeCultureTest(Type rendererType)
{
string cultureName = "de-DE";
string expected = ","; // decimal comma as separator for ticks
var logEventInfo = CreateLogEventInfo(cultureName);
var renderer = Activator.CreateInstance(rendererType) as LayoutRenderer;
Assert.NotNull(renderer);
string output = renderer.Render(logEventInfo);
Assert.Contains(expected, output);
Assert.DoesNotContain(".", output);
}
private static LogEventInfo CreateLogEventInfo(string cultureName)
{
var logEventInfo = new LogEventInfo(
LogLevel.Info,
"SomeName",
CultureInfo.GetCultureInfo(cultureName),
"SomeMessage",
null);
return logEventInfo;
}
/// <summary>
/// expected: exactly the same exception message + stack trace regardless of the CurrentUICulture
/// </summary>
[Fact]
public void ExceptionTest()
{
var target = new MemoryTarget { Layout = @"${exception:format=tostring}" };
SimpleConfigurator.ConfigureForTargetLogging(target);
var logger = LogManager.GetCurrentClassLogger();
try
{
throw new InvalidOperationException();
}
catch (Exception ex)
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
logger.Error(ex, "");
#if !NETSTANDARD
Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false);
Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false);
#endif
logger.Error(ex, "");
Assert.Equal(2, target.Logs.Count);
Assert.NotNull(target.Logs[0]);
Assert.NotNull(target.Logs[1]);
Assert.Equal(target.Logs[0], target.Logs[1]);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Razor.Extensions.Version2_X
{
public class ViewComponentTagHelperDescriptorFactoryTest
{
private static readonly Assembly _assembly = typeof(ViewComponentTagHelperDescriptorFactoryTest).GetTypeInfo().Assembly;
[Fact]
public void CreateDescriptor_UnderstandsStringParameters()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(StringParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__StringParameterViewComponentTagHelper",
typeof(StringParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__StringParameterViewComponentTagHelper")
.DisplayName("StringParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:string-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("foo"))
.RequireAttributeDescriptor(attribute => attribute.Name("bar")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("foo")
.PropertyName("foo")
.TypeName(typeof(string).FullName)
.DisplayName("string StringParameterViewComponentTagHelper.foo"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("bar")
.PropertyName("bar")
.TypeName(typeof(string).FullName)
.DisplayName("string StringParameterViewComponentTagHelper.bar"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "StringParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_UnderstandsVariousParameterTypes()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(VariousParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__VariousParameterViewComponentTagHelper",
typeof(VariousParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__VariousParameterViewComponentTagHelper")
.DisplayName("VariousParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:various-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("test-enum"))
.RequireAttributeDescriptor(attribute => attribute.Name("test-string"))
.RequireAttributeDescriptor(attribute => attribute.Name("baz")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("test-enum")
.PropertyName("testEnum")
.TypeName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum))
.AsEnum()
.DisplayName(typeof(VariousParameterViewComponent).FullName + "." + nameof(VariousParameterViewComponent.TestEnum) + " VariousParameterViewComponentTagHelper.testEnum"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("test-string")
.PropertyName("testString")
.TypeName(typeof(string).FullName)
.DisplayName("string VariousParameterViewComponentTagHelper.testString"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("baz")
.PropertyName("baz")
.TypeName(typeof(int).FullName)
.DisplayName("int VariousParameterViewComponentTagHelper.baz"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "VariousParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_UnderstandsGenericParameters()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(GenericParameterViewComponent).FullName);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__GenericParameterViewComponentTagHelper",
typeof(GenericParameterViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__GenericParameterViewComponentTagHelper")
.DisplayName("GenericParameterViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:generic-parameter")
.RequireAttributeDescriptor(attribute => attribute.Name("foo")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("foo")
.PropertyName("Foo")
.TypeName("System.Collections.Generic.List<System.String>")
.DisplayName("System.Collections.Generic.List<System.String> GenericParameterViewComponentTagHelper.Foo"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("bar")
.PropertyName("Bar")
.TypeName("System.Collections.Generic.Dictionary<System.String, System.Int32>")
.AsDictionaryAttribute("bar-", typeof(int).FullName)
.DisplayName("System.Collections.Generic.Dictionary<System.String, System.Int32> GenericParameterViewComponentTagHelper.Bar"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "GenericParameter")
.Build();
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_ForSyncViewComponentWithInvokeInBaseType_Works()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__SyncDerivedViewComponentTagHelper",
typeof(SyncDerivedViewComponent).GetTypeInfo().Assembly.GetName().Name)
.TypeName("__Generated__SyncDerivedViewComponentTagHelper")
.DisplayName("SyncDerivedViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule =>
rule
.RequireTagName("vc:sync-derived")
.RequireAttributeDescriptor(attribute => attribute.Name("foo"))
.RequireAttributeDescriptor(attribute => attribute.Name("bar")))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("foo")
.PropertyName("foo")
.TypeName(typeof(string).FullName)
.DisplayName("string SyncDerivedViewComponentTagHelper.foo"))
.BoundAttributeDescriptor(attribute =>
attribute
.Name("bar")
.PropertyName("bar")
.TypeName(typeof(string).FullName)
.DisplayName("string SyncDerivedViewComponentTagHelper.bar"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "SyncDerived")
.Build();
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncDerivedViewComponent).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_ForAsyncViewComponentWithInvokeInBaseType_Works()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var expectedDescriptor = TagHelperDescriptorBuilder.Create(
ViewComponentTagHelperConventions.Kind,
"__Generated__AsyncDerivedViewComponentTagHelper",
typeof(AsyncDerivedViewComponent).Assembly.GetName().Name)
.TypeName("__Generated__AsyncDerivedViewComponentTagHelper")
.DisplayName("AsyncDerivedViewComponentTagHelper")
.TagMatchingRuleDescriptor(rule => rule.RequireTagName("vc:async-derived"))
.AddMetadata(ViewComponentTagHelperMetadata.Name, "AsyncDerived")
.Build();
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncDerivedViewComponent).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Equal(expectedDescriptor, descriptor, TagHelperDescriptorComparer.Default);
}
[Fact]
public void CreateDescriptor_AddsDiagnostic_ForViewComponentWithNoInvokeMethod()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(ViewComponentWithoutInvokeMethod).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_CannotFindMethod.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_AddsDiagnostic_ForViewComponentWithNoInstanceInvokeMethod()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(StaticInvokeAsyncViewComponent).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_CannotFindMethod.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_AddsDiagnostic_ForViewComponentWithNoPublicInvokeMethod()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(NonPublicInvokeAsyncViewComponent).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_CannotFindMethod.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_UnderstandsGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Empty(descriptor.GetAllDiagnostics());
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_UnderstandsNonGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithNonGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
Assert.Empty(descriptor.GetAllDiagnostics());
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_DoesNotUnderstandVoid()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithString).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_AsyncMethod_ShouldReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvokeAsync_DoesNotUnderstandString()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(AsyncViewComponentWithString).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_AsyncMethod_ShouldReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandVoid()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithVoid).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_ShouldReturnValue.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandNonGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithNonGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_CannotReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponentWithInvoke_DoesNotUnderstandGenericTask()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(SyncViewComponentWithGenericTask).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_SyncMethod_CannotReturnTask.Id, diagnostic.Id);
}
[Fact]
public void CreateDescriptor_ForViewComponent_WithAmbiguousMethods()
{
// Arrange
var testCompilation = TestCompilation.Create(_assembly);
var factory = new ViewComponentTagHelperDescriptorFactory(testCompilation);
var viewComponent = testCompilation.GetTypeByMetadataName(typeof(DerivedViewComponentWithAmbiguity).FullName);
// Act
var descriptor = factory.CreateDescriptor(viewComponent);
// Assert
var diagnostic = Assert.Single(descriptor.GetAllDiagnostics());
Assert.Equal(RazorExtensionsDiagnosticFactory.ViewComponent_AmbiguousMethods.Id, diagnostic.Id);
}
}
public class StringParameterViewComponent
{
public string Invoke(string foo, string bar) => null;
}
public class VariousParameterViewComponent
{
public string Invoke(TestEnum testEnum, string testString, int baz = 5) => null;
public enum TestEnum
{
A = 1,
B = 2,
C = 3
}
}
public class GenericParameterViewComponent
{
public string Invoke(List<string> Foo, Dictionary<string, int> Bar) => null;
}
public class ViewComponentWithoutInvokeMethod
{
}
public class AsyncViewComponentWithGenericTask
{
public Task<string> InvokeAsync() => null;
}
public class AsyncViewComponentWithNonGenericTask
{
public Task InvokeAsync() => null;
}
public class AsyncViewComponentWithVoid
{
public void InvokeAsync() { }
}
public class AsyncViewComponentWithString
{
public string InvokeAsync() => null;
}
public class SyncViewComponentWithVoid
{
public void Invoke() { }
}
public class SyncViewComponentWithNonGenericTask
{
public Task Invoke() => null;
}
public class SyncViewComponentWithGenericTask
{
public Task<string> Invoke() => null;
}
public class SyncDerivedViewComponent : StringParameterViewComponent
{
}
public class AsyncDerivedViewComponent : AsyncViewComponentWithNonGenericTask
{
}
public class DerivedViewComponentWithAmbiguity : AsyncViewComponentWithNonGenericTask
{
public string Invoke() => null;
}
public class StaticInvokeAsyncViewComponent
{
public static Task<string> InvokeAsync() => null;
}
public class NonPublicInvokeAsyncViewComponent
{
protected Task<string> InvokeAsync() => null;
}
}
| |
using System;
using UnityEngine;
using JuloUtil;
namespace TurtleIsland {
public class Character : TurtleIslandObject {
public static int EAST = +1;
public static int WEST = -1;
[HideInInspector]
public int teamId;
[HideInInspector]
public int life;
[HideInInspector]
public int orientation = EAST;
[HideInInspector]
public bool isSkeleton = false;
public LifeDisplay display;
private Controller controller = null;
private float walkForce = 0f;
private Transform _shotPoint;
public Transform shotPoint {
get {
if(_shotPoint == null)
_shotPoint = JuloFind.byName<Transform>("ShotPoint", this);
return _shotPoint;
}
}
private SpriteRenderer _renderer;
private new SpriteRenderer renderer {
get {
if(_renderer == null)
_renderer = JuloFind.byName<SpriteRenderer>("Renderer", this);
return _renderer;
}
}
private SpriteRenderer _minimapRenderer;
public SpriteRenderer minimapRenderer {
get {
if(_minimapRenderer == null) {
_minimapRenderer = JuloFind.byName<SpriteRenderer>("MinimapRenderer", this);
}
return _minimapRenderer;
}
}
private Target _target;
public Target target {
get {
if(_target == null)
_target = JuloFind.byName<Target>("Target", this);
return _target;
}
}
private Animator _anim;
private Animator anim {
get {
if(_anim == null)
_anim = GetComponent<Animator>();
return _anim;
}
}
/*
public LifeDisplay display {
get {
if(_display == null) {
_display = JuloFind.byName<LifeDisplay>("Display", this);
return _display;
}
}
*/
public override void onInit() {
if(display == null) {
throw new ApplicationException("No life display");
}
Color teamColor = game.getColorForTeam(teamId);
display.GetComponent<FollowDisplay>().target = this.transform;
display.transform.SetParent(game.env.hk.displayContainer.transform, false);
display.init(life, teamColor);
JuloFind.byName<SpriteRenderer>("MinimapRenderer", this).color = teamColor;
target.hide();
}
bool physicallyUpdated = false;
void FixedUpdate() {
physicallyUpdated = true;
}
public override void onStep() {
if(physicallyUpdated) {
Vector2 v = rb.velocity;
float hAxis = Math.Abs(walkForce);
float hSpeed = Math.Abs(v.x);
float speed = v.magnitude;
anim.SetBool("grounded", isGrounded());
anim.SetBool("alive", isAlive());
anim.SetFloat("hAxis", hAxis);
anim.SetFloat("hSpeed", hSpeed);
anim.SetFloat("speed", speed);
walkForce = 0f;
/*
if(this == game.currentCharacter) {
Debug.Log(String.Format(
"{0}, {1} ({2})",
JuloMath.floatToString(hSpeed, JuloMath.TruncateMethod.ROUND, 4),
JuloMath.floatToString(speed, JuloMath.TruncateMethod.ROUND, 4),
physicallyUpdated
));
}
*/
}
if(controller != null) {
physicallyUpdated = false;
controller.step();
}
}
public override bool isIdle() {
return sinked || isSkeleton || isQuiet();
}
public bool isAlive() {
return life > 0;
}
public bool isGrounded() {
// TODO check if should be localRotation
float rot = transform.rotation.eulerAngles.z;
bool ret = rot < 90f || rot > 270f;
return ret;
}
public bool isReady() {
return isActive() && isAlive() && isGrounded();
}
public bool isLocked() {
return isQuiet() && !isGrounded();
}
public bool isLeft() {
return teamId == TurtleIsland.LeftTeamId;
}
public static Quaternion rotationQuat = Quaternion.Euler(0f, 180f, 0f);
public void flip() {
orientation *= -1;
target.orientation = orientation;
transform.rotation *= rotationQuat;
}
public bool hit(int damage) {
if(!isAlive() || damage <= 0) {
return false;
} else {
life -= damage;
display.showDamage(damage);
if(life <= 0) {
life = 0;
return true;
} else {
return false;
}
}
}
public void applyDamage() {
if(display.isActive())
display.applyDamage();
}
public void play(Controller controller) {
this.controller = controller;
controller.play(this);
target.reset();
target.show();
}
public void stop() {
controller = null;
target.hide();
}
public void dead() {
isSkeleton = true;
anim.SetTrigger("dead");
}
public void celebrate() {
anim.SetTrigger("celebrate");
}
public void charge() {
anim.SetTrigger("charge");
}
public void discharge() {
anim.SetTrigger("discharge");
target.hide();
}
public void walk(float walkForce) {
if(orientation != Mathf.Sign(walkForce)) {
flip();
} else {
rb.velocity = new Vector2(walkForce, rb.velocity.y);
}
this.walkForce = walkForce;
}
public override void kill() {
display.deactivate();
target.hide();
life = 0;
}
public override void onDestroy() {
GameObject.Destroy(display.gameObject);
}
protected override bool isSinkable() {
return true;
}
public float localZ() {
return transform.rotation.eulerAngles.z;
}
public float getTargetWorldAngle() {
float ret = target.transform.rotation.eulerAngles.z;
return orientation == EAST ? ret : 180f - ret;
}
public void moveTarget(float angularVelocity) {
float angleDelta = angularVelocity * Time.deltaTime;
target.rotate(angleDelta);
}
public int getTeamId() {
return teamId;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
namespace Microsoft.Azure.Management.Network.Fluent
{
using Microsoft.Azure.Management.Network.Fluent.Network.Definition;
using Microsoft.Azure.Management.Network.Fluent.Network.Update;
using Microsoft.Azure.Management.Network.Fluent.Subnet.Definition;
using Microsoft.Azure.Management.Network.Fluent.Subnet.Update;
using Microsoft.Azure.Management.Network.Fluent.Subnet.UpdateDefinition;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update;
using System.Collections.Generic;
internal partial class SubnetImpl
{
/// <summary>
/// Gets the services that has access to the subnet.
/// </summary>
System.Collections.Generic.IReadOnlyDictionary<Models.ServiceEndpointType, System.Collections.Generic.List<Microsoft.Azure.Management.ResourceManager.Fluent.Core.Region>> Microsoft.Azure.Management.Network.Fluent.ISubnetBeta.ServicesWithAccess
{
get
{
return this.ServicesWithAccess();
}
}
/// <summary>
/// Specifies a service endpoint to enable access from.
/// </summary>
/// <param name="service">The service type.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithServiceEndpoint<Network.Definition.IWithCreateAndSubnet>.WithAccessFromService(ServiceEndpointType service)
{
return this.WithAccessFromService(service);
}
/// <summary>
/// Specifies a service endpoint to enable access from.
/// </summary>
/// <param name="service">The service type.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithServiceEndpoint<Network.Update.IUpdate>.WithAccessFromService(ServiceEndpointType service)
{
return this.WithAccessFromService(service);
}
/// <summary>
/// Specifies a service endpoint to enable access from.
/// </summary>
/// <param name="service">The service type.</param>
/// <return>The next stage of the definition.</return>
Subnet.Update.IUpdate Subnet.Update.IWithServiceEndpoint.WithAccessFromService(ServiceEndpointType service)
{
return this.WithAccessFromService(service);
}
/// <summary>
/// Specifies that existing access from a service endpoint should be removed.
/// </summary>
/// <param name="service">The service type.</param>
/// <return>The next stage of the definition.</return>
Subnet.Update.IUpdate Subnet.Update.IWithServiceEndpoint.WithoutAccessFromService(ServiceEndpointType service)
{
return this.WithoutAccessFromService(service);
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="resourceId">The resource ID of an existing route table.</param>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithRouteTable.WithExistingRouteTable(string resourceId)
{
return this.WithExistingRouteTable(resourceId);
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="routeTable">An existing route table to associate.</param>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithRouteTable.WithExistingRouteTable(IRouteTable routeTable)
{
return this.WithExistingRouteTable(routeTable);
}
/// <summary>
/// Removes the association with a route table, if any.
/// </summary>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithRouteTable.WithoutRouteTable()
{
return this.WithoutRouteTable();
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="nsg">The network security group to assign.</param>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithNetworkSecurityGroup.WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
{
return this.WithExistingNetworkSecurityGroup(nsg);
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="resourceId">The resource ID of the network security group.</param>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithNetworkSecurityGroup.WithExistingNetworkSecurityGroup(string resourceId)
{
return this.WithExistingNetworkSecurityGroup(resourceId);
}
/// <summary>
/// Removes the association of this subnet with any network security group.
/// </summary>
/// <return>The next stage of the update.</return>
Subnet.Update.IUpdate Subnet.Update.IWithNetworkSecurityGroup.WithoutNetworkSecurityGroup()
{
return this.WithoutNetworkSecurityGroup();
}
/// <return>
/// The route table associated with this subnet, if any
/// Note that this method will result in a call to Azure each time it is invoked.
/// </return>
Microsoft.Azure.Management.Network.Fluent.IRouteTable Microsoft.Azure.Management.Network.Fluent.ISubnet.GetRouteTable()
{
return this.GetRouteTable();
}
/// <summary>
/// Gets the address space prefix, in CIDR notation, assigned to this subnet.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.ISubnet.AddressPrefix
{
get
{
return this.AddressPrefix();
}
}
/// <return>
/// Network interface IP configurations that are associated with this subnet
/// Note that this call may result in multiple calls to Azure to fetch all the referenced interfaces each time it is invoked.
/// </return>
/// <deprecated>Use Subnet.listNetworkInterfaceIPConfigurations() instead.</deprecated>
System.Collections.Generic.ISet<Microsoft.Azure.Management.Network.Fluent.INicIPConfiguration> Microsoft.Azure.Management.Network.Fluent.ISubnet.GetNetworkInterfaceIPConfigurations()
{
return this.GetNetworkInterfaceIPConfigurations();
}
/// <summary>
/// Gets number of network interface IP configurations associated with this subnet.
/// </summary>
int Microsoft.Azure.Management.Network.Fluent.ISubnet.NetworkInterfaceIPConfigurationCount
{
get
{
return this.NetworkInterfaceIPConfigurationCount();
}
}
/// <summary>
/// Gets the resource ID of the network security group associated with this subnet, if any.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.ISubnet.NetworkSecurityGroupId
{
get
{
return this.NetworkSecurityGroupId();
}
}
/// <return>
/// Network interface IP configurations that are associated with this subnet
/// Note that this call may result in multiple calls to Azure to fetch all the referenced interfaces each time it is invoked.
/// </return>
System.Collections.Generic.IReadOnlyCollection<Microsoft.Azure.Management.Network.Fluent.INicIPConfiguration> Microsoft.Azure.Management.Network.Fluent.ISubnet.ListNetworkInterfaceIPConfigurations()
{
return this.ListNetworkInterfaceIPConfigurations();
}
/// <summary>
/// Gets the resource ID of the route table associated with this subnet, if any.
/// </summary>
string Microsoft.Azure.Management.Network.Fluent.ISubnet.RouteTableId
{
get
{
return this.RouteTableId();
}
}
/// <return>
/// The network security group associated with this subnet, if any
/// Note that this method will result in a call to Azure each time it is invoked.
/// </return>
Microsoft.Azure.Management.Network.Fluent.INetworkSecurityGroup Microsoft.Azure.Management.Network.Fluent.ISubnet.GetNetworkSecurityGroup()
{
return this.GetNetworkSecurityGroup();
}
/// <return>Available private IP addresses within this network.</return>
System.Collections.Generic.ISet<string> Microsoft.Azure.Management.Network.Fluent.ISubnetBeta.ListAvailablePrivateIPAddresses()
{
return this.ListAvailablePrivateIPAddresses();
}
/// <summary>
/// Gets the name of the resource.
/// </summary>
string Microsoft.Azure.Management.ResourceManager.Fluent.Core.IHasName.Name
{
get
{
return this.Name();
}
}
/// <summary>
/// Specifies the IP address space of the subnet, within the address space of the network.
/// </summary>
/// <param name="cidr">The IP address space prefix using the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithAddressPrefix<Network.Definition.IWithCreateAndSubnet>.WithAddressPrefix(string cidr)
{
return this.WithAddressPrefix(cidr);
}
/// <summary>
/// Specifies the IP address space of the subnet, within the address space of the network.
/// </summary>
/// <param name="cidr">The IP address space prefix using the CIDR notation.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithAddressPrefix<Network.Update.IUpdate>.WithAddressPrefix(string cidr)
{
return this.WithAddressPrefix(cidr);
}
/// <summary>
/// Attaches the child definition to the parent resource update.
/// </summary>
/// <return>The next stage of the parent definition.</return>
Network.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<Network.Update.IUpdate>.Attach()
{
return this.Attach();
}
/// <summary>
/// Attaches the child definition to the parent resource definiton.
/// </summary>
/// <return>The next stage of the parent definition.</return>
Network.Definition.IWithCreateAndSubnet Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<Network.Definition.IWithCreateAndSubnet>.Attach()
{
return this.Attach();
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="resourceId">The resource ID of an existing route table.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithRouteTable<Network.Definition.IWithCreateAndSubnet>.WithExistingRouteTable(string resourceId)
{
return this.WithExistingRouteTable(resourceId);
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="routeTable">An existing route table to associate.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithRouteTable<Network.Definition.IWithCreateAndSubnet>.WithExistingRouteTable(IRouteTable routeTable)
{
return this.WithExistingRouteTable(routeTable);
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="resourceId">The resource ID of an existing route table.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithRouteTable<Network.Update.IUpdate>.WithExistingRouteTable(string resourceId)
{
return this.WithExistingRouteTable(resourceId);
}
/// <summary>
/// Specifies an existing route table to associate with the subnet.
/// </summary>
/// <param name="routeTable">An existing route table to associate.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithRouteTable<Network.Update.IUpdate>.WithExistingRouteTable(IRouteTable routeTable)
{
return this.WithExistingRouteTable(routeTable);
}
/// <summary>
/// Specifies the IP address space of the subnet, within the address space of the network.
/// </summary>
/// <param name="cidr">The IP address space prefix using the CIDR notation.</param>
/// <return>The next stage.</return>
Subnet.Update.IUpdate Subnet.Update.IWithAddressPrefix.WithAddressPrefix(string cidr)
{
return this.WithAddressPrefix(cidr);
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="nsg">The network security group to assign.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithNetworkSecurityGroup<Network.Definition.IWithCreateAndSubnet>.WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
{
return this.WithExistingNetworkSecurityGroup(nsg);
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="resourceId">The resource ID of the network security group.</param>
/// <return>The next stage of the definition.</return>
Subnet.Definition.IWithAttach<Network.Definition.IWithCreateAndSubnet> Subnet.Definition.IWithNetworkSecurityGroup<Network.Definition.IWithCreateAndSubnet>.WithExistingNetworkSecurityGroup(string resourceId)
{
return this.WithExistingNetworkSecurityGroup(resourceId);
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="nsg">The network security group to assign.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithNetworkSecurityGroup<Network.Update.IUpdate>.WithExistingNetworkSecurityGroup(INetworkSecurityGroup nsg)
{
return this.WithExistingNetworkSecurityGroup(nsg);
}
/// <summary>
/// Assigns an existing network security group to this subnet.
/// </summary>
/// <param name="resourceId">The resource ID of the network security group.</param>
/// <return>The next stage of the definition.</return>
Subnet.UpdateDefinition.IWithAttach<Network.Update.IUpdate> Subnet.UpdateDefinition.IWithNetworkSecurityGroup<Network.Update.IUpdate>.WithExistingNetworkSecurityGroup(string resourceId)
{
return this.WithExistingNetworkSecurityGroup(resourceId);
}
}
}
| |
/*
Copyright (c) 2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Reflection;
using System.Xml;
using System.Configuration;
using PHP.Core.Reflection;
using PHP.Core.Emit;
using System.Diagnostics;
#if SILVERLIGHT
using PHP.CoreCLR;
using System.Windows.Browser;
#else
using System.Web;
#endif
namespace PHP.Core
{
[DebuggerNonUserCode]
public sealed partial class ApplicationContext
{
#region Properties
/// <summary>
/// Whether full reflection of loaded libraries should be postponed until really needed.
/// Set to <B>false</B> by command line compiler (phpc) and web server manager as they both need
/// to compile source files.
/// </summary>
public bool LazyFullReflection { get { return lazyFullReflection; } }
private bool lazyFullReflection;
public Dictionary<string, DTypeDesc>/*!*/ Types { get { Debug.Assert(types != null); return types; } }
private readonly Dictionary<string, DTypeDesc> types;
public Dictionary<string, DRoutineDesc>/*!*/ Functions { get { Debug.Assert(functions != null); return functions; } }
private readonly Dictionary<string, DRoutineDesc> functions;
public DualDictionary<string, DConstantDesc>/*!*/ Constants { get { Debug.Assert(constants != null); return constants; } }
private readonly DualDictionary<string, DConstantDesc> constants;
/// <summary>
/// Associated assembly loader.
/// </summary>
/// <exception cref="InvalidOperationException">Context is readonly.</exception>
public AssemblyLoader/*!*/ AssemblyLoader
{
get
{
Debug.Assert(assemblyLoader != null, "Empty application context doesn't have a loader.");
return assemblyLoader;
}
}
private readonly AssemblyLoader assemblyLoader;
/// <summary>
/// Assembly builder where compiled pieces of eval'd code are stored.
/// </summary>
internal TransientAssemblyBuilder/*!*/ TransientAssemblyBuilder
{
get
{
if (transientAssemblyBuilder == null)
throw new InvalidOperationException();
return transientAssemblyBuilder;
}
}
private readonly TransientAssemblyBuilder transientAssemblyBuilder;
public bool HasTransientAssemblyBuilder { get { return transientAssemblyBuilder != null; } }
/// <summary>
/// Delegate checking for script existance. Created lazily, valid across all the requests on this <see cref="ApplicationContext"/>.
/// </summary>
private Predicate<FullPath> fileExists = null;
#endregion
#region Default Contexts
private static object/*!*/ mutex = new object();
/// <summary>
/// Default context.
/// </summary>
public static ApplicationContext/*!*/ Default
{
get
{
if (_defaultContext == null)
DefineDefaultContext(true, false, true);
return _defaultContext;
}
}
private static ApplicationContext _defaultContext; // lazy
public static bool DefineDefaultContext(bool lazyFullReflection, bool reflectionOnly, bool createTransientBuilder)
{
bool created = false;
if (_defaultContext == null)
{
lock (mutex)
{
if (_defaultContext == null)
{
_defaultContext = new ApplicationContext(lazyFullReflection, reflectionOnly, createTransientBuilder);
created = true;
}
}
}
return created;
}
internal static readonly ApplicationContext/*!*/ Empty = new ApplicationContext();
#endregion
#region Construction
private ApplicationContext()
{
}
public ApplicationContext(bool lazyFullReflection, bool reflectionOnly, bool createTransientBuilder)
{
this.lazyFullReflection = lazyFullReflection;
this.assemblyLoader = new AssemblyLoader(this, reflectionOnly);
this.transientAssemblyBuilder = createTransientBuilder ? new TransientAssemblyBuilder(this) : null;
this.types = new Dictionary<string, DTypeDesc>(StringComparer.OrdinalIgnoreCase);
this.functions = new Dictionary<string, DRoutineDesc>(StringComparer.OrdinalIgnoreCase);
this.constants = new DualDictionary<string, DConstantDesc>(null, StringComparer.OrdinalIgnoreCase);
#if !SILVERLIGHT
this.scriptLibraryDatabase = new ScriptLibraryDatabase(this);
#endif
PopulateTables();
}
#endregion
#region Initialization
private void PopulateTables()
{
// primitive types (prefixed by '@' to prevent ambiguities with identifiers, e.g. i'Array'):
types.Add("@" + QualifiedName.Integer.Name.Value, DTypeDesc.IntegerTypeDesc);
types.Add("@" + QualifiedName.Boolean.Name.Value, DTypeDesc.BooleanTypeDesc);
types.Add("@" + QualifiedName.LongInteger.Name.Value, DTypeDesc.LongIntegerTypeDesc);
types.Add("@" + QualifiedName.Double.Name.Value, DTypeDesc.DoubleTypeDesc);
types.Add("@" + QualifiedName.String.Name.Value, DTypeDesc.StringTypeDesc);
types.Add("@" + QualifiedName.Resource.Name.Value, DTypeDesc.ResourceTypeDesc);
types.Add("@" + QualifiedName.Array.Name.Value, DTypeDesc.ArrayTypeDesc);
types.Add("@" + QualifiedName.Object.Name.Value, DTypeDesc.ObjectTypeDesc);
// types implemented in Core
Func<Type, DTypeDesc> addType = (x) =>
{
var typedesc = DTypeDesc.Create(x);
types.Add(x.Name, typedesc);
return typedesc;
};
addType(typeof(Library.stdClass));
addType(typeof(Library.__PHP_Incomplete_Class));
addType(typeof(Library.EventClass<>));
addType(typeof(Library.SPL.Countable));
addType(typeof(Library.SPL.ArrayAccess));
addType(typeof(Library.SPL.SplFixedArray));
addType(typeof(Library.SPL.ArrayObject));
addType(typeof(Library.SPL.Serializable));
addType(typeof(Library.SPL.SplObjectStorage));
addType(typeof(Library.SPL.SplObserver));
addType(typeof(Library.SPL.SplSubject));
addType(typeof(Library.SPL.Closure));
// Reflection:
AddExportMethod(addType(typeof(Library.SPL.Reflector)));
addType(typeof(Library.SPL.Reflection));
addType(typeof(Library.SPL.ReflectionClass));
addType(typeof(Library.SPL.ReflectionFunctionAbstract));
addType(typeof(Library.SPL.ReflectionFunction));
addType(typeof(Library.SPL.ReflectionMethod));
addType(typeof(Library.SPL.ReflectionProperty));
addType(typeof(Library.SPL.ReflectionException));
// Iterators:
addType(typeof(Library.SPL.Traversable));
addType(typeof(Library.SPL.Iterator));
addType(typeof(Library.SPL.IteratorAggregate));
addType(typeof(Library.SPL.SeekableIterator));
addType(typeof(Library.SPL.OuterIterator));
addType(typeof(Library.SPL.RecursiveIterator));
addType(typeof(Library.SPL.ArrayIterator));
addType(typeof(Library.SPL.EmptyIterator));
addType(typeof(Library.SPL.IteratorIterator));
addType(typeof(Library.SPL.AppendIterator));
addType(typeof(Library.SPL.FilterIterator));
addType(typeof(Library.SPL.RecursiveArrayIterator));
addType(typeof(Library.SPL.RecursiveIteratorIterator));
// Exception:
addType(typeof(Library.SPL.Exception));
addType(typeof(Library.SPL.RuntimeException));
addType(typeof(Library.SPL.ErrorException));
addType(typeof(Library.SPL.LogicException));
addType(typeof(Library.SPL.InvalidArgumentException));
addType(typeof(Library.SPL.OutOfRangeException));
addType(typeof(Library.SPL.BadFunctionCallException));
addType(typeof(Library.SPL.BadMethodCallException));
addType(typeof(Library.SPL.LengthException));
addType(typeof(Library.SPL.RangeException));
addType(typeof(Library.SPL.OutOfBoundsException));
addType(typeof(Library.SPL.OverflowException));
addType(typeof(Library.SPL.UnderflowException));
addType(typeof(Library.SPL.UnexpectedValueException));
addType(typeof(Library.SPL.DomainException));
// primitive constants
constants.Add("TRUE", GlobalConstant.True.ConstantDesc, true);
constants.Add("FALSE", GlobalConstant.False.ConstantDesc, true);
constants.Add("NULL", GlobalConstant.Null.ConstantDesc, true);
// the constants are same for all platforms (Phalanger use Int32 for integers in PHP):
constants.Add("PHP_INT_SIZE", GlobalConstant.PhpIntSize.ConstantDesc, false);
constants.Add("PHP_INT_MAX", GlobalConstant.PhpIntMax.ConstantDesc, false);
}
#region HACK HACK HACK !!!
/// <remarks>
/// We have to inject <c>export</c> method into <see cref="Library.SPL.Reflector"/> interface, since it cannot be written in C#
/// (abstract public static method with implementation in an interface). It could be declared in pure IL, but it would be ugly.
/// </remarks>
/// <param name="typedesc"><see cref="DTypeDesc"/> corresponding to <see cref="Library.SPL.Reflector"/>.</param>
private void AddExportMethod(DTypeDesc/*!*/typedesc)
{
Debug.Assert(typedesc != null);
Debug.Assert(typedesc.RealType == typeof(Library.SPL.Reflector));
// public static object export( ScriptContext context ){ return null; }
AddMethodToType(typedesc, PhpMemberAttributes.Public | PhpMemberAttributes.Static | PhpMemberAttributes.Abstract, "export", null);
}
#endregion
internal void LoadModuleEntries(DModule/*!*/ module)
{
module.Reflect(!lazyFullReflection, types, functions, constants);
}
#endregion
#region Libraries
public List<DAssembly>/*!*/ GetLoadedAssemblies()
{
return assemblyLoader.GetLoadedAssemblies<DAssembly>();
}
public IEnumerable<PhpLibraryAssembly>/*!*/ GetLoadedLibraries()
{
foreach (PhpLibraryAssembly library in assemblyLoader.GetLoadedAssemblies<PhpLibraryAssembly>())
yield return library;
}
public IEnumerable<string>/*!*/ GetLoadedExtensions()
{
//if (assemblyLoader.ReflectionOnly)
// throw new InvalidOperationException("Cannot retrieve list of extensions loaded for reflection only");
foreach (PhpLibraryAssembly library in assemblyLoader.GetLoadedAssemblies<PhpLibraryAssembly>())
{
foreach (string name in library.ImplementedExtensions)
yield return name;
}
}
/// <summary>
/// Finds a library among currently loaded ones that implements an extension with a specified name.
/// </summary>
/// <param name="name">The name of the extension to look for.</param>
/// <returns>The library descriptor.</returns>
/// <remarks>Not thread-safe. Not available at compilation domain.</remarks>
public PhpLibraryDescriptor/*!*/ GetExtensionImplementor(string name)
{
if (assemblyLoader.ReflectionOnly)
throw new InvalidOperationException("Cannot retrieve list of extensions loaded for reflection only");
foreach (PhpLibraryAssembly library in assemblyLoader.GetLoadedAssemblies<PhpLibraryAssembly>())
{
if (CollectionUtils.ContainsString(library.ImplementedExtensions, name, true))
return library.Descriptor;
}
return null;
}
#endregion
#region Helpers
public DRoutine GetFunction(QualifiedName qualifiedName, ref string/*!*/ fullName)
{
if (fullName == null)
fullName = qualifiedName.ToString();
DRoutineDesc desc;
return (functions.TryGetValue(fullName, out desc)) ? desc.Routine : null;
}
public DType GetType(QualifiedName qualifiedName, ref string/*!*/ fullName)
{
if (fullName == null)
fullName = qualifiedName.ToString();
DTypeDesc desc;
return (types.TryGetValue(fullName, out desc)) ? desc.Type : null;
}
public GlobalConstant GetConstant(QualifiedName qualifiedName, ref string/*!*/ fullName)
{
if (fullName == null)
fullName = qualifiedName.ToString();
DConstantDesc desc;
return (constants.TryGetValue(fullName, out desc)) ? desc.GlobalConstant : null;
}
/// <summary>
/// Declares a PHP type globally. Replaces any previous declaration.
/// To be called from the compiled scripts before library loading; libraries should check for conflicts.
/// </summary>
[Emitted]
public void DeclareType(DTypeDesc/*!*/ typeDesc, string/*!*/ fullName)
{
types[fullName] = typeDesc;
}
/// <summary>
/// Declares a PHP type globally. Replaces any previous declaration.
/// To be called from the compiled scripts before library loading; libraries should check for conflicts.
/// </summary>
[Emitted]
public void DeclareType(RuntimeTypeHandle/*!*/ typeHandle, string/*!*/ fullName)
{
types[fullName] = DTypeDesc.Create(typeHandle);
}
/// <summary>
/// Declares a PHP function globally. Replaces any previous declaration.
/// To be called from the compiled scripts before library loading; libraries should check for conflicts.
/// </summary>
[Emitted]
public void DeclareFunction(RoutineDelegate/*!*/ arglessStub, string/*!*/ fullName, PhpMemberAttributes memberAttributes, MethodInfo argfull)
{
var desc = new PhpRoutineDesc(memberAttributes, arglessStub, true);
if (argfull != null) // only if we have the argfull
new PurePhpFunction(desc, fullName, argfull); // writes desc.Member
functions[fullName] = desc;
}
/// <summary>
/// Declares a PHP constant globally. Replaces any previous declaration.
/// To be called from the compiled scripts before library loading; libraries should check for conflicts.
/// </summary>
[Emitted]
public void DeclareConstant(string/*!*/ fullName, object value)
{
constants[fullName, false] = new DConstantDesc(UnknownModule.RuntimeModule, PhpMemberAttributes.None, value);
}
/// <summary>
/// Checkes whether a type is transient.
/// </summary>
public bool IsTransientRealType(Type/*!*/ realType)
{
return transientAssemblyBuilder.IsTransientRealType(realType);
}
/// <summary>
/// Build the delegate checking if the given script specified by its FullPath exists on available locations.
/// </summary>
/// <returns>Function determinig the given script existance or null if no script can be included with current configuration.</returns>
internal Predicate<FullPath> BuildFileExistsDelegate()
{
if (this.fileExists == null)
{
RequestContext context = RequestContext.CurrentContext;
Predicate<FullPath> file_exists = null;
// 1. ScriptLibrary database
var database = ScriptLibraryDatabase;
if (database != null && database.Count > 0)
file_exists = file_exists.OrElse((path) => database.ContainsScript(path)); // file_exists can really be null
if (context != null)
{
// on web, check following locations too:
// 2. bin/WebPages.dll
var msas = context.GetPrecompiledAssemblies();
file_exists = file_exists.OrElse((path) =>
{
foreach (var msa in msas)
if (msa.ScriptExists(path))
return true;
// path was not found in any msa
return false;
});
}
else
{
// on non-web application, only script library should be checked
}
if (Configuration.IsBuildTime || !Configuration.Application.Compiler.OnlyPrecompiledCode)
{
// 3. file system
file_exists = file_exists.OrElse((path) => path.FileExists);
}
// remember in ApplicationContext
this.fileExists = file_exists;
}
return this.fileExists;
}
/// <summary>
/// Add at runtime a method to a type
/// </summary>
/// <param name="typedesc">Type to modify</param>
/// <param name="attributes">New method attributes</param>
/// <param name="func_name">Method name</param>
/// <param name="callback">Method body</param>
/// <remarks>Used by PDO_SQLITE</remarks>
public void AddMethodToType(DTypeDesc typedesc, PhpMemberAttributes attributes, string func_name, Func<object, PhpStack, object> callback)
{
Debug.Assert(typedesc != null);
var name = new Name(func_name);
var method_desc = new PhpRoutineDesc(typedesc, attributes);
if (!typedesc.Methods.ContainsKey(name))
{
typedesc.Methods.Add(name, method_desc);
// assign member:
if (method_desc.Member == null)
{
Func<ScriptContext, object> dummyArgFullCallback = DummyArgFull;
PhpMethod method = new PhpMethod(name, (PhpRoutineDesc)method_desc, dummyArgFullCallback.Method, (callback != null) ? callback.Method : null);
method.WriteUp(PhpRoutineSignature.FromArgfullInfo(method, dummyArgFullCallback.Method));
method_desc.Member = method;
}
}
}
/// <summary>
/// Add at runtime a constant to a type
/// </summary>
/// <param name="typedesc">Type to modify</param>
/// <param name="attributes">New const attributes</param>
/// <param name="const_name">Const name</param>
/// <param name="value">Const value</param>
/// <remarks>Used by PDO_MYSQL</remarks>
public void AddConstantToType(DTypeDesc typedesc, PhpMemberAttributes attributes, string const_name, object value)
{
Debug.Assert(typedesc != null);
VariableName name = new VariableName(const_name);
DConstantDesc const_desc = new DConstantDesc(typedesc, attributes, value);
if (!typedesc.Constants.ContainsKey(name))
{
typedesc.Constants.Add(name, const_desc);
}
}
[NeedsArgless]
private static object DummyArgFull(ScriptContext context)
{
Debug.Fail("This function should not be called thru argfull!");
return null;
}
#endregion
}
#region AssemblyLoader
public sealed partial class AssemblyLoader
{
/// <summary>
/// The owning AC.
/// </summary>
private readonly ApplicationContext/*!*/ applicationContext;
public bool ReflectionOnly { get { return reflectionOnly; } }
private readonly bool reflectionOnly;
public bool ClrReflectionOnly { get { return clrReflectionOnly; } }
private readonly bool clrReflectionOnly;
/// <summary>
/// Loaded assemblies. Contains all instances loaded by the loader. Synchronized.
/// </summary>
private readonly Dictionary<Assembly, DAssembly>/*!!*/ loadedAssemblies = new Dictionary<Assembly, DAssembly>();
internal AssemblyLoader(ApplicationContext/*!*/ applicationContext, bool reflectionOnly)
{
this.applicationContext = applicationContext;
this.reflectionOnly = reflectionOnly;
// not supported yet:
this.clrReflectionOnly = false;
}
internal Assembly LoadRealAssembly(string/*!*/ target)
{
#if SILVERLIGHT
return Assembly.Load(target);
#else
return (clrReflectionOnly) ? Assembly.ReflectionOnlyLoad(target) : Assembly.Load(target);
#endif
}
internal Assembly LoadRealAssemblyFrom(string/*!*/ target)
{
#if SILVERLIGHT
return Assembly.LoadFrom(target);
#else
return (clrReflectionOnly) ? Assembly.ReflectionOnlyLoadFrom(target) : Assembly.LoadFrom(target);
#endif
}
public List<T> GetLoadedAssemblies<T>()
where T : DAssembly
{
lock (this)
{
List<T> result = new List<T>(loadedAssemblies.Count);
foreach (DAssembly loaded_assembly in loadedAssemblies.Values)
{
T assembly = loaded_assembly as T;
if (assembly != null)
result.Add(assembly);
}
return result;
}
}
/// <summary>
/// Loads a library assembly given its name and configuration node.
/// </summary>
/// <param name="assemblyName">Long assembly name (see <see cref="Assembly.Load"/>) or a <B>null</B> reference.</param>
/// <param name="assemblyUrl">Assembly file absolute URI or a <B>null</B> reference.</param>
/// <param name="config">Configuration node describing the assembly to load (or a <B>null</B> reference).</param>
/// <exception cref="ConfigurationErrorsException">An error occured while loading the library.</exception>
public DAssembly/*!*/ Load(string assemblyName, Uri assemblyUrl, LibraryConfigStore config)
{
if (assemblyName == null && assemblyUrl == null)
throw new ArgumentNullException("assemblyName");
if (assemblyUrl != null && !assemblyUrl.IsAbsoluteUri)
throw new ArgumentException("Absolute URL expected", "assemblyUrl");
string target = null;
try
{
if (assemblyName != null)
{
// load assembly by full name:
target = assemblyName;
return Load(LoadRealAssembly(target), config);
}
else
{
// load by URI:
target = HttpUtility.UrlDecode(assemblyUrl.AbsoluteUri);
return Load(LoadRealAssemblyFrom(target), config);
}
}
catch (Exception e)
{
throw new ConfigurationErrorsException
(CoreResources.GetString("library_assembly_loading_failed", target) + " " + e.Message, e);
}
}
public DAssembly/*!*/ Load(Assembly/*!*/ realAssembly, LibraryConfigStore config)
{
Debug.Assert(realAssembly != null);
DAssembly assembly;
lock (this)
{
if (loadedAssemblies.TryGetValue(realAssembly, out assembly))
return assembly;
assembly = DAssembly.CreateNoLock(applicationContext, realAssembly, config);
// load the members contained in the assembly to the global tables:
applicationContext.LoadModuleEntries(assembly.ExportModule);
// add the assembly into loaded assemblies list now, so if LoadModuleEntries throws, assembly is not skipped within the next request!
loadedAssemblies.Add(realAssembly, assembly);
}
if (!reflectionOnly)
assembly.LoadCompileTimeReferencedAssemblies(this);
return assembly;
}
}
#endregion
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2015-2016 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Runtime.Serialization;
#if FEATURE_TAP
using System.Threading;
using System.Threading.Tasks;
#endif // FEATURE_TAP
namespace MsgPack.Serialization.CollectionSerializers
{
/// <summary>
/// Provides basic features for non-dictionary non-generic collection serializers.
/// </summary>
/// <typeparam name="TCollection">The type of the collection.</typeparam>
/// <remarks>
/// This class provides framework to implement variable collection serializer, and this type seals some virtual members to maximize future backward compatibility.
/// If you cannot use this class, you can implement your own serializer which inherits <see cref="MessagePackSerializer{T}"/> and implements <see cref="ICollectionInstanceFactory"/>.
/// </remarks>
public abstract class NonGenericEnumerableMessagePackSerializerBase<TCollection> : MessagePackSerializer<TCollection>, ICollectionInstanceFactory
where TCollection : IEnumerable
{
private readonly MessagePackSerializer _itemSerializer;
internal MessagePackSerializer ItemSerializer { get { return this._itemSerializer; } }
/// <summary>
/// Initializes a new instance of the <see cref="NonGenericEnumerableMessagePackSerializerBase{TCollection}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema )
: base( ownerContext )
{
this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema );
}
/// <summary>
/// Initializes a new instance of the <see cref="NonGenericEnumerableMessagePackSerializerBase{TCollection}"/> class.
/// </summary>
/// <param name="ownerContext">A <see cref="SerializationContext"/> which owns this serializer.</param>
/// <param name="schema">
/// The schema for collection itself or its items for the member this instance will be used to.
/// <c>null</c> will be considered as <see cref="PolymorphismSchema.Default"/>.
/// </param>
/// <param name="capabilities">A serializer calability flags represents capabilities of this instance.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="ownerContext"/> is <c>null</c>.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by base .ctor" )]
protected NonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, PolymorphismSchema schema, SerializerCapabilities capabilities )
: base( ownerContext, capabilities )
{
this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema );
}
/// <summary>
/// Creates a new collection instance with specified initial capacity.
/// </summary>
/// <param name="initialCapacity">
/// The initial capacy of creating collection.
/// Note that this parameter may <c>0</c> for non-empty collection.
/// </param>
/// <returns>
/// New collection instance. This value will not be <c>null</c>.
/// </returns>
/// <remarks>
/// An author of <see cref="Unpacker" /> could implement unpacker for non-MessagePack format,
/// so implementer of this interface should not rely on that <paramref name="initialCapacity" /> reflects actual items count.
/// For example, JSON unpacker cannot supply collection items count efficiently.
/// </remarks>
/// <seealso cref="ICollectionInstanceFactory.CreateInstance"/>
protected abstract TCollection CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker">The <see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">The collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TCollection"/> is not collection.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods",
MessageId = "0", Justification = "By design" )]
protected internal override void UnpackToCore( Unpacker unpacker, TCollection collection )
{
if ( !unpacker.IsArrayHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker">The <see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">The collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <param name="itemsCount">The count of items of the collection in the msgpack stream.</param>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal void UnpackToCore( Unpacker unpacker, TCollection collection, int itemsCount )
{
for ( var i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
object item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = this._itemSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
item = this._itemSerializer.UnpackFrom( subtreeUnpacker );
}
}
this.AddItem( collection, item );
}
}
#if FEATURE_TAP
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/> asynchronously.
/// </summary>
/// <param name="unpacker"><see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">Collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="Task"/> that represents the asynchronous operation.
/// </returns>
/// <exception cref="System.Runtime.Serialization.SerializationException">
/// Failed to deserialize object.
/// </exception>
/// <exception cref="MessageTypeException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="InvalidMessagePackStreamException">
/// Failed to deserialize object due to invalid stream.
/// </exception>
/// <exception cref="NotSupportedException">
/// <typeparamref name="TCollection"/> is not mutable collection.
/// </exception>
/// <seealso cref="P:Capabilities"/>
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "0", Justification = "Validated by caller in base class" )]
protected internal override Task UnpackToAsyncCore( Unpacker unpacker, TCollection collection, CancellationToken cancellationToken )
{
if ( !unpacker.IsArrayHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
return this.UnpackToAsyncCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ), cancellationToken );
}
/// <summary>
/// Deserializes collection items with specified <see cref="Unpacker"/> and stores them to <paramref name="collection"/>.
/// </summary>
/// <param name="unpacker">The <see cref="Unpacker"/> which unpacks values of resulting object tree. This value will not be <c>null</c>.</param>
/// <param name="collection">The collection that the items to be stored. This value will not be <c>null</c>.</param>
/// <param name="itemsCount">The count of items of the collection in the msgpack stream.</param>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A <see cref="Task"/> that represents the asynchronous operation.
/// </returns>
/// <exception cref="SerializationException">
/// Failed to deserialize object due to invalid unpacker state, stream content, or so.
/// </exception>
protected internal Task UnpackToAsyncCore( Unpacker unpacker, TCollection collection, int itemsCount, CancellationToken cancellationToken )
{
return this.InternalUnpackToAsyncCore( unpacker, collection, itemsCount, cancellationToken );
}
internal async Task<TCollection> InternalUnpackToAsyncCore( Unpacker unpacker, TCollection collection, int itemsCount, CancellationToken cancellationToken )
{
for ( var i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
object item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = await this._itemSerializer.UnpackFromAsync( unpacker, cancellationToken ).ConfigureAwait( false );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
item = await this._itemSerializer.UnpackFromAsync( subtreeUnpacker, cancellationToken ).ConfigureAwait( false );
}
}
this.AddItem( collection, item );
}
return collection;
}
#endif // FEATURE_TAP
/// <summary>
/// When implemented by derive class,
/// adds the deserialized item to the collection on <typeparamref name="TCollection"/> specific manner
/// to implement <see cref="UnpackToCore(Unpacker,TCollection)"/>.
/// </summary>
/// <param name="collection">The collection to be added.</param>
/// <param name="item">The item to be added.</param>
/// <exception cref="NotSupportedException">
/// This implementation always throws it.
/// </exception>
protected virtual void AddItem( TCollection collection, object item )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( typeof( TCollection ), null );
}
}
#if UNITY
#warning TODO: Remove if possible for maintenancibility.
internal abstract class UnityNonGenericEnumerableMessagePackSerializerBase : NonGenericMessagePackSerializer, ICollectionInstanceFactory
{
private readonly MessagePackSerializer _itemSerializer;
internal MessagePackSerializer ItemSerializer { get { return this._itemSerializer; } }
protected UnityNonGenericEnumerableMessagePackSerializerBase( SerializationContext ownerContext, Type targetType, PolymorphismSchema schema, SerializerCapabilities capabilities )
: base( ownerContext, targetType, capabilities )
{
this._itemSerializer = ownerContext.GetSerializer( typeof( object ), ( schema ?? PolymorphismSchema.Default ).ItemSchema );
}
protected abstract object CreateInstance( int initialCapacity );
object ICollectionInstanceFactory.CreateInstance( int initialCapacity )
{
return this.CreateInstance( initialCapacity );
}
protected internal override void UnpackToCore( Unpacker unpacker, object collection )
{
if ( !unpacker.IsArrayHeader )
{
SerializationExceptions.ThrowIsNotArrayHeader( unpacker );
}
this.UnpackToCore( unpacker, collection, UnpackHelpers.GetItemsCount( unpacker ) );
}
internal void UnpackToCore( Unpacker unpacker, object collection, int itemsCount )
{
for ( var i = 0; i < itemsCount; i++ )
{
if ( !unpacker.Read() )
{
SerializationExceptions.ThrowMissingItem( i, unpacker );
}
object item;
if ( !unpacker.IsArrayHeader && !unpacker.IsMapHeader )
{
item = this._itemSerializer.UnpackFrom( unpacker );
}
else
{
using ( var subtreeUnpacker = unpacker.ReadSubtree() )
{
item = this._itemSerializer.UnpackFrom( subtreeUnpacker );
}
}
this.AddItem( collection, item );
}
}
protected virtual void AddItem( object collection, object item )
{
throw SerializationExceptions.NewUnpackToIsNotSupported( this.TargetType, null );
}
}
#endif // UNITY
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.AcceptanceTestsBodyNumber
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Models;
/// <summary>
/// Extension methods for Number.
/// </summary>
public static partial class NumberExtensions
{
/// <summary>
/// Get null Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetNull(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetNullAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get null Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetNullAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetNullWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid float Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetInvalidFloat(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetInvalidFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid float Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetInvalidFloatAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid double Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetInvalidDouble(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetInvalidDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid double Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetInvalidDoubleAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Get invalid decimal Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetInvalidDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetInvalidDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get invalid decimal Number value
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<decimal?> GetInvalidDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetInvalidDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigFloat(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigFloatAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigFloatAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigFloat(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big float value 3.402823e+20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetBigFloatAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDouble(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDoubleAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDouble(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetBigDoubleAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDoublePositiveDecimal(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDoublePositiveDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDoublePositiveDecimalAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDoublePositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDoublePositiveDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDoublePositiveDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetBigDoublePositiveDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDoublePositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDoubleNegativeDecimal(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDoubleNegativeDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDoubleNegativeDecimalAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDoubleNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetBigDoubleNegativeDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDoubleNegativeDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetBigDoubleNegativeDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDoubleNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimal(this INumber operations, decimal numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDecimalAsync(this INumber operations, decimal numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value 2.5976931e+101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<decimal?> GetBigDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimalPositiveDecimal(this INumber operations, decimal numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalPositiveDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDecimalPositiveDecimalAsync(this INumber operations, decimal numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDecimalPositiveDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimalPositiveDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalPositiveDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value 99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<decimal?> GetBigDecimalPositiveDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDecimalPositiveDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutBigDecimalNegativeDecimal(this INumber operations, decimal numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutBigDecimalNegativeDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutBigDecimalNegativeDecimalAsync(this INumber operations, decimal numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutBigDecimalNegativeDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetBigDecimalNegativeDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetBigDecimalNegativeDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big decimal value -99999999.99
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<decimal?> GetBigDecimalNegativeDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetBigDecimalNegativeDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small float value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallFloat(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutSmallFloatAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small float value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutSmallFloatAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutSmallFloatWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetSmallFloat(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetSmallFloatAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 3.402823e-20
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetSmallFloatAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSmallFloatWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallDouble(this INumber operations, double numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutSmallDoubleAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutSmallDoubleAsync(this INumber operations, double numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutSmallDoubleWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get big double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static double? GetSmallDouble(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetSmallDoubleAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get big double value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<double?> GetSmallDoubleAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSmallDoubleWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Put small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
public static void PutSmallDecimal(this INumber operations, decimal numberBody)
{
Task.Factory.StartNew(s => ((INumber)s).PutSmallDecimalAsync(numberBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Put small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='numberBody'>
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task PutSmallDecimalAsync(this INumber operations, decimal numberBody, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.PutSmallDecimalWithHttpMessagesAsync(numberBody, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Get small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static decimal? GetSmallDecimal(this INumber operations)
{
return Task.Factory.StartNew(s => ((INumber)s).GetSmallDecimalAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Get small decimal value 2.5976931e-101
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<decimal?> GetSmallDecimalAsync(this INumber operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetSmallDecimalWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
using System;
using System.Collections.ObjectModel;
using System.Windows.Input;
using EspaceClient.BackOffice.Domaine.Criterias;
using EspaceClient.BackOffice.Silverlight.Business.Depots;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.Business.Loader;
using EspaceClient.BackOffice.Silverlight.ViewModels.Common.Modularity;
using EspaceClient.BackOffice.Silverlight.ViewModels.Helper.Administration.Personne;
using EspaceClient.BackOffice.Silverlight.ViewModels.Messages;
using EspaceClient.BackOffice.Silverlight.ViewModels.ModelBuilders.Administration.Personne;
using EspaceClient.FrontOffice.Domaine;
using nRoute.Components;
using nRoute.Components.Composition;
using nRoute.Components.Messaging;
using OGDC.Silverlight.Toolkit.Services.Services;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.Administration.Personne.Tabs
{
/// <summary>
/// ViewModel de la vue <see cref="SearchView"/>
/// </summary>
public class SearchViewModel : TabBase
{
private readonly IResourceWrapper _resourceWrapper;
private readonly IDepotPersonne _depot_personne;
private readonly IMessenging _messengingService;
private readonly IApplicationContext _applicationContext;
private readonly ILoaderReferentiel _referentiel;
private readonly IModelBuilderDetails _builderDetails;
protected ChannelObserver<UpdateListMessage> ObserverUpdateListMessage { get; private set; }
private ObservableCollection<PersonneDto> _searchResult;
private ICommand _searchCommand;
private ICommand _resetCommand;
private ICommand _doubleClickCommand;
private SearchPersonneCriteriasDto _criteres;
private PersonneDto _selectedPersonne;
private bool _isLoading;
public bool IsLoading
{
get
{
return _isLoading;
}
set
{
if (_isLoading != value)
{
_isLoading = value;
NotifyPropertyChanged(() => IsLoading);
}
}
}
[ResolveConstructor]
public SearchViewModel(IResourceWrapper resourceWrapper, IDepotPersonne depot_personne, IMessenging messengingService, IApplicationContext applicationContext, ILoaderReferentiel referentiel, IModelBuilderDetails builderDetails)
: base(applicationContext, messengingService)
{
_resourceWrapper = resourceWrapper;
_depot_personne = depot_personne;
_messengingService = messengingService;
_applicationContext = applicationContext;
_referentiel = referentiel;
_builderDetails = builderDetails;
InitializeCommands();
InitializeUI();
InitializeMessenging();
}
public ObservableCollection<PersonneDto> SearchResult
{
get
{
return _searchResult;
}
set
{
if (_searchResult != value)
{
_searchResult = value;
NotifyPropertyChanged(() => SearchResult);
}
}
}
public SearchPersonneCriteriasDto Criteres
{
get
{
return _criteres;
}
set
{
_criteres = value;
NotifyPropertyChanged(() => Criteres);
}
}
public PersonneDto SelectedPersonne
{
get { return _selectedPersonne; }
set
{
if (_selectedPersonne != value)
{
_selectedPersonne = value;
NotifyPropertyChanged(() => SelectedPersonne);
}
}
}
#region Commands
/// <summary>
/// Command de recherche des utilisateurs
/// </summary>
public ICommand SearchCommand
{
get { return _searchCommand; }
}
public ICommand DoubleClickCommand
{
get
{
return _doubleClickCommand;
}
}
public ICommand ResetCommand
{
get { return _resetCommand; }
}
#endregion
private void InitializeMessenging()
{
ObserverUpdateListMessage = _messengingService.CreateObserver<UpdateListMessage>(msg =>
{
if (msg.Type == TypeUpdateList.RecherchePersonne)
{
if (SearchCommand.CanExecute(this))
SearchCommand.Execute(this);
}
});
ObserverUpdateListMessage.Subscribe(ThreadOption.UIThread);
}
private void DisposeMessenging()
{
ObserverUpdateListMessage.Unsubscribe();
}
private void InitializeCommands()
{
_searchCommand = new ActionCommand(OnSearch);
_doubleClickCommand = new ActionCommand<PersonneDto>(OnDoubleClickCommand);
_resetCommand = new ActionCommand(OnReset);
}
private void InitializeUI()
{
OnReset();
SearchResult = new ObservableCollection<PersonneDto>();
IsLoading = false;
}
private void OnReset()
{
Criteres = new SearchPersonneCriteriasDto()
{
Nom = "",
Prenom = "",
Email = "",
};
}
private void OnSearch()
{
if (IsLoading)
return;
_depot_personne.GetPersonnesByCriterias(Criteres, r =>
{
foreach (var u in r)
SearchResult.Add(u);
IsLoading = false;
}, error => _messengingService.Publish(new ErrorMessage(error)));
SearchResult.Clear();
IsLoading = true;
}
private void OnDoubleClickCommand(PersonneDto selectedPersonne)
{
if (selectedPersonne != null)
{
PersonneHelper.AddPersonneTab(selectedPersonne.ID, _messengingService, _depot_personne, _builderDetails);
}
}
public override void OnRefreshTab<EntityType>(long id, Action<EntityType> callback)
{
throw new NotImplementedException();
}
protected override void OnRefreshTabCompleted(Action callback)
{
throw new NotImplementedException();
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.SecurityTokenService;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace ServerSideCSOMWeb
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
SecondaryClientSecret,
authorizationCode,
redirectUri,
resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, SecondaryClientSecret, refreshToken, resource);
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (RequestFailedException)
{
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, SecondaryClientSecret, resource);
oauth2Request.Resource = resource;
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
else
{
throw;
}
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an add-in event
/// </summary>
/// <param name="properties">Properties of an add-in event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registered for this add-in</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted add-in. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the add-in should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust add-in.
/// </summary>
/// <returns>True if this is a high trust add-in.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted add-in configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
// StreamReaderTest.cs - NUnit Test Cases for the SystemIO.StreamReader class
//
// David Brandt (bucky@keystreams.com)
//
// (C) Ximian, Inc. http://www.ximian.com
// Copyright (C) 2004 Novell (http://www.novell.com)
//
using NUnit.Framework;
using System;
using System.IO;
using System.Text;
namespace MonoTests.System.IO
{
[TestFixture]
public class StreamReaderTest : Assertion
{
static string TempFolder = Path.Combine (Path.GetTempPath (), "MonoTests.System.IO.Tests");
private string _codeFileName = TempFolder + Path.DirectorySeparatorChar + "AFile.txt";
[SetUp]
public void SetUp ()
{
if (!Directory.Exists (TempFolder))
Directory.CreateDirectory (TempFolder);
if (!File.Exists (_codeFileName))
File.Create (_codeFileName).Close ();
}
[TearDown]
public void TearDown ()
{
if (Directory.Exists (TempFolder))
Directory.Delete (TempFolder, true);
}
[Test]
public void TestCtor1() {
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((Stream)null);
} catch (ArgumentNullException) {
errorThrown = true;
}
Assert("null string error not thrown", errorThrown);
}
{
bool errorThrown = false;
FileStream f = new FileStream(_codeFileName, FileMode.Open, FileAccess.Write);
try {
StreamReader r = new StreamReader(f);
r.Close();
} catch (ArgumentException) {
errorThrown = true;
}
f.Close();
Assert("no read error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
FileStream f = new FileStream(_codeFileName,
FileMode.Open,
FileAccess.Read);
StreamReader r = new StreamReader(f);
AssertNotNull("no stream reader", r);
r.Close();
f.Close();
}
}
[Test]
public void TestCtor2() {
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("");
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 1: " + e.ToString());
}
Assert("empty string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((string)null);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 2: " + e.ToString());
}
Assert("null string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("nonexistentfile");
} catch (FileNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 3: " + e.ToString());
}
Assert("fileNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("nonexistentdir/file");
} catch (DirectoryNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 4: " + e.ToString());
}
Assert("dirNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0]);
} catch (IOException) {
errorThrown = true;
} catch (ArgumentException) {
// FIXME - the spec says 'IOExc', but the
// compiler says 'ArgExc'...
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 5: " + e.ToString());
}
Assert("invalid filename error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
StreamReader r = new StreamReader(_codeFileName);
AssertNotNull("no stream reader", r);
r.Close();
}
}
[Test]
public void TestCtor3() {
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((Stream)null, false);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 1: " + e.ToString());
}
Assert("null stream error not thrown", errorThrown);
}
{
bool errorThrown = false;
FileStream f = new FileStream(_codeFileName, FileMode.Open, FileAccess.Write);
try {
StreamReader r = new StreamReader(f, false);
r.Close();
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 2: " + e.ToString());
}
f.Close();
Assert("no read error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
FileStream f = new FileStream(_codeFileName,
FileMode.Open,
FileAccess.Read);
StreamReader r = new StreamReader(f, false);
AssertNotNull("no stream reader", r);
r.Close();
f.Close();
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((Stream)null, true);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 3: " + e.ToString());
}
Assert("null string error not thrown", errorThrown);
}
{
bool errorThrown = false;
FileStream f = new FileStream(_codeFileName, FileMode.Open, FileAccess.Write);
try {
StreamReader r = new StreamReader(f, true);
r.Close();
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 4: " + e.ToString());
}
f.Close();
Assert("no read error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
FileStream f = new FileStream(_codeFileName,
FileMode.Open,
FileAccess.Read);
StreamReader r = new StreamReader(f, true);
AssertNotNull("no stream reader", r);
r.Close();
f.Close();
}
}
[Test]
public void TestCtor4() {
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("", false);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 1: " + e.ToString());
}
Assert("empty string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((string)null, false);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 2: " + e.ToString());
}
Assert("null string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader(TempFolder + "/nonexistentfile", false);
} catch (FileNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 3: " + e.ToString());
}
Assert("fileNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader(TempFolder + "/nonexistentdir/file", false);
} catch (DirectoryNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 4: " + e.ToString());
}
Assert("dirNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0], false);
} catch (IOException) {
errorThrown = true;
} catch (ArgumentException) {
// FIXME - the spec says 'IOExc', but the
// compiler says 'ArgExc'...
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 5: " + e.ToString());
}
Assert("invalid filename error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
StreamReader r = new StreamReader(_codeFileName, false);
AssertNotNull("no stream reader", r);
r.Close();
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("", true);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 6: " + e.ToString());
}
Assert("empty string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader((string)null, true);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 7: " + e.ToString());
}
Assert("null string error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader(TempFolder + "/nonexistentfile", true);
} catch (FileNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 8: " + e.ToString());
}
Assert("fileNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader(TempFolder + "/nonexistentdir/file", true);
} catch (DirectoryNotFoundException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 9: " + e.ToString());
}
Assert("dirNotFound error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
StreamReader r = new StreamReader("!$what? what? Huh? !$*#" + Path.InvalidPathChars[0], true);
} catch (IOException) {
errorThrown = true;
} catch (ArgumentException) {
// FIXME - the spec says 'IOExc', but the
// compiler says 'ArgExc'...
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 10: " + e.ToString());
}
Assert("invalid filename error not thrown", errorThrown);
}
{
// this is probably incestuous, but, oh well.
StreamReader r = new StreamReader(_codeFileName, true);
AssertNotNull("no stream reader", r);
r.Close();
}
}
// TODO - Ctor with Encoding
[Test]
public void TestBaseStream() {
string progress = "beginning";
try {
Byte[] b = {};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
AssertEquals("wrong base stream ", m, r.BaseStream);
progress = "Closing StreamReader";
r.Close();
progress = "Closing MemoryStream";
m.Close();
} catch (Exception e) {
Fail ("At '" + progress + "' an unexpected exception was thrown: " + e.ToString());
}
}
public void TestCurrentEncoding() {
try {
Byte[] b = {};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
AssertEquals("wrong encoding",
Encoding.UTF8.GetType (), r.CurrentEncoding.GetType ());
} catch (Exception e) {
Fail ("Unexpected exception thrown: " + e.ToString());
}
}
// TODO - Close - annoying spec - won't commit to any exceptions. How to test?
// TODO - DiscardBufferedData - I have no clue how to test this function.
[Test]
public void TestPeek() {
// FIXME - how to get an IO Exception?
{
bool errorThrown = false;
try {
Byte[] b = {};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
m.Close();
int nothing = r.Peek();
} catch (ObjectDisposedException) {
errorThrown = true;
}
Assert("nothing-to-peek-at error not thrown", errorThrown);
}
{
Byte[] b = {1, 2, 3, 4, 5, 6};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
for (int i = 1; i <= 6; i++) {
AssertEquals("peek incorrect", i, r.Peek());
r.Read();
}
AssertEquals("should be none left", -1, r.Peek());
}
}
[Test]
public void TestRead() {
// FIXME - how to get an IO Exception?
{
bool errorThrown = false;
try {
Byte[] b = {};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
m.Close();
int nothing = r.Read();
} catch (ObjectDisposedException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 1: " + e.ToString());
}
Assert("nothing-to-read error not thrown", errorThrown);
}
{
Byte[] b = {1, 2, 3, 4, 5, 6};
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
for (int i = 1; i <= 6; i++) {
AssertEquals("read incorrect", i, r.Read());
}
AssertEquals("Should be none left", -1, r.Read());
}
{
bool errorThrown = false;
try {
Byte[] b = {};
StreamReader r = new StreamReader(new MemoryStream(b));
r.Read(null, 0, 0);
} catch (ArgumentNullException) {
errorThrown = true;
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 2: " + e.ToString());
}
Assert("null buffer error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
Byte[] b = {};
StreamReader r = new StreamReader(new MemoryStream(b));
Char[] c = new Char[1];
r.Read(c, 0, 2);
} catch (ArgumentException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 3: " + e.ToString());
}
Assert("too-long range error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
Byte[] b = {};
StreamReader r = new StreamReader(new MemoryStream(b));
Char[] c = new Char[1];
r.Read(c, -1, 2);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 4: " + e.ToString());
}
Assert("out of range error not thrown", errorThrown);
}
{
bool errorThrown = false;
try {
Byte[] b = {};
StreamReader r = new StreamReader(new MemoryStream(b));
Char[] c = new Char[1];
r.Read(c, 0, -1);
} catch (ArgumentOutOfRangeException) {
errorThrown = true;
} catch (Exception e) {
Fail ("Incorrect exception thrown at 5: " + e.ToString());
}
Assert("out of range error not thrown", errorThrown);
}
{
int ii = 1;
try {
Byte[] b = {(byte)'a', (byte)'b', (byte)'c',
(byte)'d', (byte)'e', (byte)'f',
(byte)'g'};
MemoryStream m = new MemoryStream(b);
ii++;
StreamReader r = new StreamReader(m);
ii++;
char[] buffer = new Char[7];
ii++;
char[] target = {'g','d','e','f','b','c','a'};
ii++;
r.Read(buffer, 6, 1);
ii++;
r.Read(buffer, 4, 2);
ii++;
r.Read(buffer, 1, 3);
ii++;
r.Read(buffer, 0, 1);
ii++;
for (int i = 0; i < target.Length; i++) {
AssertEquals("read no work",
target[i], buffer[i]);
i++;
}
} catch (Exception e) {
Fail ("Caught when ii=" + ii + ". e:" + e.ToString());
}
}
}
[Test]
public void TestReadLine() {
// TODO Out Of Memory Exc? IO Exc?
Byte[] b = new Byte[8];
b[0] = (byte)'a';
b[1] = (byte)'\n';
b[2] = (byte)'b';
b[3] = (byte)'\n';
b[4] = (byte)'c';
b[5] = (byte)'\n';
b[6] = (byte)'d';
b[7] = (byte)'\n';
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
AssertEquals("line doesn't match", "a", r.ReadLine());
AssertEquals("line doesn't match", "b", r.ReadLine());
AssertEquals("line doesn't match", "c", r.ReadLine());
AssertEquals("line doesn't match", "d", r.ReadLine());
AssertEquals("line doesn't match", null, r.ReadLine());
}
public void TestReadToEnd() {
// TODO Out Of Memory Exc? IO Exc?
Byte[] b = new Byte[8];
b[0] = (byte)'a';
b[1] = (byte)'\n';
b[2] = (byte)'b';
b[3] = (byte)'\n';
b[4] = (byte)'c';
b[5] = (byte)'\n';
b[6] = (byte)'d';
b[7] = (byte)'\n';
MemoryStream m = new MemoryStream(b);
StreamReader r = new StreamReader(m);
AssertEquals("line doesn't match", "a\nb\nc\nd\n", r.ReadToEnd());
AssertEquals("line doesn't match", "", r.ReadToEnd());
}
[Test]
public void TestBaseStreamClosed ()
{
byte [] b = {};
MemoryStream m = new MemoryStream (b);
StreamReader r = new StreamReader (m);
m.Close ();
bool thrown = false;
try {
r.Peek ();
} catch (ObjectDisposedException) {
thrown = true;
}
AssertEquals ("#01", true, thrown);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Contructor_Stream_NullEncoding ()
{
StreamReader r = new StreamReader (new MemoryStream (), null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Contructor_Path_NullEncoding ()
{
StreamReader r = new StreamReader (_codeFileName, null);
}
[Test]
[ExpectedException (typeof (ArgumentNullException))]
public void Read_Null ()
{
StreamReader r = new StreamReader (new MemoryStream ());
r.Read (null, 0, 0);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Read_IndexOverflow ()
{
char[] array = new char [16];
StreamReader r = new StreamReader (new MemoryStream (16));
r.Read (array, 1, Int32.MaxValue);
}
[Test]
[ExpectedException (typeof (ArgumentException))]
public void Read_CountOverflow ()
{
char[] array = new char [16];
StreamReader r = new StreamReader (new MemoryStream (16));
r.Read (array, Int32.MaxValue, 1);
}
}
}
| |
using System.Diagnostics.Contracts;
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//* File: Channel.cs
//*
//* <EMAIL>Author: Tarun Anand ([....])</EMAIL>
//*
//* Purpose: Defines the general purpose remoting proxy
//*
//* Date: May 27, 1999
//*
namespace System.Runtime.Remoting.Channels {
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Activation;
using System.Runtime.Remoting.Messaging;
using System.Runtime.Remoting.Metadata;
using System.Runtime.Remoting.Proxies;
using System.Runtime.Versioning;
using System.Threading;
using System.Security;
using System.Security.Permissions;
using System.Globalization;
// ChannelServices
[System.Runtime.InteropServices.StructLayout(LayoutKind.Sequential)]
internal struct Perf_Contexts {
internal volatile int cRemoteCalls;
internal volatile int cChannels;
};
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ChannelServices
{
// This gets refreshed when a channel is registered/unregistered.
private static volatile Object[] s_currentChannelData = null;
[System.Security.SecuritySafeCritical] // static constructors should be safe to call
static ChannelServices()
{
}
internal static Object[] CurrentChannelData
{
[System.Security.SecurityCritical] // auto-generated
get
{
if (s_currentChannelData == null)
RefreshChannelData();
return s_currentChannelData;
}
} // CurrentChannelData
// hide the default constructor
private ChannelServices()
{
}
// list of registered channels and a lock to take when adding or removing channels
// Note that the channel list is read outside of the lock, which is why it's marked volatile.
private static Object s_channelLock = new Object();
private static volatile RegisteredChannelList s_registeredChannels = new RegisteredChannelList();
// Private member variables
// These have all been converted to getters and setters to get the effect of
// per-AppDomain statics (note: statics are per-AppDomain now, so these members
// could just be declared as statics on ChannelServices).
private static long remoteCalls
{
get { return Thread.GetDomain().RemotingData.ChannelServicesData.remoteCalls; }
set { Thread.GetDomain().RemotingData.ChannelServicesData.remoteCalls = value; }
}
private static volatile IMessageSink xCtxChannel;
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
[ResourceExposure(ResourceScope.None)]
static unsafe extern Perf_Contexts* GetPrivateContextsPerfCounters();
[SecurityCritical]
unsafe private static volatile Perf_Contexts *perf_Contexts = GetPrivateContextsPerfCounters();
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
public static void RegisterChannel(IChannel chnl, bool ensureSecurity)
{
RegisterChannelInternal(chnl, ensureSecurity);
}
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
[Obsolete("Use System.Runtime.Remoting.ChannelServices.RegisterChannel(IChannel chnl, bool ensureSecurity) instead.", false)]
public static void RegisterChannel(IChannel chnl)
{
RegisterChannelInternal(chnl, false/*ensureSecurity*/);
}
static bool unloadHandlerRegistered = false;
[System.Security.SecurityCritical] // auto-generated
unsafe internal static void RegisterChannelInternal(IChannel chnl, bool ensureSecurity)
{
// Validate arguments
if(null == chnl)
{
throw new ArgumentNullException("chnl");
}
Contract.EndContractBlock();
bool fLocked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_channelLock, ref fLocked);
String chnlName = chnl.ChannelName;
RegisteredChannelList regChnlList = s_registeredChannels;
// Check to make sure that the channel has not been registered
if((chnlName == null) ||
(chnlName.Length == 0) ||
(-1 == regChnlList.FindChannelIndex(chnl.ChannelName)))
{
if (ensureSecurity)
{
ISecurableChannel securableChannel = chnl as ISecurableChannel;
if (securableChannel != null)
securableChannel.IsSecured = ensureSecurity;
else
throw new RemotingException(Environment.GetResourceString("Remoting_Channel_CannotBeSecured", chnl.ChannelName??chnl.ToString()));
}
RegisteredChannel[] oldList = regChnlList.RegisteredChannels;
RegisteredChannel[] newList = null;
if (oldList == null)
{
newList = new RegisteredChannel[1];
}
else
newList = new RegisteredChannel[oldList.Length + 1];
if (!unloadHandlerRegistered && !(chnl is CrossAppDomainChannel))
{
// Register a unload handler only once and if the channel being registered
// is not the x-domain channel. x-domain channel does nothing inside its
// StopListening implementation
AppDomain.CurrentDomain.DomainUnload += new EventHandler(UnloadHandler);
unloadHandlerRegistered = true;
}
// Add the interface to the array in priority order
int priority = chnl.ChannelPriority;
int current = 0;
// Find the place in the array to insert
while (current < oldList.Length)
{
RegisteredChannel oldChannel = oldList[current];
if (priority > oldChannel.Channel.ChannelPriority)
{
newList[current] = new RegisteredChannel(chnl);
break;
}
else
{
newList[current] = oldChannel;
current++;
}
}
if (current == oldList.Length)
{
// chnl has lower priority than all old channels, so we insert
// it at the end of the list.
newList[oldList.Length] = new RegisteredChannel(chnl);
}
else
{
// finish copying rest of the old channels
while (current < oldList.Length)
{
newList[current + 1] = oldList[current];
current++;
}
}
if (perf_Contexts != null) {
perf_Contexts->cChannels++;
}
s_registeredChannels = new RegisteredChannelList(newList);
}
else
{
throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNameAlreadyRegistered", chnl.ChannelName));
}
RefreshChannelData();
} // lock (s_channelLock)
finally
{
if (fLocked)
{
Monitor.Exit(s_channelLock);
}
}
} // RegisterChannelInternal
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
unsafe public static void UnregisterChannel(IChannel chnl)
{
// we allow null to be passed in, so we can use this api to trigger the
// refresh of the channel data <
bool fLocked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_channelLock, ref fLocked);
if (chnl != null)
{
RegisteredChannelList regChnlList = s_registeredChannels;
// Check to make sure that the channel has been registered
int matchingIdx = regChnlList.FindChannelIndex(chnl);
if(-1 == matchingIdx)
{
throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNotRegistered", chnl.ChannelName));
}
RegisteredChannel[] oldList = regChnlList.RegisteredChannels;
RegisteredChannel[] newList = null;
Contract.Assert((oldList != null) && (oldList.Length != 0), "channel list should not be empty");
newList = new RegisteredChannel[oldList.Length - 1];
// Call stop listening on the channel if it is a receiver.
IChannelReceiver srvChannel = chnl as IChannelReceiver;
if (srvChannel != null)
srvChannel.StopListening(null);
int current = 0;
int oldPos = 0;
while (oldPos < oldList.Length)
{
if (oldPos == matchingIdx)
{
oldPos++;
}
else
{
newList[current] = oldList[oldPos];
current++;
oldPos++;
}
}
if (perf_Contexts != null) {
perf_Contexts->cChannels--;
}
s_registeredChannels = new RegisteredChannelList(newList);
}
RefreshChannelData();
} // lock (s_channelLock)
finally
{
if (fLocked)
{
Monitor.Exit(s_channelLock);
}
}
} // UnregisterChannel
public static IChannel[] RegisteredChannels
{
[System.Security.SecurityCritical] // auto-generated_required
get
{
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
if (0 == count)
{
return new IChannel[0];
}
else
{
// we hide the CrossAppDomainChannel, so the number of visible
// channels is one less than the number of registered channels.
int visibleChannels = count - 1;
// Copy the array of visible channels into a new array
// and return
int co = 0;
IChannel[] temp = new IChannel[visibleChannels];
for (int i = 0; i < count; i++)
{
IChannel channel = regChnlList.GetChannel(i);
// add the channel to the array if it is not the CrossAppDomainChannel
if (!(channel is CrossAppDomainChannel))
temp[co++] = channel;
}
return temp;
}
}
} // RegisteredChannels
[System.Security.SecurityCritical] // auto-generated
internal static IMessageSink CreateMessageSink(String url, Object data, out String objectURI)
{
BCLDebug.Trace("REMOTE", "ChannelServices::CreateMessageSink for url " + url + "\n");
IMessageSink msgSink = null;
objectURI = null;
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
for(int i = 0; i < count; i++)
{
if(regChnlList.IsSender(i))
{
IChannelSender chnl = (IChannelSender)regChnlList.GetChannel(i);
msgSink = chnl.CreateMessageSink(url, data, out objectURI);
if(msgSink != null)
break;
}
}
// If the object uri has not been set, set it to the url as
// default value
if(null == objectURI)
{
objectURI = url;
}
return msgSink;
} // CreateMessageSink
[System.Security.SecurityCritical] // auto-generated
internal static IMessageSink CreateMessageSink(Object data)
{
String objectUri;
return CreateMessageSink(null, data, out objectUri);
} // CreateMessageSink
[System.Security.SecurityCritical] // auto-generated_required
public static IChannel GetChannel(String name)
{
RegisteredChannelList regChnlList = s_registeredChannels;
int matchingIdx = regChnlList.FindChannelIndex(name);
if(0 <= matchingIdx)
{
IChannel channel = regChnlList.GetChannel(matchingIdx);
if ((channel is CrossAppDomainChannel) || (channel is CrossContextChannel))
return null;
else
return channel;
}
else
{
return null;
}
} // GetChannel
[System.Security.SecurityCritical] // auto-generated_required
public static String[] GetUrlsForObject(MarshalByRefObject obj)
{
if(null == obj)
{
return null;
}
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
Hashtable table = new Hashtable();
bool fServer;
Identity id = MarshalByRefObject.GetIdentity(obj, out fServer);
if(null != id)
{
String uri = id.ObjURI;
if (null != uri)
{
for(int i = 0; i < count; i++)
{
if(regChnlList.IsReceiver(i))
{
try
{
String[] urls = ((IChannelReceiver)regChnlList.GetChannel(i)).GetUrlsForUri(uri);
// Add the strings to the table
for(int j = 0; j < urls.Length; j++)
{
table.Add(urls[j], urls[j]);
}
}
catch(NotSupportedException )
{
// We do not count the channels that do not
// support this method
}
}
}
}
}
// copy url's into string array
ICollection keys = table.Keys;
String[] urlList = new String[keys.Count];
int co = 0;
foreach (String key in keys)
{
urlList[co++] = key;
}
return urlList;
}
// Find the channel message sink associated with a given proxy
// <
[System.Security.SecurityCritical] // auto-generated
internal static IMessageSink GetChannelSinkForProxy(Object obj)
{
IMessageSink sink = null;
if (RemotingServices.IsTransparentProxy(obj))
{
RealProxy rp = RemotingServices.GetRealProxy(obj);
RemotingProxy remProxy = rp as RemotingProxy;
if (null != remProxy)
{
Identity idObj = remProxy.IdentityObject;
Contract.Assert(null != idObj,"null != idObj");
sink = idObj.ChannelSink;
}
}
return sink;
} // GetChannelSinkForProxy
// Get the message sink dictionary of properties for a given proxy
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute(SecurityAction.Demand, Flags=SecurityPermissionFlag.RemotingConfiguration)]
public static IDictionary GetChannelSinkProperties(Object obj)
{
IMessageSink sink = GetChannelSinkForProxy(obj);
IClientChannelSink chnlSink = sink as IClientChannelSink;
if (null != chnlSink)
{
// collect dictionaries for all channel sinks and return
// aggregate dictionary
ArrayList dictionaries = new ArrayList();
do
{
IDictionary dict = chnlSink.Properties;
if (dict != null)
dictionaries.Add(dict);
chnlSink = chnlSink.NextChannelSink;
} while (chnlSink != null);
return new AggregateDictionary(dictionaries);
}
else
{
IDictionary dict = sink as IDictionary;
if(null != dict)
{
return dict;
}
else
{
return null;
}
}
} // GetChannelSinkProperties
internal static IMessageSink GetCrossContextChannelSink()
{
if(null == xCtxChannel)
{
xCtxChannel = CrossContextChannel.MessageSink;
}
return xCtxChannel;
} // GetCrossContextChannelSink
#if DEBUG
// A few methods to count the number of calls made across appdomains,
// processes and machines
internal static long GetNumberOfRemoteCalls()
{
return remoteCalls;
} // GetNumberOfRemoteCalls
#endif //DEBUG
[System.Security.SecurityCritical] // auto-generated
unsafe internal static void IncrementRemoteCalls(long cCalls)
{
remoteCalls += cCalls;
if (perf_Contexts != null)
perf_Contexts->cRemoteCalls += (int)cCalls;
} // IncrementRemoteCalls
[System.Security.SecurityCritical] // auto-generated
internal static void IncrementRemoteCalls()
{
IncrementRemoteCalls( 1 );
} // IncrementRemoteCalls
[System.Security.SecurityCritical] // auto-generated
internal static void RefreshChannelData()
{
bool fLocked = false;
RuntimeHelpers.PrepareConstrainedRegions();
try
{
Monitor.Enter(s_channelLock, ref fLocked);
s_currentChannelData = CollectChannelDataFromChannels();
}
finally
{
if (fLocked)
{
Monitor.Exit(s_channelLock);
}
}
} // RefreshChannelData
[System.Security.SecurityCritical] // auto-generated
private static Object[] CollectChannelDataFromChannels()
{
// Ensure that our native cross-context & cross-domain channels
// are registered
RemotingServices.RegisterWellKnownChannels();
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
// Compute the number of channels that implement IChannelReceiver
int numChnls = regChnlList.ReceiverCount;
// Allocate array for channel data
Object[] data = new Object[numChnls];
// we need to remove null entries
int nonNullDataCount = 0;
// Set the channel data, names and mime types
for (int i = 0, j = 0; i < count; i++)
{
IChannel chnl = regChnlList.GetChannel(i);
if (null == chnl)
{
throw new RemotingException(Environment.GetResourceString("Remoting_ChannelNotRegistered", ""));
}
if (regChnlList.IsReceiver(i))
{
BCLDebug.Trace("REMOTE", "Setting info for receiver " + j.ToString(CultureInfo.InvariantCulture) + "\n");
// Extract the data
Object channelData = ((IChannelReceiver)chnl).ChannelData;
data[j] = channelData;
if (channelData != null)
nonNullDataCount++;
// Increment the counter
j++;
}
}
if (nonNullDataCount != numChnls)
{
// there were null entries, so remove them.
Object[] nonNullData = new Object[nonNullDataCount];
int nonNullCounter = 0;
for (int co = 0; co < numChnls; co++)
{
Object channelData = data[co];
if (channelData != null)
nonNullData[nonNullCounter++] = channelData;
}
data = nonNullData;
}
return data;
} // CollectChannelDataFromChannels
// Checks to make sure the remote method being invoked is callable
static bool IsMethodReallyPublic(MethodInfo mi)
{
if (!mi.IsPublic || mi.IsStatic)
return false;
if (!mi.IsGenericMethod)
return true;
foreach (Type t in mi.GetGenericArguments())
if (!t.IsVisible)
return false;
return true;
}
//--------------------------------------------------------------------
//----------------------- Dispatch Support ------------------------
//--------------------------------------------------------------------
[System.Security.SecurityCritical] // auto-generated_required
public static ServerProcessing DispatchMessage(
IServerChannelSinkStack sinkStack,
IMessage msg,
out IMessage replyMsg)
{
ServerProcessing processing = ServerProcessing.Complete;
replyMsg = null;
try
{
if(null == msg)
{
throw new ArgumentNullException("msg");
}
BCLDebug.Trace("REMOTE", "Dispatching for URI " + InternalSink.GetURI(msg));
// we must switch to the target context of the object and call the context chains etc...
// Currenly XContextChannel does exactly so. So this method is just a wrapper..
// <
// Make sure that incoming calls are counted as a remote call. This way it
// makes more sense on a server.
IncrementRemoteCalls();
// Check if the object has been disconnected or if it is
// a well known object then we have to create it lazily.
ServerIdentity srvId = CheckDisconnectedOrCreateWellKnownObject(msg);
// Make sure that this isn't an AppDomain object since we don't allow
// calls to the AppDomain from out of process (and x-process calls
// are always dispatched through this method)
if (srvId.ServerType == typeof(System.AppDomain))
{
throw new RemotingException(
Environment.GetResourceString(
"Remoting_AppDomainsCantBeCalledRemotely"));
}
IMethodCallMessage mcm = msg as IMethodCallMessage;
if (mcm == null)
{
// It's a plain IMessage, so just check to make sure that the
// target object implements IMessageSink and dispatch synchronously.
if (!typeof(IMessageSink).IsAssignableFrom(srvId.ServerType))
{
throw new RemotingException(
Environment.GetResourceString(
"Remoting_AppDomainsCantBeCalledRemotely"));
}
processing = ServerProcessing.Complete;
replyMsg = ChannelServices.GetCrossContextChannelSink().SyncProcessMessage(msg);
}
else
{
// It's an IMethodCallMessage.
// Check if the method is one way. Dispatch one way calls in
// an asynchronous manner
MethodInfo method = (MethodInfo)mcm.MethodBase;
// X-process / X-machine calls should be to non-static
// public methods only! Non-public or static methods can't
// be called remotely.
if (!IsMethodReallyPublic(method) &&
!RemotingServices.IsMethodAllowedRemotely(method))
{
throw new RemotingException(
Environment.GetResourceString(
"Remoting_NonPublicOrStaticCantBeCalledRemotely"));
}
RemotingMethodCachedData cache = (RemotingMethodCachedData)
InternalRemotingServices.GetReflectionCachedData(method);
/*
*/
if(RemotingServices.IsOneWay(method))
{
processing = ServerProcessing.OneWay;
ChannelServices.GetCrossContextChannelSink().AsyncProcessMessage(msg, null);
}
else
{
// regular processing
processing = ServerProcessing.Complete;
if (!srvId.ServerType.IsContextful)
{
Object[] args = new Object[]{msg, srvId.ServerContext};
replyMsg = (IMessage) CrossContextChannel.SyncProcessMessageCallback(args);
}
else
replyMsg = ChannelServices.GetCrossContextChannelSink().SyncProcessMessage(msg);
}
} // end of case for IMethodCallMessage
}
catch(Exception e)
{
if(processing != ServerProcessing.OneWay)
{
try
{
IMethodCallMessage mcm =
(IMethodCallMessage) ((msg!=null)?msg:new ErrorMessage());
replyMsg = (IMessage)new ReturnMessage(e, mcm);
if (msg != null)
{
((ReturnMessage)replyMsg).SetLogicalCallContext(
(LogicalCallContext)
msg.Properties[Message.CallContextKey]);
}
}
catch(Exception )
{
// Fatal exception .. ignore
}
}
}
return processing;
} // DispatchMessage
// This method is used by the channel to dispatch the incoming messages
// to the server side chain(s) based on the URI embedded in the message.
// The URI uniquely identifies the receiving object.
//
[System.Security.SecurityCritical] // auto-generated_required
public static IMessage SyncDispatchMessage(IMessage msg)
{
IMessage msgRet = null;
bool fIsOneWay = false;
try
{
if(null == msg)
{
throw new ArgumentNullException("msg");
}
// For ContextBoundObject's,
// we must switch to the target context of the object and call the context chains etc...
// Currenly XContextChannel does exactly so. So this method is just a wrapper..
// Make sure that incoming calls are counted as a remote call. This way it
// makes more sense on a server.
IncrementRemoteCalls();
// <
if (!(msg is TransitionCall))
{
// Check if the object has been disconnected or if it is
// a well known object then we have to create it lazily.
CheckDisconnectedOrCreateWellKnownObject(msg);
MethodBase method = ((IMethodMessage)msg).MethodBase;
// Check if the method is one way. Dispatch one way calls in
// an asynchronous manner
fIsOneWay = RemotingServices.IsOneWay(method);
}
// <
IMessageSink nextSink = ChannelServices.GetCrossContextChannelSink();
if(!fIsOneWay)
{
msgRet = nextSink.SyncProcessMessage(msg);
}
else
{
nextSink.AsyncProcessMessage(msg, null);
}
}
catch(Exception e)
{
if(!fIsOneWay)
{
try
{
IMethodCallMessage mcm =
(IMethodCallMessage) ((msg!=null)?msg:new ErrorMessage());
msgRet = (IMessage)new ReturnMessage(e, mcm);
if (msg!=null)
{
((ReturnMessage)msgRet).SetLogicalCallContext(
mcm.LogicalCallContext);
}
}
catch(Exception )
{
// Fatal exception .. ignore
}
}
}
return msgRet;
}
// This method is used by the channel to dispatch the incoming messages
// to the server side chain(s) based on the URI embedded in the message.
// The URI uniquely identifies the receiving object.
//
[System.Security.SecurityCritical] // auto-generated_required
public static IMessageCtrl AsyncDispatchMessage(IMessage msg, IMessageSink replySink)
{
IMessageCtrl ctrl = null;
try
{
if(null == msg)
{
throw new ArgumentNullException("msg");
}
// we must switch to the target context of the object and call the context chains etc...
// Currenly XContextChannel does exactly so. So this method is just a wrapper..
// Make sure that incoming calls are counted as a remote call. This way it
// makes more sense on a server.
IncrementRemoteCalls();
if (!(msg is TransitionCall))
{
// Check if the object has been disconnected or if it is
// a well known object then we have to create it lazily.
CheckDisconnectedOrCreateWellKnownObject(msg);
}
// <
ctrl = ChannelServices.GetCrossContextChannelSink().AsyncProcessMessage(msg, replySink);
}
catch(Exception e)
{
if(null != replySink)
{
try
{
IMethodCallMessage mcm = (IMethodCallMessage)msg;
ReturnMessage retMsg = new ReturnMessage(e, (IMethodCallMessage)msg);
if (msg!=null)
{
retMsg.SetLogicalCallContext(mcm.LogicalCallContext);
}
replySink.SyncProcessMessage(retMsg);
}
catch(Exception )
{
// Fatal exception... ignore
}
}
}
return ctrl;
} // AsyncDispatchMessage
// Creates a channel sink chain (adds special dispatch sink to the end of the chain)
[System.Security.SecurityCritical] // auto-generated_required
public static IServerChannelSink CreateServerChannelSinkChain(
IServerChannelSinkProvider provider, IChannelReceiver channel)
{
if (provider == null)
return new DispatchChannelSink();
// add dispatch provider to end (first find last provider)
IServerChannelSinkProvider lastProvider = provider;
while (lastProvider.Next != null)
lastProvider = lastProvider.Next;
lastProvider.Next = new DispatchChannelSinkProvider();
IServerChannelSink sinkChain = provider.CreateSink(channel);
// remove dispatch provider from end
lastProvider.Next = null;
return sinkChain;
} // CreateServerChannelSinkChain
// Check if the object has been disconnected or if it is
// a well known object then we have to create it lazily.
[System.Security.SecurityCritical] // auto-generated
internal static ServerIdentity CheckDisconnectedOrCreateWellKnownObject(IMessage msg)
{
ServerIdentity ident = InternalSink.GetServerIdentity(msg);
BCLDebug.Trace("REMOTE", "Identity found = " + (ident == null ? "null" : "ServerIdentity"));
// If the identity is null, then we should check whether the
// request if for a well known object. If yes, then we should
// create the well known object lazily and marshal it.
if ((ident == null) || ident.IsRemoteDisconnected())
{
String uri = InternalSink.GetURI(msg);
BCLDebug.Trace("REMOTE", "URI " + uri);
if (uri != null)
{
ServerIdentity newIdent = RemotingConfigHandler.CreateWellKnownObject(uri);
if (newIdent != null)
{
// The uri was a registered wellknown object.
ident = newIdent;
BCLDebug.Trace("REMOTE", "Identity created = " + (ident == null ? "null" : "ServerIdentity"));
}
}
}
if ((ident == null) || (ident.IsRemoteDisconnected()))
{
String uri = InternalSink.GetURI(msg);
throw new RemotingException(Environment.GetResourceString("Remoting_Disconnected",uri));
}
return ident;
}
// Channel Services AppDomain Unload Event Handler
[System.Security.SecurityCritical] // auto-generated
internal static void UnloadHandler(Object sender, EventArgs e)
{
StopListeningOnAllChannels();
}
[System.Security.SecurityCritical] // auto-generated
private static void StopListeningOnAllChannels()
{
try
{
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
for(int i = 0; i < count; i++)
{
if(regChnlList.IsReceiver(i))
{
IChannelReceiver chnl = (IChannelReceiver)regChnlList.GetChannel(i);
chnl.StopListening(null);
}
}
}
catch (Exception)
{
// Ignore ... appdomain is shutting down..
}
}
//
// INTERNAL PROFILER NOTIFICATION SERVICES
//
[System.Security.SecurityCritical] // auto-generated
internal static void NotifyProfiler(IMessage msg, RemotingProfilerEvent profilerEvent)
{
switch (profilerEvent)
{
case RemotingProfilerEvent.ClientSend:
{
if (RemotingServices.CORProfilerTrackRemoting())
{
Guid g;
RemotingServices.CORProfilerRemotingClientSendingMessage(out g, false);
if (RemotingServices.CORProfilerTrackRemotingCookie())
msg.Properties["CORProfilerCookie"] = g;
}
break;
} // case RemotingProfilerEvent.ClientSend
case RemotingProfilerEvent.ClientReceive:
{
if (RemotingServices.CORProfilerTrackRemoting())
{
Guid g = Guid.Empty;
if (RemotingServices.CORProfilerTrackRemotingCookie())
{
Object obj = msg.Properties["CORProfilerCookie"];
if (obj != null)
{
g = (Guid) obj;
}
}
RemotingServices.CORProfilerRemotingClientReceivingReply(g, false);
}
break;
} // case RemotingProfilerEvent.ClientReceive
} // switch (event)
} // NotifyProfiler
// This is a helper used by UrlObjRef's.
// Finds an http channel and returns first url for this object.
[System.Security.SecurityCritical] // auto-generated
internal static String FindFirstHttpUrlForObject(String objectUri)
{
if (objectUri == null)
return null;
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
for (int i = 0; i < count; i++)
{
if(regChnlList.IsReceiver(i))
{
IChannelReceiver chnl = (IChannelReceiver)regChnlList.GetChannel(i);
String chnlType = chnl.GetType().FullName;
if ((String.CompareOrdinal(chnlType, "System.Runtime.Remoting.Channels.Http.HttpChannel") == 0) ||
(String.CompareOrdinal(chnlType, "System.Runtime.Remoting.Channels.Http.HttpServerChannel") == 0))
{
String[] urls = chnl.GetUrlsForUri(objectUri);
if ((urls != null) && (urls.Length > 0))
return urls[0];
}
}
}
return null;
} // FindFirstHttpUrlForObject
//
// DEBUG Helpers
// Note: These methods should be included even in retail builds so that
// they can be called from the debugger.
//
#if DEBUG
internal static void DumpRegisteredChannels()
{
// To use from cordbg:
// f System.Runtime.Remoting.Channels.ChannelServices::DumpRegisteredChannels
RegisteredChannelList regChnlList = s_registeredChannels;
int count = regChnlList.Count;
Console.Error.WriteLine("Registered Channels:");
for (int i = 0; i < count; i++)
{
IChannel chnl = regChnlList.GetChannel(i);
Console.Error.WriteLine(chnl);
}
} // DumpRegisteredChannels
#endif // DEBUG
} // class ChannelServices
// used by ChannelServices.NotifyProfiler
[Serializable]
internal enum RemotingProfilerEvent
{
ClientSend,
ClientReceive
} // RemotingProfilerEvent
internal class RegisteredChannel
{
// private member variables
private IChannel channel;
private byte flags;
private const byte SENDER = 0x1;
private const byte RECEIVER = 0x2;
internal RegisteredChannel(IChannel chnl)
{
channel = chnl;
flags = 0;
if(chnl is IChannelSender)
{
flags |= SENDER;
}
if(chnl is IChannelReceiver)
{
flags |= RECEIVER;
}
}
internal virtual IChannel Channel
{
get { return channel; }
}
internal virtual bool IsSender()
{
return ((flags & SENDER) != 0);
}
internal virtual bool IsReceiver()
{
return ((flags & RECEIVER) != 0);
}
}// class RegisteredChannel
// This list should be considered immutable once created.
// <
internal class RegisteredChannelList
{
private RegisteredChannel[] _channels;
internal RegisteredChannelList()
{
_channels = new RegisteredChannel[0];
} // RegisteredChannelList
internal RegisteredChannelList(RegisteredChannel[] channels)
{
_channels = channels;
} // RegisteredChannelList
internal RegisteredChannel[] RegisteredChannels
{
get { return _channels; }
} // RegisteredChannels
internal int Count
{
get
{
if (_channels == null)
return 0;
return _channels.Length;
}
} // Count
internal IChannel GetChannel(int index)
{
return _channels[index].Channel;
} // GetChannel
internal bool IsSender(int index)
{
return _channels[index].IsSender();
} // IsSender
internal bool IsReceiver(int index)
{
return _channels[index].IsReceiver();
} // IsReceiver
internal int ReceiverCount
{
get
{
if (_channels == null)
return 0;
int total = 0;
for (int i = 0; i < _channels.Length; i++)
{
if (IsReceiver(i))
total++;
}
return total;
}
} // ReceiverCount
internal int FindChannelIndex(IChannel channel)
{
Object chnlAsObject = (Object)channel;
for (int i = 0; i < _channels.Length; i++)
{
if (chnlAsObject == (Object)GetChannel(i))
return i;
}
return -1;
} // FindChannelIndex
[System.Security.SecurityCritical] // auto-generated
internal int FindChannelIndex(String name)
{
for (int i = 0; i < _channels.Length; i++)
{
if(String.Compare(name, GetChannel(i).ChannelName, StringComparison.OrdinalIgnoreCase) == 0)
return i;
}
return -1;
} // FindChannelIndex
} // class RegisteredChannelList
internal class ChannelServicesData
{
internal long remoteCalls = 0;
internal CrossContextChannel xctxmessageSink = null;
internal CrossAppDomainChannel xadmessageSink = null;
internal bool fRegisterWellKnownChannels = false;
}
//
// Terminator sink used for profiling so that we can intercept asynchronous
// replies on the server side.
//
/* package scope */
internal class ServerAsyncReplyTerminatorSink : IMessageSink
{
internal IMessageSink _nextSink;
internal ServerAsyncReplyTerminatorSink(IMessageSink nextSink)
{
Contract.Assert(nextSink != null,
"null IMessageSink passed to ServerAsyncReplyTerminatorSink ctor.");
_nextSink = nextSink;
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessage SyncProcessMessage(IMessage replyMsg)
{
// If this class has been brought into the picture, then the following must be true.
Contract.Assert(RemotingServices.CORProfilerTrackRemoting(),
"CORProfilerTrackRemoting returned false, but we're in AsyncProcessMessage!");
Contract.Assert(RemotingServices.CORProfilerTrackRemotingAsync(),
"CORProfilerTrackRemoting returned false, but we're in AsyncProcessMessage!");
Guid g;
// Notify the profiler that we are receiving an async reply from the server-side
RemotingServices.CORProfilerRemotingServerSendingReply(out g, true);
// If GUID cookies are active, then we save it for the other end of the channel
if (RemotingServices.CORProfilerTrackRemotingCookie())
replyMsg.Properties["CORProfilerCookie"] = g;
// Now that we've done the intercepting, pass the message on to the regular chain
return _nextSink.SyncProcessMessage(replyMsg);
}
[System.Security.SecurityCritical] // auto-generated
public virtual IMessageCtrl AsyncProcessMessage(IMessage replyMsg, IMessageSink replySink)
{
// Since this class is only used for intercepting async replies, this function should
// never get called. (Async replies are synchronous, ironically)
Contract.Assert(false, "ServerAsyncReplyTerminatorSink.AsyncProcessMessage called!");
return null;
}
public IMessageSink NextSink
{
[System.Security.SecurityCritical] // auto-generated
get
{
return _nextSink;
}
}
// Do I need a finalize here?
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace System.Collections.Tests
{
public static class HashtableTests
{
[Fact]
public static void TestCtor_Empty()
{
var hash = new ComparableHashtable();
VerifyHashtable(hash, null, null);
}
[Fact]
public static void TestCtor_IDictionary()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable());
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))));
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public static void TestCtor_IDictionary_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new Hashtable((IDictionary)null)); // Dictionary is null
}
[Fact]
public static void TestCtor_IEqualityComparer()
{
// Null comparer
var hash = new ComparableHashtable((IEqualityComparer)null);
VerifyHashtable(hash, null, null);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
public static void TestCtor_Capacity(int capacity)
{
var hash = new ComparableHashtable(capacity);
VerifyHashtable(hash, null, null);
}
[Fact]
public static void TestCtor_Capacity_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(-1)); // Capacity < 0
Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue
}
[Fact]
public static void TestCtor_IDictionary_LoadFactor()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f);
Assert.Equal(0, hash1.Count);
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f);
VerifyHashtable(hash1, hash2, null);
}
[Fact]
public static void TestCtor_IDictionary_LoadFactor_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new Hashtable(null, 1f)); // Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity
}
[Fact]
public static void TestCtor_IDictionary_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, null);
VerifyHashtable(hash1, hash2, null);
// Custom comparer
hash2 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, comparer);
VerifyHashtable(hash1, hash2, comparer);
});
}
[Fact]
public static void TestCtor_IDictionary_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new Hashtable(null, null)); // Dictionary is null
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public static void TestCtor_Capacity_LoadFactor(int capacity, float loadFactor)
{
var hash = new ComparableHashtable(capacity, loadFactor);
VerifyHashtable(hash, null, null);
}
[Fact]
public static void TestCtor_Capacity_LoadFactor_GenerateNewPrime()
{
// The ctor for Hashtable performs the following calculation:
// rawSize = capacity / (loadFactor * 0.72)
// If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime.
// Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically
// This test makes sure this works.
int capacity = 8000000;
float loadFactor = 0.1f / 0.72f;
try
{
var hash = new ComparableHashtable(capacity, loadFactor);
}
catch (OutOfMemoryException)
{
// On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore.
}
}
[Fact]
public static void TestCtor_Capacity_LoadFactor_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(-1, 1f)); // Capacity < 0
Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, 0.09f)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, 1.01f)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, float.NaN)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void TestCtor_Capacity_IEqualityComparer(int capacity)
{
// Null comparer
var hash = new ComparableHashtable(capacity, null);
VerifyHashtable(hash, null, null);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Fact]
public static void TestCtor_Capacity_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(-1, null)); // Capacity < 0
Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue
}
[Fact]
public static void TestCtor_IDictionary_LoadFactor_IEqualityComparer()
{
// No exception
var hash1 = new ComparableHashtable(new Hashtable(), 1f, null);
Assert.Equal(0, hash1.Count);
hash1 = new ComparableHashtable(new Hashtable(new Hashtable(
new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null);
Assert.Equal(0, hash1.Count);
// Null comparer
Hashtable hash2 = Helpers.CreateIntHashtable(100);
hash1 = new ComparableHashtable(hash2, 1f, null);
VerifyHashtable(hash1, hash2, null);
hash2 = Helpers.CreateIntHashtable(100);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash1 = new ComparableHashtable(hash2, 1f, comparer);
VerifyHashtable(hash1, hash2, comparer);
});
}
[Fact]
public static void TestCtor_IDictionary_LoadFactor_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentNullException>(() => new Hashtable(null, 1f, null)); // Dictionary is null
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity
}
[Theory]
[InlineData(0, 0.1)]
[InlineData(10, 0.2)]
[InlineData(100, 0.3)]
[InlineData(1000, 1)]
public static void TestCtor_Capacity_LoadFactor_IEqualityComparer(int capacity, float loadFactor)
{
// Null comparer
var hash = new ComparableHashtable(capacity, loadFactor, null);
VerifyHashtable(hash, null, null);
Assert.Null(hash.EqualityComparer);
// Custom comparer
Helpers.PerformActionOnCustomCulture(() =>
{
IEqualityComparer comparer = StringComparer.CurrentCulture;
hash = new ComparableHashtable(capacity, loadFactor, comparer);
VerifyHashtable(hash, null, comparer);
});
}
[Fact]
public static void TestCtor_Capacit_yLoadFactor_IEqualityComparer_Invalid()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(-1, 1f, null)); // Capacity < 0
Assert.Throws<ArgumentException>(() => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, 1.01f, null)); // Load factor > 1f
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, float.NaN, null)); // Load factor is NaN
Assert.Throws<ArgumentOutOfRangeException>(() => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity
}
[Fact]
public static void TestDebuggerAttribute()
{
DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable());
var hash = new Hashtable() { { "a", 1 }, { "b", 2 } };
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash);
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash));
bool threwNull = false;
try
{
DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null);
}
catch (TargetInvocationException ex)
{
ArgumentNullException nullException = ex.InnerException as ArgumentNullException;
threwNull = nullException != null;
}
Assert.True(threwNull);
}
[Theory]
[InlineData(1)]
[InlineData(10)]
[InlineData(100)]
[InlineData(1000)]
public static void TestAdd(int count)
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
hash2.Add(key, value);
Assert.Equal(i + 1, hash2.Count);
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.ContainsValue(value));
Assert.Equal(value, hash2[key]);
}
Assert.Equal(count, hash2.Count);
});
}
[Fact]
public static void TestAdd_ReferenceType()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
// Value is a reference
var foo = new Foo();
hash2.Add("Key", foo);
Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue);
// Changing original object should change the object stored in the Hashtable
foo.StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue);
});
}
[Fact]
public static void TestAdd_Invalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2.Add(null, 1)); // Key is null
Assert.Throws<ArgumentException>(() => hash2.Add("Key_1", "Value_2")); // Key already exists
});
}
[Fact]
public static void TestAdd_ClearRepeatedly()
{
const int Iterations = 2;
const int Count = 2;
var hash = new Hashtable();
for (int i = 0; i < Iterations; i++)
{
for (int j = 0; j < Count; j++)
{
string key = "Key: i=" + i + ", j=" + j;
string value = "Value: i=" + i + ", j=" + j;
hash.Add(key, value);
}
Assert.Equal(Count, hash.Count);
hash.Clear();
}
}
[Fact]
[OuterLoop]
public static void TestAddRemove_LargeAmountNumbers()
{
// Generate a random 100,000 array of ints as test data
var inputData = new int[100000];
var random = new Random(341553);
for (int i = 0; i < inputData.Length; i++)
{
inputData[i] = random.Next(7500000, int.MaxValue);
}
var hash = new Hashtable();
int count = 0;
foreach (long number in inputData)
{
hash.Add(number, count++);
}
count = 0;
foreach (long number in inputData)
{
Assert.Equal(hash[number], count);
Assert.True(hash.ContainsKey(number));
count++;
}
foreach (long number in inputData)
{
hash.Remove(number);
}
Assert.Equal(0, hash.Count);
}
[Fact]
public static void TestDuplicatedKeysWithInitialCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable(200);
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Fact]
public static void TestDuplicatedKeysWithDefaultCapacity()
{
// Make rehash get called because to many items with duplicated keys have been added to the hashtable
var hash = new Hashtable();
const int Iterations = 1600;
for (int i = 0; i < Iterations; i += 2)
{
hash.Add(new BadHashCode(i), i.ToString());
hash.Add(new BadHashCode(i + 1), (i + 1).ToString());
hash.Remove(new BadHashCode(i));
hash.Remove(new BadHashCode(i + 1));
}
for (int i = 0; i < Iterations; i++)
{
hash.Add(i.ToString(), i);
}
for (int i = 0; i < Iterations; i++)
{
Assert.Equal(i, hash[i.ToString()]);
}
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void TestClear(int count)
{
Hashtable hash1 = Helpers.CreateIntHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
hash2.Clear();
for (int i = 0; i < hash2.Count; i++)
{
Assert.False(hash2.ContainsKey(i));
Assert.False(hash2.ContainsValue(i));
}
Assert.Equal(0, hash2.Count);
hash2.Clear();
Assert.Equal(0, hash2.Count);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void TestClone(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Hashtable clone = (Hashtable)hash2.Clone();
Assert.Equal(hash2.Count, clone.Count);
Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized);
Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize);
Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly);
for (int i = 0; i < clone.Count; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
Assert.True(clone.ContainsKey(key));
Assert.True(clone.ContainsValue(value));
Assert.Equal(value, clone[key]);
}
});
}
[Fact]
public static void TestClone_IsShallowCopy()
{
var hash = new Hashtable();
for (int i = 0; i < 10; i++)
{
hash.Add(i, new Foo());
}
Hashtable clone = (Hashtable)hash.Clone();
for (int i = 0; i < clone.Count; i++)
{
Assert.Equal("Hello World", ((Foo)clone[i]).StringValue);
Assert.Same(hash[i], clone[i]);
}
// Change object in original hashtable
((Foo)hash[1]).StringValue = "Goodbye";
Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue);
// Removing an object from the original hashtable doesn't change the clone
hash.Remove(0);
Assert.True(clone.Contains(0));
}
[Fact]
public static void TestClone_HashtableCastedToInterfaces()
{
// Try to cast the returned object from Clone() to different types
Hashtable hash = Helpers.CreateIntHashtable(100);
ICollection collection = (ICollection)hash.Clone();
Assert.Equal(hash.Count, collection.Count);
IDictionary dictionary = (IDictionary)hash.Clone();
Assert.Equal(hash.Count, dictionary.Count);
}
[Fact]
public static void TestContainsKey()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.True(hash2.ContainsKey(key));
Assert.True(hash2.Contains(key));
}
Assert.False(hash2.ContainsKey("Non Existent Key"));
Assert.False(hash2.Contains("Non Existent Key"));
Assert.False(hash2.ContainsKey(101));
Assert.False(hash2.Contains("Non Existent Key"));
string removedKey = "Key_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsKey(removedKey));
Assert.False(hash2.Contains(removedKey));
});
}
[Fact]
public static void TestContainsKey_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(foo1, 101);
Assert.True(hash2.ContainsKey(foo2));
Assert.True(hash2.Contains(foo2));
int i1 = 0x10;
int i2 = 0x100;
long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode
long l2 = (((long)i2) << 32) + i1;
hash2.Add(l1, 101);
hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set
Assert.True(hash2.ContainsKey(l1));
Assert.True(hash2.Contains(l1));
hash2.Remove(l1); // Remove the first item
Assert.False(hash2.ContainsKey(l1));
Assert.False(hash2.Contains(l1));
Assert.True(hash2.ContainsKey(l2));
Assert.True(hash2.Contains(l2));
});
}
[Fact]
public static void TestContainsKey_Invalid()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2.ContainsKey(null)); // Key is null
Assert.Throws<ArgumentNullException>(() => hash2.Contains(null)); // Key is null
});
}
[Fact]
public static void TestContainsValue()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string value = "Value_" + i;
Assert.True(hash2.ContainsValue(value));
}
Assert.False(hash2.ContainsValue("Non Existent Value"));
Assert.False(hash2.ContainsValue(101));
Assert.False(hash2.ContainsValue(null));
hash2.Add("Key_101", null);
Assert.True(hash2.ContainsValue(null));
string removedKey = "Key_1";
string removedValue = "Value_1";
hash2.Remove(removedKey);
Assert.False(hash2.ContainsValue(removedValue));
});
}
[Fact]
public static void TestContainsValue_EqualObjects()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var foo1 = new Foo() { StringValue = "Goodbye" };
var foo2 = new Foo() { StringValue = "Goodbye" };
hash2.Add(101, foo1);
Assert.True(hash2.ContainsValue(foo2));
});
}
[Fact]
public static void TestCopyTo()
{
var hash1 = new Hashtable();
var keys = new object[]
{
new object(),
"Hello" ,
"my array" ,
new DateTime(),
new SortedList(),
typeof(Environment),
5
};
var values = new object[]
{
"Somestring" ,
new object(),
new int [] { 1, 2, 3, 4, 5 },
new Hashtable(),
new Exception(),
new Guid(),
null
};
for (int i = 0; i < values.Length; i++)
{
hash1.Add(keys[i], values[i]);
}
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var array = new object[values.Length + 2];
array[0] = "start-string";
array[values.Length + 1] = "end-string";
hash2.CopyTo(array, 1);
Assert.Equal("start-string", array[0]);
Assert.Equal("end-string", array[values.Length + 1]);
Assert.Equal(values.Length + 2, array.Length);
for (int i = 1; i < array.Length - 1; i++)
{
DictionaryEntry entry = (DictionaryEntry)array[i];
int valueIndex = Array.IndexOf(values, entry.Value);
int keyIndex = Array.IndexOf(keys, entry.Key);
Assert.NotEqual(-1, valueIndex);
Assert.NotEqual(-1, keyIndex);
Assert.Equal(valueIndex, keyIndex);
}
});
}
[Fact]
public static void TestCopyTo_EmptyHashtable()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
var array = new object[0];
hash2.CopyTo(array, 0);
Assert.Equal(0, array.Length);
array = new object[100];
for (int i = 0; i < array.Length; i++)
{
array[i] = i;
}
// Both of these should be valid
hash2.CopyTo(array, 99);
hash2.CopyTo(array, 100);
Assert.Equal(100, array.Length);
for (int i = 0; i < array.Length; i++)
{
Assert.Equal(i, array[i]);
}
});
}
[Fact]
public static void TestCopyTo_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(10);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => hash2.CopyTo(new object[10, 10], 0)); // Array is multidimensional
Assert.Throws<InvalidCastException>(() => hash2.CopyTo(new object[10][], 0)); // Array is invalid
Assert.Throws<ArgumentOutOfRangeException>(() => hash2.CopyTo(new object[10], -1)); // Index < 0
Assert.Throws<ArgumentException>(() => hash2.CopyTo(new object[9], 0)); // Hash.Count + index > array.Length
Assert.Throws<ArgumentException>(() => hash2.CopyTo(new object[11], 2)); // Hash.Count + index > array.Length
Assert.Throws<ArgumentException>(() => hash2.CopyTo(new object[0], 0)); // Hash.Count + index > array.Length
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void TestGetEnumerator_IDictionaryEnumerator(int count)
{
Hashtable hash1 = Helpers.CreateIntHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IDictionaryEnumerator enumerator1 = hash2.GetEnumerator();
IDictionaryEnumerator enumerator2 = hash2.GetEnumerator();
Assert.NotSame(enumerator1, enumerator2);
Assert.NotNull(enumerator1);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator1.MoveNext())
{
DictionaryEntry entry1 = (DictionaryEntry)enumerator1.Current;
DictionaryEntry entry2 = enumerator1.Entry;
Assert.Equal(entry1.Key, entry2.Key);
Assert.Equal(entry1.Value, entry2.Value);
Assert.Equal(enumerator1.Key, entry1.Key);
Assert.Equal(enumerator1.Value, entry1.Value);
Assert.Equal(enumerator1.Value, hash2[enumerator1.Key]);
counter++;
}
Assert.Equal(hash2.Count, counter);
enumerator1.Reset();
}
});
}
[Fact]
public static void TestGetEnumerator_IDictionaryEnumerator_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IDictionaryEnumerator enumerator = hash2.GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Index > dictionary.Count
while (enumerator.MoveNext()) ;
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.Entry);
Assert.Throws<InvalidOperationException>(() => enumerator.Key);
Assert.Throws<InvalidOperationException>(() => enumerator.Value);
// MoveNext and Reset throw after modifying the hashtable
enumerator.MoveNext();
hash2.Add("Key", "Value");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
Assert.NotNull(enumerator.Entry);
Assert.NotNull(enumerator.Key);
Assert.NotNull(enumerator.Value);
});
}
[Theory]
[InlineData(0)]
[InlineData(100)]
public static void TestGetEnumerator_IEnumerator(int count)
{
Hashtable hash1 = Helpers.CreateStringHashtable(count);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IEnumerator enumerator1 = ((IEnumerable)hash2).GetEnumerator();
IDictionaryEnumerator enumerator2 = hash2.GetEnumerator();
Assert.NotSame(enumerator1, enumerator2);
Assert.NotNull(enumerator1);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enumerator1.MoveNext())
{
DictionaryEntry entry = (DictionaryEntry)enumerator1.Current;
Assert.Equal(entry.Value, hash2[entry.Key]);
counter++;
}
Assert.Equal(hash2.Count, counter);
enumerator1.Reset();
}
});
}
[Fact]
public static void TestGetEnumerator_IEnumerator_Invalid()
{
Hashtable hash1 = Helpers.CreateIntHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
IEnumerator enumerator = ((IEnumerable)hash2).GetEnumerator();
// Index < 0
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// Index >= dictionary.Count
while (enumerator.MoveNext()) ;
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
// Current throws after resetting
enumerator.Reset();
Assert.True(enumerator.MoveNext());
enumerator.Reset();
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
// MoveNext and Reset throw after modifying the hashtable
enumerator.MoveNext();
hash2.Add("Key", "Value");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
Assert.NotNull(enumerator.Current);
});
}
[Fact]
public static void TestGetItem()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Equal(null, hash2["No_Such_Key"]);
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
Assert.Equal("Value_" + i, hash2[key]);
hash2.Remove(key);
Assert.Equal(null, hash2[key]);
}
});
}
[Fact]
public static void TestGetItem_Invalid()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2[null]); // Key is null
});
}
[Fact]
public static void TestSetItem()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < 100; i++)
{
string key = "Key_" + i;
string value = "Value_" + i;
// Non existent key
hash2[key] = "Value";
Assert.Equal("Value", hash2[key]);
// Existent key
hash2[key] = value;
Assert.Equal(value, hash2[key]);
// Null
hash2[key] = null;
Assert.Equal(null, hash2[key]);
Assert.True(hash2.ContainsKey(key));
}
});
}
[Fact]
public static void TestSetItem_Invalid()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2[null] = "Value"); // Key is null
});
}
[Fact]
public static void TestKeys_ICollectionProperties()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys1 = hash2.Keys;
Assert.False(keys1.IsSynchronized);
Assert.Equal(hash2.SyncRoot, keys1.SyncRoot);
Assert.Equal(hash2.Count, keys1.Count);
hash2.Clear();
Assert.Equal(keys1.Count, 0);
ICollection keys2 = hash2.Keys;
Assert.Same(keys1, keys2);
});
}
[Fact]
public static void TestKeys_GetEnumerator()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
IEnumerator enum1 = keys.GetEnumerator();
IEnumerator enum2 = keys.GetEnumerator();
Assert.NotSame(enum1, enum2);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enum1.MoveNext())
{
Assert.True(hash2.ContainsKey(enum1.Current));
counter++;
}
Assert.Equal(keys.Count, counter);
enum1.Reset();
}
});
}
[Fact]
public static void TestKeys_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection keys = hash.Keys;
// Removing a key from the hashtable should update the Keys ICollection.
// This means that the Keys ICollection no longer contains the key.
hash.Remove("Key_0");
IEnumerator enumerator = keys.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Key_0", enumerator.Current);
}
}
[Fact]
public static void TestKeys_CopyTo()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
// Index = 0
object[] keysCopy = new object[keys.Count];
keys.CopyTo(keysCopy, 0);
Assert.Equal(keys.Count, keysCopy.Length);
for (int i = 0; i < keysCopy.Length; i++)
{
Assert.True(hash2.ContainsKey(keysCopy[i]));
}
// Index > 0
int index = 50;
keysCopy = new object[keys.Count + index];
keys.CopyTo(keysCopy, index);
Assert.Equal(keys.Count + index, keysCopy.Length);
for (int i = index; i < keysCopy.Length; i++)
{
Assert.True(hash2.ContainsKey(keysCopy[i]));
}
});
}
[Fact]
public static void TestKeys_CopyToInvalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection keys = hash2.Keys;
Assert.Throws<ArgumentNullException>(() => keys.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[100, 100], 0)); // Array is multidimensional
Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[50], 0)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentException>(() => keys.CopyTo(new object[100], 1)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentOutOfRangeException>(() => keys.CopyTo(new object[100], -1)); // Index < 0
});
}
[Fact]
public static void TestRemove()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
for (int i = 0; i < hash2.Count; i++)
{
string key = "Key_" + i;
hash2.Remove(key);
Assert.Equal(null, hash2[key]);
Assert.False(hash2.ContainsKey(key));
}
hash2.Remove("Non_Existent_Key");
});
}
[Fact]
public static void TestRemove_SameHashcode()
{
// We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable
// does not expand but have to tread through collision bit set positions to insert the new elements. We do this
// by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that
// the hashtable does not expand as long as we have at most 7 elements at any given time?
var hash = new Hashtable();
var arrList = new ArrayList();
for (int i = 0; i < 7; i++)
{
var hashConfuse = new BadHashCode(i);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, i);
}
var rand = new Random(-55);
int iCount = 7;
for (int i = 0; i < 100; i++)
{
for (int j = 0; j < 7; j++)
{
Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value);
}
// Delete 3 elements from the hashtable
for (int j = 0; j < 3; j++)
{
int iElement = rand.Next(6);
hash.Remove(arrList[iElement]);
Assert.False(hash.ContainsValue(null));
arrList.RemoveAt(iElement);
int testInt = iCount++;
var hashConfuse = new BadHashCode(testInt);
arrList.Add(hashConfuse);
hash.Add(hashConfuse, testInt);
}
}
}
[Fact]
public static void TestRemove_Invalid()
{
var hash1 = new Hashtable();
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
Assert.Throws<ArgumentNullException>(() => hash2.Remove(null));
});
}
[Fact]
public static void TestSynchronizedProperties()
{
// Ensure Synchronized correctly reflects a wrapped hashtable
var hash1 = Helpers.CreateStringHashtable(100);
var hash2 = Hashtable.Synchronized(hash1);
Assert.Equal(hash1.Count, hash2.Count);
Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly);
Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize);
Assert.True(hash2.IsSynchronized);
Assert.Equal(hash1.SyncRoot, hash2.SyncRoot);
for (int i = 0; i < hash2.Count; i++)
{
Assert.Equal("Value_" + i, hash2["Key_" + i]);
}
}
[Fact]
public static void TestSynchronizedInvalid()
{
Assert.Throws<ArgumentNullException>(() => Hashtable.Synchronized(null)); // Table is null
}
[Fact]
public static void TestValues_ICollectionProperties()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values1 = hash2.Values;
Assert.False(values1.IsSynchronized);
Assert.Equal(hash2.SyncRoot, values1.SyncRoot);
Assert.Equal(hash2.Count, values1.Count);
hash2.Clear();
Assert.Equal(values1.Count, 0);
ICollection values2 = hash2.Values;
Assert.Same(values1, values2);
});
}
[Fact]
public static void TestValues_GetEnumerator()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
IEnumerator enum1 = values.GetEnumerator();
IEnumerator enum2 = values.GetEnumerator();
Assert.NotSame(enum1, enum2);
for (int i = 0; i < 2; i++)
{
int counter = 0;
while (enum1.MoveNext())
{
Assert.True(hash2.ContainsValue(enum1.Current));
counter++;
}
Assert.Equal(values.Count, counter);
enum1.Reset();
}
});
}
[Fact]
public static void TestValues_ModifyingHashtable_ModifiesCollection()
{
Hashtable hash = Helpers.CreateStringHashtable(100);
ICollection values = hash.Values;
// Removing a value from the hashtable should update the Values ICollection.
// This means that the Values ICollection no longer contains the value.
hash.Remove("Key_0");
IEnumerator enumerator = values.GetEnumerator();
while (enumerator.MoveNext())
{
Assert.NotEqual("Value_0", enumerator.Current);
}
}
[Fact]
public static void TestValues_CopyTo()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
// Index = 0
object[] valuesCopy = new object[values.Count];
values.CopyTo(valuesCopy, 0);
Assert.Equal(values.Count, valuesCopy.Length);
for (int i = 0; i < valuesCopy.Length; i++)
{
Assert.True(hash2.ContainsValue(valuesCopy[i]));
}
// Index > 0
int index = 50;
valuesCopy = new object[values.Count + index];
values.CopyTo(valuesCopy, index);
Assert.Equal(values.Count + index, valuesCopy.Length);
for (int i = index; i < valuesCopy.Length; i++)
{
Assert.True(hash2.ContainsValue(valuesCopy[i]));
}
});
}
[Fact]
public static void TestValues_CopyToInvalid()
{
Hashtable hash1 = Helpers.CreateStringHashtable(100);
Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 =>
{
ICollection values = hash2.Values;
Assert.Throws<ArgumentNullException>(() => values.CopyTo(null, 0)); // Array is null
Assert.Throws<ArgumentException>(() => values.CopyTo(new object[100, 100], 0)); // Array is multidimensional
Assert.Throws<ArgumentException>(() => values.CopyTo(new object[50], 0)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentException>(() => values.CopyTo(new object[100], 1)); // Index + array.Length > hash.Count
Assert.Throws<ArgumentOutOfRangeException>(() => values.CopyTo(new object[100], -1)); // Index < 0
});
}
private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc)
{
if (hash2 == null)
{
Assert.Equal(0, hash1.Count);
}
else
{
// Make sure that construtor imports all keys and values
Assert.Equal(hash2.Count, hash1.Count);
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
// Make sure the new and old hashtables are not linked
hash2.Clear();
for (int i = 0; i < 100; i++)
{
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
Assert.Equal(ikc, hash1.EqualityComparer);
Assert.False(hash1.IsFixedSize);
Assert.False(hash1.IsReadOnly);
Assert.False(hash1.IsSynchronized);
// Make sure we can add to the hashtable
int count = hash1.Count;
for (int i = count; i < count + 100; i++)
{
hash1.Add(i, i);
Assert.True(hash1.ContainsKey(i));
Assert.True(hash1.ContainsValue(i));
}
}
private class ComparableHashtable : Hashtable
{
public ComparableHashtable() : base()
{
}
public ComparableHashtable(int capacity) : base(capacity)
{
}
public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor)
{
}
public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc)
{
}
public ComparableHashtable(IEqualityComparer ikc) : base(ikc)
{
}
public ComparableHashtable(IDictionary d) : base(d)
{
}
public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor)
{
}
public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc)
{
}
public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc)
{
}
public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc)
{
}
public new IEqualityComparer EqualityComparer
{
get
{
return base.EqualityComparer;
}
}
}
private class BadHashCode
{
public BadHashCode(int value)
{
Value = value;
}
public int Value { get; private set; }
public override bool Equals(object o)
{
BadHashCode rhValue = o as BadHashCode;
if (rhValue != null)
{
return Value.Equals(rhValue.Value);
}
else
{
throw new ArgumentException(nameof(o), "is not BadHashCode type actual " + o.GetType());
}
}
public override int GetHashCode()
{
// Return 0 for everything to force hash collisions.
return 0;
}
public override string ToString()
{
return Value.ToString();
}
}
private class Foo
{
private string _stringValue = "Hello World";
public string StringValue
{
get { return _stringValue; }
set { _stringValue = value; }
}
public override bool Equals(object obj)
{
Foo foo = obj as Foo;
if (foo == null)
{
return false;
}
return StringValue.Equals(foo.StringValue);
}
public override int GetHashCode()
{
return StringValue.GetHashCode();
}
}
}
/// <summary>
/// A hashtable can have a race condition:
/// A read operation on hashtable has three steps:
/// (1) calculate the hash and find the slot number.
/// (2) compare the hashcode, if equal, go to step 3. Otherwise end.
/// (3) compare the key, if equal, go to step 4. Otherwise end.
/// (4) return the value contained in the bucket.
/// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one
/// in the same bukcet. In order to make this happen easily, I created two long with same hashcode.
/// </summary>
public class Hashtable_ItemThreadSafetyTests
{
private object _key1;
private object _key2;
private object _value1 = "value1";
private object _value2 = "value2";
private Hashtable _hash;
private bool _errorOccurred = false;
private bool _timeExpired = false;
private const int MAX_TEST_TIME_MS = 10000; // 10 seconds
[Fact]
[OuterLoop]
public void TestGetItem_ThreadSafety()
{
int i1 = 0x10;
int i2 = 0x100;
// Setup key1 and key2 so they are different values but have the same hashcode
// To produce a hashcode long XOR's the first 32bits with the last 32 bits
long l1 = (((long)i1) << 32) + i2;
long l2 = (((long)i2) << 32) + i1;
_key1 = l1;
_key2 = l2;
_hash = new Hashtable(3); // Just one item will be in the hashtable at a time
int taskCount = 3;
var readers1 = new Task[taskCount];
var readers2 = new Task[taskCount];
Stopwatch stopwatch = Stopwatch.StartNew();
for (int i = 0; i < readers1.Length; i++)
{
readers1[i] = Task.Run(new Action(ReaderFunction1));
}
for (int i = 0; i < readers2.Length; i++)
{
readers2[i] = Task.Run(new Action(ReaderFunction2));
}
Task writer = Task.Run(new Action(WriterFunction));
var spin = new SpinWait();
while (!_errorOccurred && !_timeExpired)
{
if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds)
{
_timeExpired = true;
}
spin.SpinOnce();
}
Task.WaitAll(readers1);
Task.WaitAll(readers2);
writer.Wait();
Assert.False(_errorOccurred);
}
private void ReaderFunction1()
{
while (!_timeExpired)
{
object value = _hash[_key1];
if (value != null)
{
Assert.NotEqual(value, _value2);
}
}
}
private void ReaderFunction2()
{
while (!_errorOccurred && !_timeExpired)
{
object value = _hash[_key2];
if (value != null)
{
Assert.NotEqual(value, _value1);
}
}
}
private void WriterFunction()
{
while (!_errorOccurred && !_timeExpired)
{
_hash.Add(_key1, _value1);
_hash.Remove(_key1);
_hash.Add(_key2, _value2);
_hash.Remove(_key2);
}
}
}
public class Hashtable_SynchronizedTests
{
private Hashtable _hash2;
private int _iNumberOfElements = 20;
[Fact]
[OuterLoop]
public void TestSynchronizedThreadSafety()
{
int iNumberOfWorkers = 3;
// Synchronized returns a hashtable that is thread safe
// We will try to test this by getting a number of threads to write some items
// to a synchronized IList
var hash1 = new Hashtable();
_hash2 = Hashtable.Synchronized(hash1);
var workers = new Task[iNumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
var name = "Thread worker " + i;
var task = new Action(() => AddElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
// Check time
Assert.Equal(_hash2.Count, _iNumberOfElements * iNumberOfWorkers);
for (int i = 0; i < iNumberOfWorkers; i++)
{
for (int j = 0; j < _iNumberOfElements; j++)
{
string strValue = "Thread worker " + i + "_" + j;
Assert.True(_hash2.Contains(strValue));
}
}
// We cannot can make an assumption on the order of these items but
// now we are going to remove all of these
workers = new Task[iNumberOfWorkers];
for (int i = 0; i < workers.Length; i++)
{
string name = "Thread worker " + i;
var task = new Action(() => RemoveElements(name));
workers[i] = Task.Run(task);
}
Task.WaitAll(workers);
Assert.Equal(_hash2.Count, 0);
}
private void AddElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Add(strName + "_" + i, "string_" + i);
}
}
private void RemoveElements(string strName)
{
for (int i = 0; i < _iNumberOfElements; i++)
{
_hash2.Remove(strName + "_" + i);
}
}
}
public class Hashtable_SyncRootTests
{
private Hashtable _hashDaughter;
private Hashtable _hashGrandDaughter;
private int _iNumberOfElements = 100;
[Fact]
public void TestSyncRoot()
{
// Different hashtables have different SyncRoots
var hash1 = new Hashtable();
var hash2 = new Hashtable();
Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot);
Assert.Equal(hash1.SyncRoot.GetType(), typeof(object));
// Cloned hashtables have different SyncRoots
hash1 = new Hashtable();
hash2 = Hashtable.Synchronized(hash1);
Hashtable hash3 = (Hashtable)hash2.Clone();
Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot);
Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot);
// Testing SyncRoot is not as simple as its implementation looks like. This is the working
// scenrio we have in mind.
// 1) Create your Down to earth mother Hashtable
// 2) Get a synchronized wrapper from it
// 3) Get a Synchronized wrapper from 2)
// 4) Get a synchronized wrapper of the mother from 1)
// 5) all of these should SyncRoot to the mother earth
var hashMother = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
hashMother.Add("Key_" + i, "Value_" + i);
}
Hashtable hashSon = Hashtable.Synchronized(hashMother);
_hashGrandDaughter = Hashtable.Synchronized(hashSon);
_hashDaughter = Hashtable.Synchronized(hashMother);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot);
Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot);
// We are going to rumble with the Hashtables with some threads
int iNumberOfWorkers = 30;
var workers = new Task[iNumberOfWorkers];
var ts2 = new Action(RemoveElements);
for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2)
{
var name = "Thread_worker_" + iThreads;
var ts1 = new Action(() => AddMoreElements(name));
workers[iThreads] = Task.Run(ts1);
workers[iThreads + 1] = Task.Run(ts2);
}
Task.WaitAll(workers);
// Check:
// Either there should be some elements (the new ones we added and/or the original ones) or none
var hshPossibleValues = new Hashtable();
for (int i = 0; i < _iNumberOfElements; i++)
{
hshPossibleValues.Add("Key_" + i, "Value_" + i);
}
for (int i = 0; i < iNumberOfWorkers; i++)
{
hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i);
}
IDictionaryEnumerator idic = hashMother.GetEnumerator();
while (idic.MoveNext())
{
Assert.True(hshPossibleValues.ContainsKey(idic.Key));
Assert.True(hshPossibleValues.ContainsValue(idic.Value));
}
}
private void AddMoreElements(string threadName)
{
_hashGrandDaughter.Add("Key_" + threadName, threadName);
}
private void RemoveElements()
{
_hashDaughter.Clear();
}
}
}
| |
/* * *******************************************************************************************
* This file is part of the Oracle Service Cloud Accelerator Reference Integration set published
* by Oracle Service Cloud under the Universal Permissive License (UPL), Version 1.0
* included in the original distribution.
* Copyright (c) 2014, 2015, 2016, Oracle and/or its affiliates. All rights reserved.
***********************************************************************************************
* Accelerator Package: OSvC + OFSC Reference Integration
* link: http://www-content.oracle.com/technetwork/indexes/samplecode/accelerator-osvc-2525361.html
* OSvC release: 15.2 (Feb 2015)
* OFSC release: 15.2 (Feb 2015)
* reference: 150622-000130
* date: Thu Sep 3 23:14:02 PDT 2015
* revision: rnw-15-11-fixes-release-03
* SHA1: $Id: 4397aa47f140b7444f3dd0d22e5e32a2db193939 $
* *********************************************************************************************
* File: RightNowConnectService.cs
* ****************************************************************************************** */
using System;
using System.Configuration;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Windows.Forms;
using Oracle.RightNow.Toa.Client.Common;
using Oracle.RightNow.Toa.Client.RightNowProxyService;
using Oracle.RightNow.Toa.Client.Services;
using RightNow.AddIns.AddInViews;
using System.Collections.Generic;
using Oracle.RightNow.Toa.Client.Model;
using Oracle.RightNow.Toa.Client.Logs;
using System.Text;
namespace Oracle.RightNow.Toa.Client.Rightnow
{
public class RightNowConnectService : IRightNowConnectService
{
private static RightNowConnectService _rightnowConnectService;
private static object _sync = new object();
private static RightNowSyncPortClient _rightNowClient;
private RightNowConnectService()
{
}
public static IRightNowConnectService GetService()
{
if (_rightnowConnectService != null)
{
return _rightnowConnectService;
}
try
{
lock (_sync)
{
if (_rightnowConnectService == null)
{
// Initialize client with current interface soap url
string url = ToaAutoClientAddIn.GlobalContext.GetInterfaceServiceUrl(ConnectServiceType.Soap);
EndpointAddress endpoint = new EndpointAddress(url);
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential);
binding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;
// Optional depending upon use cases
binding.MaxReceivedMessageSize = 1024 * 1024;
binding.MaxBufferSize = 1024 * 1024;
binding.MessageEncoding = WSMessageEncoding.Mtom;
_rightNowClient = new RightNowSyncPortClient(binding, endpoint);
// Initialize credentials for rightnow client
/*var rightNowConnectUser = ConfigurationManager.AppSettings["rightnow_user"];
var rightNowConnectPassword = ConfigurationManager.AppSettings["rightnow_password"];
_rightNowClient.ClientCredentials.UserName.UserName = rightNowConnectUser;
_rightNowClient.ClientCredentials.UserName.Password = rightNowConnectPassword;*/
BindingElementCollection elements = _rightNowClient.Endpoint.Binding.CreateBindingElements();
elements.Find<SecurityBindingElement>().IncludeTimestamp = false;
_rightNowClient.Endpoint.Binding = new CustomBinding(elements);
_rightnowConnectService = new RightNowConnectService();
}
}
}
catch (Exception e)
{
_rightnowConnectService = null;
MessageBox.Show(ToaExceptionMessages.RightNowConnectServiceNotInitialized,"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return _rightnowConnectService;
}
public string GetRightNowEndPointURIHost()
{
string endpointurihost = null;
if (_rightNowClient.Endpoint != null && _rightNowClient.Endpoint.Address != null && _rightNowClient.Endpoint.Address.Uri != null)
{
endpointurihost = _rightNowClient.Endpoint.Address.Uri.Host;
}
return endpointurihost;
}
/// <summary>
/// Get config verb value
/// </summary>
/// <param name="configVerbName"></param>
/// <returns></returns>
public string GetRightNowConfigVerbValue(string configVerbName)
{
Debug("RightNowConnectService - GetRightNowConfigVerbValue() - Enter");
string configVerbValue = String.Empty;
try
{
//Prepare session
ToaAutoClientAddIn.GlobalContext.PrepareConnectSession(_rightNowClient.ChannelFactory);
// Set up query and set request
ClientInfoHeader cih = new ClientInfoHeader();
cih.AppID = OracleRightNowToaAddInNames.OracleRightNowToaClient;
byte[] outByte = new byte[1000];
string query = RightNowQueries.GetConfigVerbQuery + "'" + configVerbName + "'";
Notice("Sending query to fetch " + configVerbName + " Config verb value");
CSVTableSet tableSet = _rightNowClient.QueryCSV(cih, query, 100, ",", false, false, out outByte);
CSVTable[] csvTables = tableSet.CSVTables;
CSVTable table = csvTables[0];
string[] rowData = table.Rows;
// Check whether configuration is set
if (rowData.Length == 0)
{
return String.Empty;
}
// Get configuration value
Notice("Returning Config verb '" + configVerbName + "' value: " + rowData[0]);
configVerbValue = rowData[0];
}
catch (Exception e)
{
Debug("RightNowConnectService - GetRightNowConfigVerbValue() - Error while fetching config verb" + e.Message);
Error("RightNowConnectService - GetRightNowConfigVerbValue() - Error while fetching config verb", e.StackTrace);
MessageBox.Show("RightNowConnectService - Error while fetching config verb", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
Debug("RightNowConnectService - GetRightNowConfigVerbValue() - Exit");
return configVerbValue;
}
/// <summary>
/// Returns the object as per query
/// Ex Query : SELECT Contact FROM Contact WHERE Contact.ID = 21 LIMIT 1
/// </summary>
/// <param name="ApplicationID"></param>
/// <param name="Query"></param>
/// <param name="RNObjects"></param>
//public object GetRNObject(string ApplicationID, string Query, RNObject[] RNObjects)
//{
// ToaAutoClientAddIn.GlobalContext.PrepareConnectSession(_rightNowClient.ChannelFactory);
//
// ClientInfoHeader hdr = new ClientInfoHeader() { AppID = ApplicationID };
//
// if (_rightNowClient != null)
// {
// QueryResultData[] data = _rightNowClient.QueryObjects(hdr, Query, RNObjects, 10);
// RNObject[] rn_objects = data[0].RNObjectsResult;
// return rn_objects[0];
// }
// return null;
//}
/// <summary>
/// Return individual fields as per query
/// </summary>
/// <param name="ApplicationID"></param>
/// <param name="Query"></param>
/// <returns> array of string delimited by '|'</returns>
private string[] GetRNData(string ApplicationID, string Query)
{
string[] rn_data = null;
ToaAutoClientAddIn.GlobalContext.PrepareConnectSession(_rightNowClient.ChannelFactory);
ClientInfoHeader hdr = new ClientInfoHeader() { AppID = ApplicationID };
byte[] output = null;
CSVTableSet data = null;
try
{
data = _rightNowClient.QueryCSV(hdr, Query, 50, "|", false, false, out output);
string data_row = String.Empty;
if (data != null && data.CSVTables.Length > 0 && data.CSVTables[0].Rows.Length > 0)
{
return data.CSVTables[0].Rows;
}
}
catch (Exception ex)
{
throw ex;
}
return rn_data;
}
private void Notice(string logMessage, string logNote = null)
{
if(RightNowConfigService.IsConfigured())
{
var log = ToaLogService.GetLog();
log.Notice(logMessage, logNote);
}
}
private void Error(string logMessage, string logNote = null)
{
if (RightNowConfigService.IsConfigured())
{
var log = ToaLogService.GetLog();
log.Error(logMessage, logNote);
}
}
private void Debug(string logMessage, string logNote = null)
{
if (RightNowConfigService.IsConfigured())
{
var log = ToaLogService.GetLog();
log.Debug(logMessage, logNote);
}
}
/**
* Commeting out the code to be reused if customer decides to have dynamic field mapping.
* This part of code fetches the data fro the mapping table.
*
private void InitializeMappingFields(string ApplicationID)
{
string query = "SELECT TOA.WO_Data_Mapping.WO_Field, TOA.WO_Data_Mapping.WS_Field, TOA.WO_Data_Mapping.Related_Object_Field_Lvl_1, TOA.WO_Data_Mapping.Related_Object_Lvl_1, TOA.WO_Data_Mapping.Data_Sync FROM TOA.WO_Data_Mapping where TOA.WO_Data_Mapping.Data_Sync = 1";
try
{
string[] datas = _rightnowConnectService.GetRNData(ApplicationID, query);
_workOrderFieldMappings = new Dictionary<string, WorkOrderFieldMapping>();
foreach (string data in datas)
{
string[] row = data.Split(new char[] { '|' });
WorkOrderFieldMapping woFieldMapping = new WorkOrderFieldMapping();
woFieldMapping.Wo_Field = row[0];
woFieldMapping.WS_Field = row[1];
woFieldMapping.Related_Object_Field_Lvl_1 = row[2];
woFieldMapping.Related_Object_Lvl_1 = row[3];
woFieldMapping.Data_Sync = Convert.ToInt32(row[4]);
//TODO: Currently zeroth level field are being fetched so skipping duplicate work order field, but this would
// need handling while implementing first level drill down.
if (!_workOrderFieldMappings.ContainsKey(woFieldMapping.Wo_Field))
{
_workOrderFieldMappings.Add(woFieldMapping.Wo_Field, woFieldMapping);
}
}
}
catch (Exception e)
{
throw e;
}
}*/
/*
* This is a way to fetch an menu item through the connect api.
public NamedID[] getNamedID(string fieldName)
{
ToaAutoClientAddIn.GlobalContext.PrepareConnectSession(_rightNowClient.ChannelFactory);
ClientInfoHeader hdr = new ClientInfoHeader() { AppID = OracleRightNowToaAddInNames.WorkOrderAddIn };
NamedID[] namedId = null;
if (_rightNowClient != null)
{
namedId = _rightNowClient.GetValuesForNamedID(hdr, null, fieldName);
}
return namedId;
}*/
public string GetProvinceName(int provinceId)
{
string query = String.Format("SELECT Provinces.Name from Country WHERE Provinces.ID = {0} limit 1", provinceId);
string[] resultset = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, query);
if (resultset.Length > 0)
{
return resultset[0];
}
return null;
}
public string[] GetWorkOrderTypeFromID(int workorderTypeId)
{
string query = String.Format("select WO_Type_Code, Manual_Duration, Manual_Duration_Default from TOA.Work_Order_Type where ID = {0}", workorderTypeId);
string[] workordertype = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, query)[0].Split(new char[] { '|' });
return workordertype;
}
public string[] GetReminder_TimeFromID(int reminderTimeId)
{
string query = String.Format("select Name from TOA.Reminder_Time where ID = {0}", reminderTimeId);
string[] remindertime = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, query);
return remindertime;
}
public string[] GetResolutionDueFromID(int incidentId)
{
string query = String.Format(RightNowQueries.GetMilestonesQuery,incidentId);
string[] milestones = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, query);
return milestones;
}
public string[] GetIncidentPrimaryAssetFromID(int incidentId)
{
string asset_query = String.Format("select Asset from Incident where ID = {0}", incidentId);
string[] asset = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, asset_query);
return asset;
}
public string[] GetAssetDetailsFromAssetID(string assetId)
{
string asset_details_query = String.Format("select Product.ID, SerialNumber from Asset where ID = {0}", assetId);
string[] assetdetails = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, asset_details_query);
if (null != assetdetails && null != assetdetails[0])
{
return assetdetails[0].Split('|');
}
return assetdetails;
}
public string[] GetRequiredInventoryDetailsFromWorkOrderType(int workOrderTypeId)
{
string workOrder_type_inventory_query = String.Format("select Product.ID, Quantity, Model from TOA.WO_Type_Inventory where Work_Order_Type = {0}", workOrderTypeId);
string[] workOrder_type_inventories = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, workOrder_type_inventory_query);
return workOrder_type_inventories;
}
public string[] GetProductDetailsFromProductID(string productID)
{
string salesProductQuery = String.Format("select PartNumber from SalesProduct where ID = {0}", productID);
string[] salesProductDetails = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, salesProductQuery);
return salesProductDetails;
}
//public string[] GetRequiredInventoryTypeCodeFromRequiredInventoryID(string requiredInventoryId)
//{
// string workOrder_inventory_query = String.Format("select Inventory_Code, Model_Property from TOA.Work_Order_Inventory where ID = {0}", requiredInventoryId);
// string[] workOrderInventoryCode = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, workOrder_inventory_query);
// if (null != workOrderInventoryCode && null != workOrderInventoryCode[0])
// {
// return workOrderInventoryCode[0].Split('|');
// }
// return workOrderInventoryCode;
//}
//public QueryResultData[] GetProductCatalogDetailsFromId(int productId)
//{
// string workOrder_inventory_query = String.Format("select SalesProduct from SalesProduct where ID = {0}", productId);
// ClientInfoHeader hdr = new ClientInfoHeader() { AppID = "TOAClient" };
// SalesProduct salesProduct = new SalesProduct();
// RNObject[] salesProductTemplates = new RNObject[] { salesProduct };
// QueryResultData[] querySalesProductsObj = null;
// try
// {
// querySalesProductsObj = _rightNowClient.QueryObjects(hdr, workOrder_inventory_query, salesProductTemplates, 1);
// return querySalesProductsObj;
// }catch(Exception ex)
// {
// throw ex;
// }
// //string[] workOrderInventoryCode = GetRNData(OracleRightNowToaAddInNames.WorkOrderAddIn, workOrder_inventory_query);
//}
public RightNowSyncPortClient GetRightNowClient()
{
return _rightNowClient;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Mime;
namespace SuperGlue.Web.Output
{
public class MimeType
{
public static readonly string HttpFormMimetype = "application/x-www-form-urlencoded";
public static readonly string MultipartMimetype = "multipart/form-data";
private static readonly Cache<string, MimeType> MimeTypes = new Cache<string, MimeType>(key => new MimeType(key));
public static readonly MimeType Html = New(MediaTypeNames.Text.Html, ".htm", ".html");
public static readonly MimeType Json = New("application/json");
public static readonly MimeType Text = New(MediaTypeNames.Text.Plain, ".txt");
public static readonly MimeType Javascript = New("application/javascript", ".js", ".coffee");
public static readonly MimeType Css = New("text/css", ".css");
public static readonly MimeType Gif = New("image/gif", ".gif");
public static readonly MimeType Png = New("image/png", ".png");
public static readonly MimeType Jpg = New("image/jpeg", ".jpg", ".jpeg");
public static readonly MimeType Bmp = New("image/bmp", ".bmp", ".bm");
public static readonly MimeType Unknown = New("dunno");
public static readonly MimeType EventStream = New("text/event-stream");
public static readonly MimeType Xml = New("application/xml", ".xml");
public static readonly MimeType Any = New("*/*");
public static readonly MimeType TrueTypeFont = New("application/octet-stream", ".ttf");
public static readonly MimeType WebOpenFont = New("application/font-woff", ".woff");
public static readonly MimeType WebOpenFont2 = New("application/font-woff2", ".woff2");
public static readonly MimeType EmbeddedOpenType = New("application/vnd.ms-fontobject", ".eot");
public static readonly MimeType Svg = New("image/svg+xml", ".svg");
private readonly IList<string> _extensions = new List<string>();
private MimeType(string mimeType)
{
Value = mimeType;
}
public string Value { get; }
public static MimeType New(string mimeTypeValue, params string[] extensions)
{
var mimeType = new MimeType(mimeTypeValue);
foreach (var extension in extensions)
mimeType.AddExtension(extension);
MimeTypes[mimeTypeValue] = mimeType;
return mimeType;
}
public void AddExtension(string extension)
{
if (!_extensions.Contains(extension))
_extensions.Add(extension);
}
public override string ToString()
{
return Value;
}
public static IEnumerable<MimeType> All()
{
return MimeTypes.GetAll();
}
public static MimeType MimeTypeByValue(string mimeTypeValue)
{
return MimeTypes[mimeTypeValue];
}
public bool HasExtension(string extension)
{
return _extensions.Contains(extension);
}
public string DefaultExtension()
{
return _extensions.FirstOrDefault();
}
public static MimeType MimeTypeByFileName(string name)
{
var extension = Path.GetExtension(name);
return MappingFromExtension[extension];
}
public IEnumerable<string> Extensions => _extensions;
private static readonly Cache<string, MimeType> MappingFromExtension;
static MimeType()
{
foreach (var pair in FileExtensions)
MimeTypes[pair.Value].AddExtension(pair.Key);
MappingFromExtension = new Cache<string, MimeType>(extension =>
{
return MimeTypes.GetAll().FirstOrDefault(x => x.HasExtension(extension));
});
}
private static readonly Dictionary<string, string> FileExtensions = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{".323", "text/h323"},
{".3g2", "video/3gpp2"},
{".3gp2", "video/3gpp2"},
{".3gp", "video/3gpp"},
{".3gpp", "video/3gpp"},
{".aac", "audio/aac"},
{".aaf", "application/octet-stream"},
{".aca", "application/octet-stream"},
{".accdb", "application/msaccess"},
{".accde", "application/msaccess"},
{".accdt", "application/msaccess"},
{".acx", "application/internet-property-stream"},
{".adt", "audio/vnd.dlna.adts"},
{".adts", "audio/vnd.dlna.adts"},
{".afm", "application/octet-stream"},
{".ai", "application/postscript"},
{".aif", "audio/x-aiff"},
{".aifc", "audio/aiff"},
{".aiff", "audio/aiff"},
{".application", "application/x-ms-application"},
{".art", "image/x-jg"},
{".asd", "application/octet-stream"},
{".asf", "video/x-ms-asf"},
{".asi", "application/octet-stream"},
{".asm", "text/plain"},
{".asr", "video/x-ms-asf"},
{".asx", "video/x-ms-asf"},
{".atom", "application/atom+xml"},
{".au", "audio/basic"},
{".avi", "video/x-msvideo"},
{".axs", "application/olescript"},
{".bas", "text/plain"},
{".bcpio", "application/x-bcpio"},
{".bin", "application/octet-stream"},
{".bmp", "image/bmp"},
{".c", "text/plain"},
{".cab", "application/vnd.ms-cab-compressed"},
{".calx", "application/vnd.ms-office.calx"},
{".cat", "application/vnd.ms-pki.seccat"},
{".cdf", "application/x-cdf"},
{".chm", "application/octet-stream"},
{".class", "application/x-java-applet"},
{".clp", "application/x-msclip"},
{".cmx", "image/x-cmx"},
{".cnf", "text/plain"},
{".cod", "image/cis-cod"},
{".cpio", "application/x-cpio"},
{".cpp", "text/plain"},
{".crd", "application/x-mscardfile"},
{".crl", "application/pkix-crl"},
{".crt", "application/x-x509-ca-cert"},
{".csh", "application/x-csh"},
{".css", "text/css"},
{".csv", "application/octet-stream"},
{".cur", "application/octet-stream"},
{".dcr", "application/x-director"},
{".deploy", "application/octet-stream"},
{".der", "application/x-x509-ca-cert"},
{".dib", "image/bmp"},
{".dir", "application/x-director"},
{".disco", "text/xml"},
{".dlm", "text/dlm"},
{".doc", "application/msword"},
{".docm", "application/vnd.ms-word.document.macroEnabled.12"},
{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{".dot", "application/msword"},
{".dotm", "application/vnd.ms-word.template.macroEnabled.12"},
{".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{".dsp", "application/octet-stream"},
{".dtd", "text/xml"},
{".dvi", "application/x-dvi"},
{".dvr-ms", "video/x-ms-dvr"},
{".dwf", "drawing/x-dwf"},
{".dwp", "application/octet-stream"},
{".dxr", "application/x-director"},
{".eml", "message/rfc822"},
{".emz", "application/octet-stream"},
{".eot", "application/vnd.ms-fontobject"},
{".eps", "application/postscript"},
{".etx", "text/x-setext"},
{".evy", "application/envoy"},
{".fdf", "application/vnd.fdf"},
{".fif", "application/fractals"},
{".fla", "application/octet-stream"},
{".flr", "x-world/x-vrml"},
{".flv", "video/x-flv"},
{".gif", "image/gif"},
{".gtar", "application/x-gtar"},
{".gz", "application/x-gzip"},
{".h", "text/plain"},
{".hdf", "application/x-hdf"},
{".hdml", "text/x-hdml"},
{".hhc", "application/x-oleobject"},
{".hhk", "application/octet-stream"},
{".hhp", "application/octet-stream"},
{".hlp", "application/winhlp"},
{".hqx", "application/mac-binhex40"},
{".hta", "application/hta"},
{".htc", "text/x-component"},
{".htm", "text/html"},
{".html", "text/html"},
{".htt", "text/webviewhtml"},
{".hxt", "text/html"},
{".ical", "text/calendar"},
{".icalendar", "text/calendar"},
{".ico", "image/x-icon"},
{".ics", "text/calendar"},
{".ief", "image/ief"},
{".ifb", "text/calendar"},
{".iii", "application/x-iphone"},
{".inf", "application/octet-stream"},
{".ins", "application/x-internet-signup"},
{".isp", "application/x-internet-signup"},
{".IVF", "video/x-ivf"},
{".jar", "application/java-archive"},
{".java", "application/octet-stream"},
{".jck", "application/liquidmotion"},
{".jcz", "application/liquidmotion"},
{".jfif", "image/pjpeg"},
{".jpb", "application/octet-stream"},
{".jpe", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".jpg", "image/jpeg"},
{".js", "application/javascript"},
{".jsx", "text/jsx"},
{".latex", "application/x-latex"},
{".lit", "application/x-ms-reader"},
{".lpk", "application/octet-stream"},
{".lsf", "video/x-la-asf"},
{".lsx", "video/x-la-asf"},
{".lzh", "application/octet-stream"},
{".m13", "application/x-msmediaview"},
{".m14", "application/x-msmediaview"},
{".m1v", "video/mpeg"},
{".m2ts", "video/vnd.dlna.mpeg-tts"},
{".m3u", "audio/x-mpegurl"},
{".m4a", "audio/mp4"},
{".m4v", "video/mp4"},
{".man", "application/x-troff-man"},
{".manifest", "application/x-ms-manifest"},
{".map", "text/plain"},
{".mdb", "application/x-msaccess"},
{".mdp", "application/octet-stream"},
{".me", "application/x-troff-me"},
{".mht", "message/rfc822"},
{".mhtml", "message/rfc822"},
{".mid", "audio/mid"},
{".midi", "audio/mid"},
{".mix", "application/octet-stream"},
{".mmf", "application/x-smaf"},
{".mno", "text/xml"},
{".mny", "application/x-msmoney"},
{".mov", "video/quicktime"},
{".movie", "video/x-sgi-movie"},
{".mp2", "video/mpeg"},
{".mp3", "audio/mpeg"},
{".mp4", "video/mp4"},
{".mp4v", "video/mp4"},
{".mpa", "video/mpeg"},
{".mpe", "video/mpeg"},
{".mpeg", "video/mpeg"},
{".mpg", "video/mpeg"},
{".mpp", "application/vnd.ms-project"},
{".mpv2", "video/mpeg"},
{".ms", "application/x-troff-ms"},
{".msi", "application/octet-stream"},
{".mso", "application/octet-stream"},
{".mvb", "application/x-msmediaview"},
{".mvc", "application/x-miva-compiled"},
{".nc", "application/x-netcdf"},
{".nsc", "video/x-ms-asf"},
{".nws", "message/rfc822"},
{".ocx", "application/octet-stream"},
{".oda", "application/oda"},
{".odc", "text/x-ms-odc"},
{".ods", "application/oleobject"},
{".oga", "audio/ogg"},
{".ogg", "video/ogg"},
{".ogv", "video/ogg"},
{".ogx", "application/ogg"},
{".one", "application/onenote"},
{".onea", "application/onenote"},
{".onetoc", "application/onenote"},
{".onetoc2", "application/onenote"},
{".onetmp", "application/onenote"},
{".onepkg", "application/onenote"},
{".osdx", "application/opensearchdescription+xml"},
{".otf", "font/otf"},
{".p10", "application/pkcs10"},
{".p12", "application/x-pkcs12"},
{".p7b", "application/x-pkcs7-certificates"},
{".p7c", "application/pkcs7-mime"},
{".p7m", "application/pkcs7-mime"},
{".p7r", "application/x-pkcs7-certreqresp"},
{".p7s", "application/pkcs7-signature"},
{".pbm", "image/x-portable-bitmap"},
{".pcx", "application/octet-stream"},
{".pcz", "application/octet-stream"},
{".pdf", "application/pdf"},
{".pfb", "application/octet-stream"},
{".pfm", "application/octet-stream"},
{".pfx", "application/x-pkcs12"},
{".pgm", "image/x-portable-graymap"},
{".pko", "application/vnd.ms-pki.pko"},
{".pma", "application/x-perfmon"},
{".pmc", "application/x-perfmon"},
{".pml", "application/x-perfmon"},
{".pmr", "application/x-perfmon"},
{".pmw", "application/x-perfmon"},
{".png", "image/png"},
{".pnm", "image/x-portable-anymap"},
{".pnz", "image/png"},
{".pot", "application/vnd.ms-powerpoint"},
{".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12"},
{".potx", "application/vnd.openxmlformats-officedocument.presentationml.template"},
{".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{".ppm", "image/x-portable-pixmap"},
{".pps", "application/vnd.ms-powerpoint"},
{".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{".ppt", "application/vnd.ms-powerpoint"},
{".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{".prf", "application/pics-rules"},
{".prm", "application/octet-stream"},
{".prx", "application/octet-stream"},
{".ps", "application/postscript"},
{".psd", "application/octet-stream"},
{".psm", "application/octet-stream"},
{".psp", "application/octet-stream"},
{".pub", "application/x-mspublisher"},
{".qt", "video/quicktime"},
{".qtl", "application/x-quicktimeplayer"},
{".qxd", "application/octet-stream"},
{".ra", "audio/x-pn-realaudio"},
{".ram", "audio/x-pn-realaudio"},
{".rar", "application/octet-stream"},
{".ras", "image/x-cmu-raster"},
{".rf", "image/vnd.rn-realflash"},
{".rgb", "image/x-rgb"},
{".rm", "application/vnd.rn-realmedia"},
{".rmi", "audio/mid"},
{".roff", "application/x-troff"},
{".rpm", "audio/x-pn-realaudio-plugin"},
{".rtf", "application/rtf"},
{".rtx", "text/richtext"},
{".scd", "application/x-msschedule"},
{".sct", "text/scriptlet"},
{".sea", "application/octet-stream"},
{".setpay", "application/set-payment-initiation"},
{".setreg", "application/set-registration-initiation"},
{".sgml", "text/sgml"},
{".sh", "application/x-sh"},
{".shar", "application/x-shar"},
{".sit", "application/x-stuffit"},
{".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12"},
{".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide"},
{".smd", "audio/x-smd"},
{".smi", "application/octet-stream"},
{".smx", "audio/x-smd"},
{".smz", "audio/x-smd"},
{".snd", "audio/basic"},
{".snp", "application/octet-stream"},
{".spc", "application/x-pkcs7-certificates"},
{".spl", "application/futuresplash"},
{".spx", "audio/ogg"},
{".src", "application/x-wais-source"},
{".ssm", "application/streamingmedia"},
{".sst", "application/vnd.ms-pki.certstore"},
{".stl", "application/vnd.ms-pki.stl"},
{".sv4cpio", "application/x-sv4cpio"},
{".sv4crc", "application/x-sv4crc"},
{".svg", "image/svg+xml"},
{".svgz", "image/svg+xml"},
{".swf", "application/x-shockwave-flash"},
{".t", "application/x-troff"},
{".tar", "application/x-tar"},
{".tcl", "application/x-tcl"},
{".tex", "application/x-tex"},
{".texi", "application/x-texinfo"},
{".texinfo", "application/x-texinfo"},
{".tgz", "application/x-compressed"},
{".thmx", "application/vnd.ms-officetheme"},
{".thn", "application/octet-stream"},
{".tif", "image/tiff"},
{".tiff", "image/tiff"},
{".toc", "application/octet-stream"},
{".tr", "application/x-troff"},
{".trm", "application/x-msterminal"},
{".ts", "video/vnd.dlna.mpeg-tts"},
{".tsv", "text/tab-separated-values"},
{".ttf", "application/octet-stream"},
{".tts", "video/vnd.dlna.mpeg-tts"},
{".txt", "text/plain"},
{".u32", "application/octet-stream"},
{".uls", "text/iuls"},
{".ustar", "application/x-ustar"},
{".vbs", "text/vbscript"},
{".vcf", "text/x-vcard"},
{".vcs", "text/plain"},
{".vdx", "application/vnd.ms-visio.viewer"},
{".vml", "text/xml"},
{".vsd", "application/vnd.visio"},
{".vss", "application/vnd.visio"},
{".vst", "application/vnd.visio"},
{".vsto", "application/x-ms-vsto"},
{".vsw", "application/vnd.visio"},
{".vsx", "application/vnd.visio"},
{".vtx", "application/vnd.visio"},
{".wav", "audio/wav"},
{".wax", "audio/x-ms-wax"},
{".wbmp", "image/vnd.wap.wbmp"},
{".wcm", "application/vnd.ms-works"},
{".wdb", "application/vnd.ms-works"},
{".webm", "video/webm"},
{".wks", "application/vnd.ms-works"},
{".wm", "video/x-ms-wm"},
{".wma", "audio/x-ms-wma"},
{".wmd", "application/x-ms-wmd"},
{".wmf", "application/x-msmetafile"},
{".wml", "text/vnd.wap.wml"},
{".wmlc", "application/vnd.wap.wmlc"},
{".wmls", "text/vnd.wap.wmlscript"},
{".wmlsc", "application/vnd.wap.wmlscriptc"},
{".wmp", "video/x-ms-wmp"},
{".wmv", "video/x-ms-wmv"},
{".wmx", "video/x-ms-wmx"},
{".wmz", "application/x-ms-wmz"},
{".woff", "application/font-woff"},
{".woff2", "application/font-woff2"},
{".wps", "application/vnd.ms-works"},
{".wri", "application/x-mswrite"},
{".wrl", "x-world/x-vrml"},
{".wrz", "x-world/x-vrml"},
{".wsdl", "text/xml"},
{".wtv", "video/x-ms-wtv"},
{".wvx", "video/x-ms-wvx"},
{".x", "application/directx"},
{".xaf", "x-world/x-vrml"},
{".xaml", "application/xaml+xml"},
{".xap", "application/x-silverlight-app"},
{".xbap", "application/x-ms-xbap"},
{".xbm", "image/x-xbitmap"},
{".xdr", "text/plain"},
{".xht", "application/xhtml+xml"},
{".xhtml", "application/xhtml+xml"},
{".xla", "application/vnd.ms-excel"},
{".xlam", "application/vnd.ms-excel.addin.macroEnabled.12"},
{".xlc", "application/vnd.ms-excel"},
{".xlm", "application/vnd.ms-excel"},
{".xls", "application/vnd.ms-excel"},
{".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".xlt", "application/vnd.ms-excel"},
{".xltm", "application/vnd.ms-excel.template.macroEnabled.12"},
{".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{".xlw", "application/vnd.ms-excel"},
{".xml", "text/xml"},
{".xof", "x-world/x-vrml"},
{".xpm", "image/x-xpixmap"},
{".xps", "application/vnd.ms-xpsdocument"},
{".xsd", "text/xml"},
{".xsf", "text/xml"},
{".xsl", "text/xml"},
{".xslt", "text/xml"},
{".xsn", "application/octet-stream"},
{".xtp", "application/octet-stream"},
{".xwd", "image/x-xwindowdump"},
{".z", "application/x-compress"},
{".zip", "application/x-zip-compressed"},
};
}
}
| |
//
// Copyright (c) 2008-2019 the Urho3D project.
// Copyright (c) 2017-2020 the rbfx project.
//
// 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.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Urho3DNet
{
/// Two-dimensional vector.
[StructLayout(LayoutKind.Sequential)]
public struct Vector2 : IEquatable<Vector2>
{
/// Construct from an IntVector2.
public Vector2(in IntVector2 vector)
{
X = vector.X;
Y = vector.Y;
}
/// Construct from coordinates.
public Vector2(float x, float y)
{
X = x;
Y = y;
}
/// Construct from a float array.
public Vector2(IReadOnlyList<float> data)
{
X = data[0];
Y = data[1];
}
/// Test for equality with another vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(in Vector2 lhs, in Vector2 rhs)
{
return lhs.X == rhs.X && lhs.Y == rhs.Y;
}
/// Test for inequality with another vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(in Vector2 lhs, in Vector2 rhs)
{
return lhs.X != rhs.X || lhs.Y != rhs.Y;
}
/// Add a vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator +(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(lhs.X + rhs.X, lhs.Y + rhs.Y);
}
/// Return negation.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(in Vector2 v)
{
return new Vector2(-v.X, -v.Y);
}
/// Subtract a vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator -(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(lhs.X - rhs.X, lhs.Y - rhs.Y);
}
/// Multiply with a scalar.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(in Vector2 lhs, float rhs)
{
return new Vector2(lhs.X * rhs, lhs.Y * rhs);
}
/// Multiply with a vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(lhs.X * rhs.X, lhs.Y * rhs.Y);
}
/// Divide by a scalar.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(in Vector2 lhs, float rhs)
{
return new Vector2(lhs.X / rhs, lhs.Y / rhs);
}
/// Divide by a vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator /(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(lhs.X / rhs.X, lhs.Y / rhs.Y);
}
/// Multiply Vector2 with a scalar
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 operator *(float lhs, in Vector2 rhs)
{
return rhs * lhs;
}
/// Return value by index.
public float this[int index]
{
get
{
if (index < 0 || index > 1)
throw new IndexOutOfRangeException();
unsafe
{
fixed (float* p = &X)
{
return p[index];
}
}
}
set
{
if (index < 0 || index > 1)
throw new IndexOutOfRangeException();
unsafe
{
fixed (float* p = &X)
{
p[index] = value;
}
}
}
}
/// Normalize to unit length.
public void Normalize()
{
float lenSquared = LengthSquared;
if (!MathDefs.Equals(lenSquared, 1.0f) && lenSquared > 0.0f)
{
float invLen = 1.0f / (float) Math.Sqrt(lenSquared);
X *= invLen;
Y *= invLen;
}
}
/// Return length.
public float Length => (float) Math.Sqrt(X * X + Y * Y);
/// Return squared length.
public float LengthSquared => X * X + Y * Y;
/// Calculate dot product.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float DotProduct(in Vector2 rhs)
{
return X * rhs.X + Y * rhs.Y;
}
/// Calculate absolute dot product.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float AbsDotProduct(in Vector2 rhs)
{
return Math.Abs(X * rhs.X) + Math.Abs(Y * rhs.Y);
}
/// Project vector onto axis.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ProjectOntoAxis(in Vector2 axis)
{
return DotProduct(axis.Normalized);
}
/// Returns the angle between this vector and another vector in degrees.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float Angle(in Vector2 rhs)
{
return (float) Math.Acos(DotProduct(rhs) / (Length * rhs.Length));
}
/// Return absolute vector.
public Vector2 Abs => new Vector2(Math.Abs(X), Math.Abs(Y));
/// Linear interpolation with another vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Vector2 Lerp(in Vector2 rhs, float t)
{
return this * (1.0f - t) + rhs * t;
}
/// Test for equality with another vector with epsilon.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(Vector2 rhs)
{
return MathDefs.Equals(X, rhs.X) && MathDefs.Equals(Y, rhs.Y);
}
/// Return whether is NaN.
public bool IsNaN => float.IsNaN(X) || float.IsNaN(Y);
/// Return normalized to unit length.
public Vector2 Normalized
{
get
{
float lenSquared = LengthSquared;
if (!MathDefs.Equals(lenSquared, 1.0f) && lenSquared > 0.0f)
{
float invLen = 1.0f / (float) Math.Sqrt(lenSquared);
return this * invLen;
}
else
return this;
}
}
/// Return float data.
public float[] Data => new float[] {X, Y};
/// Return as string.
public override string ToString()
{
return $"{X} {Y}";
}
/// Return hash value for HashSet & HashMap.
public override int GetHashCode()
{
unchecked
{
return (X.GetHashCode() * 31) ^ Y.GetHashCode();
}
}
/// Per-component linear interpolation between two 2-vectors.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Lerp(in Vector2 lhs, in Vector2 rhs, in Vector2 t)
{
return lhs + (rhs - lhs) * t;
}
/// Per-component min of two 2-vectors.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Min(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(Math.Min(lhs.X, rhs.X), Math.Min(lhs.Y, rhs.Y));
}
/// Per-component max of two 2-vectors.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Max(in Vector2 lhs, in Vector2 rhs)
{
return new Vector2(Math.Max(lhs.X, rhs.X), Math.Max(lhs.Y, rhs.Y));
}
/// Per-component floor of 2-vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Floor(in Vector2 vec)
{
return new Vector2((float) Math.Floor(vec.X), (float) Math.Floor(vec.Y));
}
/// Per-component round of 2-vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Round(in Vector2 vec)
{
return new Vector2((float) Math.Round(vec.X), (float) Math.Round(vec.Y));
}
/// Per-component ceil of 2-vector.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static Vector2 Ceil(in Vector2 vec)
{
return new Vector2((float) Math.Ceiling(vec.X), (float) Math.Ceiling(vec.Y));
}
/// Per-component floor of 2-vector. Returns IntVector2.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntVector2 FloorToInt(in Vector2 vec)
{
return new IntVector2((int) Math.Floor(vec.X), (int) Math.Floor(vec.Y));
}
/// Per-component round of 2-vector. Returns IntVector2.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntVector2 RoundToInt(in Vector2 vec)
{
return new IntVector2((int) Math.Round(vec.X), (int) Math.Round(vec.Y));
}
/// Per-component ceil of 2-vector. Returns IntVector2.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static IntVector2 CeilToInt(in Vector2 vec)
{
return new IntVector2((int) Math.Ceiling(vec.X), (int) Math.Ceiling(vec.Y));
}
/// Return a random value from [0, 1) from 2-vector seed.
/// http://stackoverflow.com/questions/12964279/whats-the-origin-of-this-glsl-rand-one-liner
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float StableRandom(in Vector2 seed)
{
return (float) MathDefs.Fract(
Math.Sin(MathDefs.RadiansToDegrees(seed.DotProduct(new Vector2(12.9898f, 78.233f)))) * 43758.5453f);
}
/// Return a random value from [0, 1) from scalar seed.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float StableRandom(float seed)
{
return StableRandom(new Vector2(seed, seed));
}
/// X coordinate.
public float X;
/// Y coordinate.
public float Y;
/// Zero vector.
public static readonly Vector2 ZERO;
/// (-1,0) vector.
public static readonly Vector2 LEFT = new Vector2(-1, 0);
/// (1,0) vector.
public static readonly Vector2 RIGHT = new Vector2(1, 0);
/// (0,1) vector.
public static readonly Vector2 UP = new Vector2(0, 1);
/// (0,-1) vector.
public static readonly Vector2 DOWN = new Vector2(0, -1);
/// (1,1) vector.
public static readonly Vector2 ONE = new Vector2(1, 1);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool Equals(object obj)
{
return obj is Vector2 other && Equals(other);
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.Dispatcher
{
using System.Collections.Generic;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Diagnostics;
using System.Threading;
using System.Diagnostics;
abstract class DurableInstanceContextProvider : IInstanceContextProvider
{
ContextCache contextCache;
bool isPerCall;
ServiceHostBase serviceHostBase;
protected DurableInstanceContextProvider(ServiceHostBase serviceHostBase, bool isPerCall)
{
if (serviceHostBase == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceHostBase");
}
this.serviceHostBase = serviceHostBase;
if (serviceHostBase.Description.Behaviors.Find<ServiceThrottlingBehavior>() == null)
{
serviceHostBase.ServiceThrottle.MaxConcurrentInstances = (new ServiceThrottlingBehavior()).MaxConcurrentInstances;
}
this.contextCache = new ContextCache();
this.isPerCall = isPerCall;
}
protected ContextCache Cache
{
get
{
return this.contextCache;
}
}
public virtual InstanceContext GetExistingInstanceContext(Message message, IContextChannel channel)
{
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (channel == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel");
}
Guid instanceId = GetInstanceIdFromMessage(message);
InstanceContext result = null;
if (instanceId != Guid.Empty) //Not an activation request.
{
if (contextCache.TryGetInstanceContext(instanceId, out result))
{
lock (result.ThisLock)
{
if (!string.IsNullOrEmpty(channel.SessionId) && !result.IncomingChannels.Contains(channel))
{
result.IncomingChannels.Add(channel);
}
}
return result;
}
}
return result;
}
public int GetReferenceCount(Guid instanceId)
{
return this.Cache.GetReferenceCount(instanceId);
}
public virtual void InitializeInstanceContext(InstanceContext instanceContext, Message message, IContextChannel channel)
{
if (instanceContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instanceContext");
}
if (message == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message");
}
if (channel == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("channel");
}
Guid instanceId = GetInstanceIdFromMessage(message);
DurableInstance durableInstance;
if (instanceId == Guid.Empty) //Activation Request.
{
instanceId = Guid.NewGuid();
durableInstance = this.OnCreateNewInstance(instanceId);
message.Properties[DurableMessageDispatchInspector.NewDurableInstanceIdPropertyName] = instanceId;
}
else
{
durableInstance = this.OnGetExistingInstance(instanceId);
}
Fx.Assert(durableInstance != null, "Durable instance should never be null at this point.");
durableInstance.Open();
instanceContext.Extensions.Add(durableInstance);
if (!string.IsNullOrEmpty(channel.SessionId))
{
instanceContext.IncomingChannels.Add(channel);
}
contextCache.AddInstanceContext(instanceId, instanceContext);
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR.GetString(SR.TraceCodeDICPInstanceContextCached, instanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.DICPInstanceContextCached, SR.GetString(SR.TraceCodeDICPInstanceContextCached),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
public virtual bool IsIdle(InstanceContext instanceContext)
{
bool removed = false;
if (instanceContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instanceContext");
}
DurableInstance durableInstance = instanceContext.Extensions.Find<DurableInstance>();
if (durableInstance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
new InvalidOperationException(
SR2.GetString(
SR2.RequiredInstanceContextExtensionNotFound,
typeof(DurableInstance).Name)));
}
lock (instanceContext.ThisLock)
{
if (instanceContext.IncomingChannels.Count == 0)
{
removed = contextCache.RemoveIfNotBusy(durableInstance.InstanceId, instanceContext);
}
}
if (removed && DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR.GetString(SR.TraceCodeDICPInstanceContextRemovedFromCache, durableInstance.InstanceId);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.DICPInstanceContextRemovedFromCache, SR.GetString(SR.TraceCodeDICPInstanceContextRemovedFromCache),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
return removed;
}
public virtual void NotifyIdle(InstanceContextIdleCallback callback, InstanceContext instanceContext)
{
}
//Called by MessageInspector.BeforeReply
internal void DecrementActivityCount(Guid instanceId)
{
contextCache.ReleaseReference(instanceId);
}
internal void UnbindAbortedInstance(InstanceContext instanceContext, Guid instanceId)
{
if (instanceContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instanceContext");
}
//We made our best effor to clean up the instancecontext out of our cache.
//If another request already in middle of processing the request on InstanceContext
//It will Fail with CommunicationException.
this.contextCache.Remove(instanceId, instanceContext);
}
protected virtual Guid GetInstanceIdFromMessage(Message message)
{
if (!this.isPerCall)
{
ContextMessageProperty contextProperties = null;
string instanceId = null;
if (ContextMessageProperty.TryGet(message, out contextProperties))
{
if (contextProperties.Context.TryGetValue(WellKnownContextProperties.InstanceId, out instanceId))
{
return Fx.CreateGuid(instanceId);
}
}
}
return Guid.Empty;
}
protected abstract DurableInstance OnCreateNewInstance(Guid instanceId);
protected abstract DurableInstance OnGetExistingInstance(Guid instanceId);
//This class takes self contained lock, never calls out with lock taken.
protected class ContextCache
{
Dictionary<Guid, ContextItem> contextCache;
object lockObject = new object();
public ContextCache()
{
contextCache = new Dictionary<Guid, ContextItem>();
}
public void AddInstanceContext(Guid instanceId, InstanceContext instanceContext)
{
ContextItem contextItem;
int? referenceCount = null;
lock (lockObject)
{
if (!contextCache.TryGetValue(instanceId, out contextItem))
{
//This will be the case for activation request.
contextItem = new ContextItem(instanceId);
referenceCount = contextItem.AddReference();
contextCache.Add(instanceId, contextItem);
}
}
contextItem.InstanceContext = instanceContext;
if (DiagnosticUtility.ShouldTraceInformation && referenceCount.HasValue)
{
string traceText = SR2.GetString(SR2.DurableInstanceRefCountToInstanceContext, instanceId, referenceCount.Value);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.InstanceContextBoundToDurableInstance, SR.GetString(SR.TraceCodeInstanceContextBoundToDurableInstance),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
public bool Contains(Guid instanceId, InstanceContext instanceContext)
{
ContextItem contextItem = null;
lock (this.lockObject)
{
if (contextCache.TryGetValue(instanceId, out contextItem))
{
return object.ReferenceEquals(contextItem.InstanceContext, instanceContext);
}
return false;
}
}
public int GetReferenceCount(Guid instanceId)
{
int result = 0;
lock (lockObject)
{
ContextItem contextItem;
if (contextCache.TryGetValue(instanceId, out contextItem))
{
result = contextItem.ReferenceCount;
}
}
return result;
}
public void ReleaseReference(Guid instanceId)
{
int referenceCount = -1;
ContextItem contextItem;
lock (lockObject)
{
if (contextCache.TryGetValue(instanceId, out contextItem))
{
referenceCount = contextItem.ReleaseReference();
}
else
{
Fx.Assert(false, "Cannot Release Reference of non exisiting items");
}
}
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.DurableInstanceRefCountToInstanceContext, instanceId, referenceCount);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.InstanceContextDetachedFromDurableInstance, SR.GetString(SR.TraceCodeInstanceContextDetachedFromDurableInstance),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
public bool Remove(Guid instanceId, InstanceContext instanceContext)
{
lock (this.lockObject)
{
ContextItem contextItem = null;
if (this.contextCache.TryGetValue(instanceId, out contextItem))
{
if (object.ReferenceEquals(instanceContext, contextItem.InstanceContext))
{
return this.contextCache.Remove(instanceId);
}
}
//InstanceContext is not in memory.
return false;
}
}
public bool RemoveIfNotBusy(Guid instanceId, InstanceContext instanceContext)
{
lock (lockObject)
{
ContextItem contextItem = null;
if (contextCache.TryGetValue(instanceId, out contextItem))
{
if (object.ReferenceEquals(contextItem.InstanceContext, instanceContext))
{
return (!contextItem.HasOutstandingReference)
&& (contextCache.Remove(instanceId));
}
}
//InstanceContext is not in memory.
return true;
}
}
//Helper method to call from GetExistingInstanceContext
//returns true : If InstanceContext is found in cache & guaranteed to stay in cache until ReleaseReference is called.
//returns false : If InstanceContext is not found in cache;
// reference & slot is created for the ID;
// InitializeInstanceContext to call AddInstanceContext.
public bool TryGetInstanceContext(Guid instanceId, out InstanceContext instanceContext)
{
ContextItem contextItem;
instanceContext = null;
int referenceCount = -1;
try
{
lock (lockObject)
{
if (!contextCache.TryGetValue(instanceId, out contextItem))
{
contextItem = new ContextItem(instanceId);
referenceCount = contextItem.AddReference();
contextCache.Add(instanceId, contextItem);
return false;
}
referenceCount = contextItem.AddReference();
}
}
finally
{
if (DiagnosticUtility.ShouldTraceInformation)
{
string traceText = SR2.GetString(SR2.DurableInstanceRefCountToInstanceContext, instanceId, referenceCount);
TraceUtility.TraceEvent(TraceEventType.Information,
TraceCode.InstanceContextBoundToDurableInstance, SR.GetString(SR.TraceCodeInstanceContextBoundToDurableInstance),
new StringTraceRecord("InstanceDetail", traceText),
this, null);
}
}
instanceContext = contextItem.InstanceContext;
return true;
}
class ContextItem
{
InstanceContext context;
Guid instanceId;
object lockObject;
int referenceCount;
public ContextItem(Guid instanceId)
{
lockObject = new object();
referenceCount = 0;
this.instanceId = instanceId;
}
public bool HasOutstandingReference
{
get
{
return this.referenceCount > 0;
}
}
public InstanceContext InstanceContext
{
get
{
if (this.context == null)
{
lock (this.lockObject)
{
if (this.context == null)
{
Monitor.Wait(this.lockObject);
}
}
}
Fx.Assert(this.context != null, "Context cannot be null at this point");
return this.context;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.context = value;
lock (this.lockObject)
{
Monitor.PulseAll(this.lockObject);
}
}
}
public int ReferenceCount
{
get
{
return this.referenceCount;
}
}
public int AddReference()
{
//Called from higher locks taken
return ++this.referenceCount;
}
public int ReleaseReference()
{
Fx.Assert(referenceCount > 0, "Reference count gone to negative");
//Called from higher locks taken
return --this.referenceCount;
}
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.IO
{
/// <summary>
/// Implements read-only stream what operates on specified range of source stream
/// </summary>
public class PartialStream : Stream
{
private bool m_IsDisposed = false;
private Stream m_pStream = null;
private long m_Start = 0;
private long m_Length = 0;
private long m_Position = 0;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stream">Source stream.</param>
/// <param name="start">Zero based start positon in source stream.</param>
/// <param name="length">Length of stream.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
public PartialStream(Stream stream,long start,long length)
{
if(stream == null){
throw new ArgumentNullException("stream");
}
if(!stream.CanSeek){
throw new ArgumentException("Argument 'stream' does not support seeking.");
}
if(start < 0){
throw new ArgumentException("Argument 'start' value must be >= 0.");
}
if((start + length) > stream.Length){
throw new ArgumentException("Argument 'length' value will exceed source stream length.");
}
m_pStream = stream;
m_Start = start;
m_Length = length;
}
#region method Dispose
/// <summary>
/// Cleans up any resources being used.
/// </summary>
public new void Dispose()
{
if(m_IsDisposed){
return;
}
m_IsDisposed = true;
base.Dispose();
}
#endregion
#region override method Flush
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public override void Flush()
{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
}
#endregion
#region override method Seek
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public override long Seek(long offset,SeekOrigin origin)
{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
if(origin == SeekOrigin.Begin){
m_Position = 0;
}
else if(origin == SeekOrigin.Current){
}
else if(origin == SeekOrigin.End){
m_Position = m_Length;
}
return m_Position;
}
#endregion
#region override method SetLength
/// <summary>
/// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception>
public override void SetLength(long value)
{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
throw new NotSupportedException();
}
#endregion
#region override method Read
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public override int Read(byte[] buffer,int offset,int count)
{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
if(m_pStream.Position != (m_Start + m_Position)){
m_pStream.Position = m_Start + m_Position;
}
int readedCount = m_pStream.Read(buffer,offset,Math.Min(count,(int)(this.Length - m_Position)));
m_Position += readedCount;
return readedCount;
}
#endregion
#region override method Write
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception>
public override void Write(byte[] buffer,int offset,int count)
{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
throw new NotSupportedException();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanRead
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanSeek
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanWrite
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return false;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="Seek">Is raised when this property is accessed.</exception>
public override long Length
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return m_Length;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override long Position
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return m_Position;
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
if(value < 0 || value > this.Length){
throw new ArgumentException("Property 'Position' value must be >= 0 and <= this.Length.");
}
m_Position = value;
}
}
#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;
using Microsoft.Build.Framework;
using Microsoft.Build.BackEnd.Logging;
using Microsoft.Build.BackEnd;
using Microsoft.Build.Logging;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Execution;
using Microsoft.Build.Exceptions;
using Microsoft.Build.Shared;
using Microsoft.Build.UnitTests.BackEnd;
using System.Threading;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using Shouldly;
using Xunit;
namespace Microsoft.Build.UnitTests.Logging
{
/// <summary>
/// Test the logging service component
/// </summary>
public class LoggingService_Tests
{
#region Data
/// <summary>
/// An already instantiated and initialized service.
/// This is used so the host object does not need to be
/// used in every test method.
/// </summary>
private LoggingService _initializedService;
#endregion
#region Setup
/// <summary>
/// This method is run before each test case is run.
/// We instantiate and initialize a new logging service each time
/// </summary>
public LoggingService_Tests()
{
InitializeLoggingService();
}
#endregion
#region Test BuildComponent Methods
/// <summary>
/// Verify the CreateLogger method create a LoggingService in both Synchronous mode
/// and Asynchronous mode.
/// </summary>
[Fact]
public void CreateLogger()
{
// Generic host which has some default properties set inside of it
IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
// Create a synchronous logging service and do some quick checks
Assert.NotNull(logServiceComponent);
LoggingService logService = (LoggingService)logServiceComponent;
Assert.Equal(LoggerMode.Synchronous, logService.LoggingMode);
Assert.Equal(LoggingServiceState.Instantiated, logService.ServiceState);
// Create an asynchronous logging service
logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Asynchronous, 1);
Assert.NotNull(logServiceComponent);
logService = (LoggingService)logServiceComponent;
Assert.Equal(LoggerMode.Asynchronous, logService.LoggingMode);
Assert.Equal(LoggingServiceState.Instantiated, logService.ServiceState);
// Shutdown logging thread
logServiceComponent.InitializeComponent(new MockHost());
logServiceComponent.ShutdownComponent();
Assert.Equal(LoggingServiceState.Shutdown, logService.ServiceState);
}
/// <summary>
/// Test the IBuildComponent method InitializeComponent, make sure the component gets the parameters it expects
/// </summary>
[Fact]
public void InitializeComponent()
{
IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
BuildParameters parameters = new BuildParameters();
parameters.MaxNodeCount = 4;
parameters.OnlyLogCriticalEvents = true;
IBuildComponentHost loggingHost = new MockHost(parameters);
// Make sure we are in the Instantiated state before initializing
Assert.Equal(LoggingServiceState.Instantiated, ((LoggingService)logServiceComponent).ServiceState);
logServiceComponent.InitializeComponent(loggingHost);
// Make sure that the parameters in the host are set in the logging service
LoggingService service = (LoggingService)logServiceComponent;
Assert.Equal(LoggingServiceState.Initialized, service.ServiceState);
Assert.Equal(4, service.MaxCPUCount);
Assert.True(service.OnlyLogCriticalEvents);
}
/// <summary>
/// Verify the correct exception is thrown when a null Component host is passed in
/// </summary>
[Fact]
public void InitializeComponentNullHost()
{
Assert.Throws<InternalErrorException>(() =>
{
IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
logServiceComponent.InitializeComponent(null);
}
);
}
/// <summary>
/// Verify an exception is thrown if in initialized is called after the service has been shutdown
/// </summary>
[Fact]
public void InitializeComponentAfterShutdown()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.ShutdownComponent();
_initializedService.InitializeComponent(new MockHost());
}
);
}
/// <summary>
/// Verify the correct exceptions are thrown if the loggers crash
/// when they are shutdown
/// </summary>
[Fact]
public void ShutDownComponentExceptionsInForwardingLogger()
{
// Cause a logger exception in the shutdown of the logger
string className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownLoggerExceptionFL";
Type exceptionType = typeof(LoggerException);
VerifyShutdownExceptions(null, className, exceptionType);
Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState);
// Cause a general exception which should result in an InternalLoggerException
className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownGeneralExceptionFL";
exceptionType = typeof(InternalLoggerException);
VerifyShutdownExceptions(null, className, exceptionType);
Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState);
// Cause a StackOverflow exception in the shutdown of the logger
// this kind of exception should not be caught
className = "Microsoft.Build.UnitTests.Logging.LoggingService_Tests+ShutdownStackoverflowExceptionFL";
exceptionType = typeof(StackOverflowException);
VerifyShutdownExceptions(null, className, exceptionType);
Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState);
}
/// <summary>
/// Verify the correct exceptions are thrown when ILoggers
/// throw exceptions during shutdown
/// </summary>
[Fact]
public void ShutDownComponentExceptionsInLogger()
{
LoggerThrowException logger = new LoggerThrowException(true, false, new LoggerException("Hello"));
VerifyShutdownExceptions(logger, null, typeof(LoggerException));
logger = new LoggerThrowException(true, false, new Exception("boo"));
VerifyShutdownExceptions(logger, null, typeof(InternalLoggerException));
logger = new LoggerThrowException(true, false, new StackOverflowException());
VerifyShutdownExceptions(logger, null, typeof(StackOverflowException));
Assert.Equal(LoggingServiceState.Shutdown, _initializedService.ServiceState);
}
/// <summary>
/// Make sure an exception is thrown if shutdown is called
/// more than once
/// </summary>
[Fact]
public void DoubleShutdown()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.ShutdownComponent();
_initializedService.ShutdownComponent();
}
);
}
#endregion
#region RegisterLogger
/// <summary>
/// Verify we get an exception when a null logger is passed in
/// </summary>
[Fact]
public void NullLogger()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.RegisterLogger(null);
}
);
}
/// <summary>
/// Verify we get an exception when we try and register a logger
/// and the system has already shutdown
/// </summary>
[Fact]
public void RegisterLoggerServiceShutdown()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.ShutdownComponent();
RegularILogger regularILogger = new RegularILogger();
_initializedService.RegisterLogger(regularILogger);
}
);
}
/// <summary>
/// Verify a logger exception when initializing a logger is rethrown
/// as a logger exception
/// </summary>
[Fact]
public void LoggerExceptionInInitialize()
{
Assert.Throws<LoggerException>(() =>
{
LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new LoggerException());
_initializedService.RegisterLogger(exceptionLogger);
}
);
}
/// <summary>
/// Verify a general exception when initializing a logger is wrapped
/// as a InternalLogger exception
/// </summary>
[Fact]
public void GeneralExceptionInInitialize()
{
Assert.Throws<InternalLoggerException>(() =>
{
LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new Exception());
_initializedService.RegisterLogger(exceptionLogger);
}
);
}
/// <summary>
/// Verify a critical exception is not wrapped
/// </summary>
[Fact]
public void ILoggerExceptionInInitialize()
{
Assert.Throws<StackOverflowException>(() =>
{
LoggerThrowException exceptionLogger = new LoggerThrowException(false, true, new StackOverflowException());
_initializedService.RegisterLogger(exceptionLogger);
}
);
}
/// <summary>
/// Register an good Logger and verify it was registered.
/// </summary>
[Fact]
public void RegisterILoggerAndINodeLoggerGood()
{
ConsoleLogger consoleLogger = new ConsoleLogger();
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterLogger(consoleLogger));
Assert.True(_initializedService.RegisterLogger(regularILogger));
Assert.NotNull(_initializedService.RegisteredLoggerTypeNames);
// Should have 2 central loggers and 1 forwarding logger
Assert.Equal(3, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.Logging.ConsoleLogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 1 event sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.RegisteredSinkNames);
}
/// <summary>
/// Try and register the same logger multiple times
/// </summary>
[Fact]
public void RegisterDuplicateLogger()
{
ConsoleLogger consoleLogger = new ConsoleLogger();
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterLogger(consoleLogger));
Assert.False(_initializedService.RegisterLogger(consoleLogger));
Assert.True(_initializedService.RegisterLogger(regularILogger));
Assert.False(_initializedService.RegisterLogger(regularILogger));
Assert.NotNull(_initializedService.RegisteredLoggerTypeNames);
Assert.Equal(3, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.Logging.ConsoleLogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 1 event sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.RegisteredSinkNames);
}
#endregion
#region RegisterDistributedLogger
/// <summary>
/// Verify we get an exception when a null logger forwarding logger is passed in
/// </summary>
[Fact]
public void NullForwardingLogger()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.RegisterDistributedLogger(null, null);
}
);
}
/// <summary>
/// Verify we get an exception when we try and register a distributed logger
/// and the system has already shutdown
/// </summary>
[Fact]
public void RegisterDistributedLoggerServiceShutdown()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.ShutdownComponent();
string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
_initializedService.RegisterDistributedLogger(null, description);
}
);
}
/// <summary>
/// Register both a good central logger and a good forwarding logger
/// </summary>
[Fact]
public void RegisterGoodDistributedAndCentralLogger()
{
string configurableClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
string distributedClassName = "Microsoft.Build.Logging.DistributedFileLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription configurableDescription = CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
LoggerDescription distributedDescription = CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
DistributedFileLogger fileLogger = new DistributedFileLogger();
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, configurableDescription));
Assert.True(_initializedService.RegisterDistributedLogger(null, distributedDescription));
Assert.NotNull(_initializedService.RegisteredLoggerTypeNames);
// Should have 2 central loggers and 2 forwarding logger
Assert.Equal(4, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.Logging.DistributedFileLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.BackEnd.Logging.NullCentralLogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 2 event sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Equal(2, _initializedService.RegisteredSinkNames.Count);
Assert.Equal(2, _initializedService.LoggerDescriptions.Count);
}
/// <summary>
/// Have a one forwarding logger which forwards build started and finished and have one which does not and a regular logger. Expect the central loggers to all get
/// one build started and one build finished event only.
/// </summary>
[Fact]
public void RegisterGoodDistributedAndCentralLoggerTestBuildStartedFinished()
{
string configurableClassNameA = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
string configurableClassNameB = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription configurableDescriptionA = CreateLoggerDescription(configurableClassNameA, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
LoggerDescription configurableDescriptionB = CreateLoggerDescription(configurableClassNameB, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
RegularILogger regularILoggerA = new RegularILogger();
RegularILogger regularILoggerB = new RegularILogger();
RegularILogger regularILoggerC = new RegularILogger();
Assert.True(_initializedService.RegisterDistributedLogger(regularILoggerA, configurableDescriptionA));
Assert.True(_initializedService.RegisterDistributedLogger(regularILoggerB, configurableDescriptionB));
Assert.True(_initializedService.RegisterLogger(regularILoggerC));
Assert.NotNull(_initializedService.RegisteredLoggerTypeNames);
_initializedService.LogBuildStarted();
Assert.Equal(1, regularILoggerA.BuildStartedCount);
Assert.Equal(1, regularILoggerB.BuildStartedCount);
Assert.Equal(1, regularILoggerC.BuildStartedCount);
_initializedService.LogBuildFinished(true);
Assert.Equal(1, regularILoggerA.BuildFinishedCount);
Assert.Equal(1, regularILoggerB.BuildFinishedCount);
Assert.Equal(1, regularILoggerC.BuildFinishedCount);
// Make sure if we call build started again we only get one other build started event.
_initializedService.LogBuildStarted();
Assert.Equal(2, regularILoggerA.BuildStartedCount);
Assert.Equal(2, regularILoggerB.BuildStartedCount);
Assert.Equal(2, regularILoggerC.BuildStartedCount);
// Make sure if we call build started again we only get one other build started event.
_initializedService.LogBuildFinished(true);
Assert.Equal(2, regularILoggerA.BuildFinishedCount);
Assert.Equal(2, regularILoggerB.BuildFinishedCount);
Assert.Equal(2, regularILoggerC.BuildFinishedCount);
}
/// <summary>
/// Try and register a duplicate central logger
/// </summary>
[Fact]
public void RegisterDuplicateCentralLogger()
{
string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description));
Assert.False(_initializedService.RegisterDistributedLogger(regularILogger, description));
// Should have 2 central loggers and 1 forwarding logger
Assert.Equal(2, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 1 sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.LoggerDescriptions);
}
/// <summary>
/// Try and register a duplicate Forwarding logger
/// </summary>
[Fact]
public void RegisterDuplicateForwardingLoggerLogger()
{
string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description));
Assert.True(_initializedService.RegisterDistributedLogger(null, description));
Assert.Equal(4, _initializedService.RegisteredLoggerTypeNames.Count);
// Verify there are two versions in the type names, one for each description
int countForwardingLogger = 0;
foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames)
{
if (String.Equals("Microsoft.Build.Logging.ConfigurableForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase))
{
countForwardingLogger++;
}
}
Assert.Equal(2, countForwardingLogger);
Assert.Contains("Microsoft.Build.BackEnd.Logging.NullCentralLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 2 sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Equal(2, _initializedService.RegisteredSinkNames.Count);
Assert.Equal(2, _initializedService.LoggerDescriptions.Count);
}
#endregion
#region RegisterLoggerDescriptions
/// <summary>
/// Verify we get an exception when a null description collection is passed in
/// </summary>
[Fact]
public void NullDescriptionCollection()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.InitializeNodeLoggers(null, new EventSourceSink(), 3);
}
);
}
/// <summary>
/// Verify we get an exception when an empty description collection is passed in
/// </summary>
[Fact]
public void EmptyDescriptionCollection()
{
Assert.Throws<InternalErrorException>(() =>
{
_initializedService.InitializeNodeLoggers(new List<LoggerDescription>(), new EventSourceSink(), 3);
}
);
}
/// <summary>
/// Verify we get an exception when we try and register a description and the component has already shutdown
/// </summary>
[Fact]
public void NullForwardingLoggerSink()
{
Assert.Throws<InternalErrorException>(() =>
{
string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
_initializedService.ShutdownComponent();
List<LoggerDescription> tempList = new List<LoggerDescription>();
tempList.Add(description);
_initializedService.InitializeNodeLoggers(tempList, new EventSourceSink(), 2);
}
);
}
/// <summary>
/// Register both a good central logger and a good forwarding logger
/// </summary>
[Fact]
public void RegisterGoodDiscriptions()
{
string configurableClassName = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
string distributedClassName = "Microsoft.Build.BackEnd.Logging.CentralForwardingLogger";
EventSourceSink sink = new EventSourceSink();
EventSourceSink sink2 = new EventSourceSink();
List<LoggerDescription> loggerDescriptions = new List<LoggerDescription>();
#if FEATURE_ASSEMBLY_LOCATION
loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true));
loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true));
#else
loggerDescriptions.Add(CreateLoggerDescription(configurableClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true));
loggerDescriptions.Add(CreateLoggerDescription(distributedClassName, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true));
#endif
// Register some descriptions with a sink
_initializedService.InitializeNodeLoggers(loggerDescriptions, sink, 1);
// Register the same descriptions with another sink (so we can see that another sink was added)
_initializedService.InitializeNodeLoggers(loggerDescriptions, sink2, 1);
// Register the descriptions again with the same sink so we can verify that another sink was not created
_initializedService.InitializeNodeLoggers(loggerDescriptions, sink, 1);
Assert.NotNull(_initializedService.RegisteredLoggerTypeNames);
// Should have 6 forwarding logger. three of each type
Assert.Equal(6, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
int countForwardingLogger = 0;
foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames)
{
if (String.Equals("Microsoft.Build.Logging.ConfigurableForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase))
{
countForwardingLogger++;
}
}
// Should be 3, one for each call to RegisterLoggerDescriptions
Assert.Equal(3, countForwardingLogger);
countForwardingLogger = 0;
foreach (string loggerName in _initializedService.RegisteredLoggerTypeNames)
{
if (String.Equals("Microsoft.Build.BackEnd.Logging.CentralForwardingLogger", loggerName, StringComparison.OrdinalIgnoreCase))
{
countForwardingLogger++;
}
}
// Should be 3, one for each call to RegisterLoggerDescriptions
Assert.Equal(3, countForwardingLogger);
// Should have 2 event sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Equal(2, _initializedService.RegisteredSinkNames.Count);
// There should not be any (this method is to be called on a child node)
Assert.Empty(_initializedService.LoggerDescriptions);
}
/// <summary>
/// Try and register a duplicate central logger
/// </summary>
[Fact]
public void RegisterDuplicateDistributedCentralLogger()
{
string className = "Microsoft.Build.Logging.ConfigurableForwardingLogger";
#if FEATURE_ASSEMBLY_LOCATION
LoggerDescription description = CreateLoggerDescription(className, Assembly.GetAssembly(typeof(ProjectCollection)).FullName, true);
#else
LoggerDescription description = CreateLoggerDescription(className, typeof(ProjectCollection).GetTypeInfo().Assembly.FullName, true);
#endif
RegularILogger regularILogger = new RegularILogger();
Assert.True(_initializedService.RegisterDistributedLogger(regularILogger, description));
Assert.False(_initializedService.RegisterDistributedLogger(regularILogger, description));
// Should have 2 central loggers and 1 forwarding logger
Assert.Equal(2, _initializedService.RegisteredLoggerTypeNames.Count);
Assert.Contains("Microsoft.Build.Logging.ConfigurableForwardingLogger", _initializedService.RegisteredLoggerTypeNames);
Assert.Contains("Microsoft.Build.UnitTests.Logging.LoggingService_Tests+RegularILogger", _initializedService.RegisteredLoggerTypeNames);
// Should have 1 sink
Assert.NotNull(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.RegisteredSinkNames);
Assert.Single(_initializedService.LoggerDescriptions);
}
#endregion
#region Test Properties
/// <summary>
/// Verify the getters and setters for the properties work.
/// </summary>
[Fact]
public void Properties()
{
// Test OnlyLogCriticalEvents
LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
Assert.False(loggingService.OnlyLogCriticalEvents); // "Expected only log critical events to be false"
loggingService.OnlyLogCriticalEvents = true;
Assert.True(loggingService.OnlyLogCriticalEvents); // "Expected only log critical events to be true"
// Test LoggingMode
Assert.Equal(LoggerMode.Synchronous, loggingService.LoggingMode); // "Expected Logging mode to be Synchronous"
// Test LoggerDescriptions
Assert.Empty(loggingService.LoggerDescriptions); // "Expected LoggerDescriptions to be empty"
// Test Number of InitialNodes
Assert.Equal(1, loggingService.MaxCPUCount);
loggingService.MaxCPUCount = 5;
Assert.Equal(5, loggingService.MaxCPUCount);
// Test MinimumRequiredMessageImportance
Assert.Equal(MessageImportance.Low, loggingService.MinimumRequiredMessageImportance);
loggingService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
Assert.Equal(MessageImportance.Normal, loggingService.MinimumRequiredMessageImportance);
}
#endregion
#region PacketHandling Tests
/// <summary>
/// Verify how a null packet is handled. There should be an InternalErrorException thrown
/// </summary>
[Fact]
public void NullPacketReceived()
{
Assert.Throws<InternalErrorException>(() =>
{
LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
loggingService.PacketReceived(1, null);
}
);
}
/// <summary>
/// Verify when a non logging packet is received.
/// An invalid operation should be thrown
/// </summary>
[Fact]
public void NonLoggingPacketPacketReceived()
{
Assert.Throws<InternalErrorException>(() =>
{
LoggingService loggingService = (LoggingService)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
NonLoggingPacket packet = new NonLoggingPacket();
loggingService.PacketReceived(1, packet);
}
);
}
/// <summary>
/// Verify when a logging packet is received the build event is
/// properly passed to ProcessLoggingEvent
/// An invalid operation should be thrown
/// </summary>
[Fact]
public void LoggingPacketReceived()
{
LoggingServicesLogMethod_Tests.ProcessBuildEventHelper loggingService = (LoggingServicesLogMethod_Tests.ProcessBuildEventHelper)LoggingServicesLogMethod_Tests.ProcessBuildEventHelper.CreateLoggingService(LoggerMode.Synchronous, 1);
BuildMessageEventArgs messageEvent = new BuildMessageEventArgs("MyMessage", "HelpKeyword", "Sender", MessageImportance.High);
LogMessagePacket packet = new LogMessagePacket(new KeyValuePair<int, BuildEventArgs>(1, messageEvent));
loggingService.PacketReceived(1, packet);
BuildMessageEventArgs messageEventFromPacket = loggingService.ProcessedBuildEvent as BuildMessageEventArgs;
Assert.NotNull(messageEventFromPacket);
Assert.Equal(messageEventFromPacket, messageEvent); // "Expected messages to match"
}
#endregion
#region WarningsAsErrors Tests
private static readonly BuildWarningEventArgs BuildWarningEventForTreatAsErrorOrMessageTests = new BuildWarningEventArgs("subcategory", "C94A41A90FFB4EF592BF98BA59BEE8AF", "file", 1, 2, 3, 4, "message", "helpKeyword", "senderName");
/// <summary>
/// Verifies that a warning is logged as an error when it's warning code specified.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsErrorWhenSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsErrors = new HashSet<string>
{
"123",
BuildWarningEventForTreatAsErrorOrMessageTests.Code,
"ABC",
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrors);
BuildErrorEventArgs actualBuildEvent = logger.Errors.ShouldHaveSingleItem();
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp);
}
/// <summary>
/// Verifies that a warning is not treated as an error when other warning codes are specified.
/// </summary>
[Fact]
public void NotTreatWarningsAsErrorWhenNotSpecified()
{
HashSet<string> warningsAsErrors = new HashSet<string>
{
"123",
"ABC",
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, warningsAsErrors: warningsAsErrors);
var actualEvent = logger.Warnings.ShouldHaveSingleItem();
actualEvent.ShouldBe(BuildWarningEventForTreatAsErrorOrMessageTests);
}
/// <summary>
/// Verifies that a warning is not treated as an error when other warning codes are specified.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsErrorWhenAllSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsErrors = new HashSet<string>();
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrors);
logger.Errors.ShouldHaveSingleItem();
}
/// <summary>
/// Verifies that a warning is logged as a low importance message when it's warning code is specified.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsMessagesWhenSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsMessages = new HashSet<string>
{
"FOO",
BuildWarningEventForTreatAsErrorOrMessageTests.Code,
"BAR",
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsMessages: warningsAsMessages);
BuildMessageEventArgs actualBuildEvent = logger.BuildMessageEvents.ShouldHaveSingleItem();
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword);
Assert.Equal(MessageImportance.Low, actualBuildEvent.Importance);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp);
}
/// <summary>
/// Verifies that a warning is not treated as a low importance message when other warning codes are specified.
/// </summary>
[Fact]
public void NotTreatWarningsAsMessagesWhenNotSpecified()
{
HashSet<string> warningsAsMessages = new HashSet<string>
{
"FOO",
"BAR",
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, warningsAsMessages: warningsAsMessages);
logger.Warnings.ShouldHaveSingleItem();
}
/// <summary>
/// Verifies that warnings are treated as an error for a particular project when codes are specified.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsErrorByProjectWhenSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsErrorsForProject = new HashSet<string>
{
"123",
BuildWarningEventForTreatAsErrorOrMessageTests.Code,
"ABC"
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrorsForProject: warningsAsErrorsForProject);
BuildErrorEventArgs actualBuildEvent = logger.Errors.ShouldHaveSingleItem();
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp);
}
/// <summary>
/// Verifies that all warnings are treated as errors for a particular project.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsErrorByProjectWhenAllSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsErrorsForProject = new HashSet<string>();
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsErrorsForProject: warningsAsErrorsForProject);
logger.Errors.ShouldHaveSingleItem();
}
/// <summary>
/// Verifies that warnings are treated as messages for a particular project.
/// </summary>
[Theory]
[InlineData(0, 1)]
[InlineData(0, 2)]
[InlineData(1, 1)]
[InlineData(1, 2)]
public void TreatWarningsAsMessagesByProjectWhenSpecified(int loggerMode, int nodeId)
{
HashSet<string> warningsAsMessagesForProject = new HashSet<string>
{
"123",
BuildWarningEventForTreatAsErrorOrMessageTests.Code,
"ABC"
};
MockLogger logger = GetLoggedEventsWithWarningsAsErrorsOrMessages(BuildWarningEventForTreatAsErrorOrMessageTests, (LoggerMode)loggerMode, nodeId, warningsAsMessagesForProject: warningsAsMessagesForProject);
BuildMessageEventArgs actualBuildEvent = logger.BuildMessageEvents.ShouldHaveSingleItem();
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.BuildEventContext, actualBuildEvent.BuildEventContext);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Code, actualBuildEvent.Code);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ColumnNumber, actualBuildEvent.ColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndColumnNumber, actualBuildEvent.EndColumnNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.EndLineNumber, actualBuildEvent.EndLineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.File, actualBuildEvent.File);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.HelpKeyword, actualBuildEvent.HelpKeyword);
Assert.Equal(MessageImportance.Low, actualBuildEvent.Importance);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.LineNumber, actualBuildEvent.LineNumber);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Message, actualBuildEvent.Message);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.ProjectFile, actualBuildEvent.ProjectFile);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.SenderName, actualBuildEvent.SenderName);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Subcategory, actualBuildEvent.Subcategory);
Assert.Equal(BuildWarningEventForTreatAsErrorOrMessageTests.Timestamp, actualBuildEvent.Timestamp);
}
private MockLogger GetLoggedEventsWithWarningsAsErrorsOrMessages(
BuildEventArgs buildEvent,
LoggerMode loggerMode = LoggerMode.Synchronous,
int nodeId = 1,
ISet<string> warningsAsErrors = null,
ISet<string> warningsAsMessages = null,
ISet<string> warningsAsErrorsForProject = null,
ISet<string> warningsAsMessagesForProject = null)
{
IBuildComponentHost host = new MockHost();
BuildEventContext buildEventContext = new BuildEventContext(
submissionId: 0,
nodeId: 1,
projectInstanceId: 2,
projectContextId: -1,
targetId: -1,
taskId: -1);
BuildRequestData buildRequestData = new BuildRequestData("projectFile", new Dictionary<string, string>(), "Current", new[] { "Build" }, null);
ConfigCache configCache = host.GetComponent(BuildComponentType.ConfigCache) as ConfigCache;
configCache.AddConfiguration(new BuildRequestConfiguration(buildEventContext.ProjectInstanceId, buildRequestData, buildRequestData.ExplicitlySpecifiedToolsVersion));
MockLogger logger = new MockLogger();
ILoggingService loggingService = LoggingService.CreateLoggingService(loggerMode, nodeId);
((IBuildComponent)loggingService).InitializeComponent(host);
loggingService.RegisterLogger(logger);
BuildEventContext projectStarted = loggingService.LogProjectStarted(buildEventContext, 0, buildEventContext.ProjectInstanceId, BuildEventContext.Invalid, "projectFile", "Build", Enumerable.Empty<DictionaryEntry>(), Enumerable.Empty<DictionaryEntry>());
if (warningsAsErrorsForProject != null)
{
loggingService.AddWarningsAsErrors(projectStarted, warningsAsErrorsForProject);
}
if (warningsAsMessagesForProject != null)
{
loggingService.AddWarningsAsMessages(projectStarted, warningsAsMessagesForProject);
}
loggingService.WarningsAsErrors = warningsAsErrors;
loggingService.WarningsAsMessages = warningsAsMessages;
buildEvent.BuildEventContext = projectStarted;
loggingService.LogBuildEvent(buildEvent);
loggingService.LogProjectFinished(projectStarted, "projectFile", true);
while (logger.ProjectFinishedEvents.Count == 0)
{
Thread.Sleep(100);
}
((IBuildComponent)loggingService).ShutdownComponent();
return logger;
}
#endregion
#region MinimumRequiredMessageImportance Tests
[Fact]
public void ImportanceReflectsConsoleLoggerVerbosity()
{
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Quiet));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.High - 1);
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Minimal));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.High);
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Normal);
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Detailed));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Diagnostic));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
}
[Fact]
public void ImportanceReflectsConfigurableForwardingLoggerVerbosity()
{
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Quiet));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.High - 1);
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Minimal));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.High);
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Normal));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Normal);
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Detailed));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Diagnostic));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
}
[Fact]
public void ImportanceReflectsCentralForwardingLoggerVerbosity()
{
MockHost mockHost = new MockHost();
ILoggingService node1LoggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
((IBuildComponent)node1LoggingService).InitializeComponent(mockHost);
ILoggingService node2LoggingService = LoggingService.CreateLoggingService(LoggerMode.Synchronous, 2);
((IBuildComponent)node2LoggingService).InitializeComponent(mockHost);
// CentralForwardingLogger is always registered in in-proc nodes and it does not affect minimum importance.
node1LoggingService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Minimal));
node1LoggingService.RegisterLogger(new CentralForwardingLogger());
node1LoggingService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.High);
// CentralForwardingLogger in out-of-proc nodes means that we are forwarding everything and the minimum importance
// is Low regardless of what other loggers are registered.
node2LoggingService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Minimal));
node2LoggingService.RegisterLogger(new CentralForwardingLogger());
node2LoggingService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
// Register another ConsoleLogger and verify that minimum importance hasn't changed.
node2LoggingService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Minimal));
node2LoggingService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
}
[Fact]
public void ImportanceReflectsUnknownLoggerVerbosity()
{
// Minimum message importance is Low (i.e. we're logging everything) even when all registered loggers have
// Normal verbosity if at least of one them is not on our whitelist.
_initializedService.RegisterLogger(new ConsoleLogger(LoggerVerbosity.Normal));
_initializedService.RegisterLogger(new MockLogger() { Verbosity = LoggerVerbosity.Normal });
_initializedService.RegisterLogger(CreateConfigurableForwardingLogger(LoggerVerbosity.Normal));
_initializedService.MinimumRequiredMessageImportance.ShouldBe(MessageImportance.Low);
}
#endregion
#region PrivateMethods
/// <summary>
/// Instantiate and Initialize a new loggingService.
/// This is used by the test setup method to create
/// a new logging service before each test.
/// </summary>
private void InitializeLoggingService()
{
BuildParameters parameters = new BuildParameters();
parameters.MaxNodeCount = 2;
MockHost mockHost = new MockHost(parameters);
IBuildComponent logServiceComponent = (IBuildComponent)LoggingService.CreateLoggingService(LoggerMode.Synchronous, 1);
logServiceComponent.InitializeComponent(mockHost);
_initializedService = logServiceComponent as LoggingService;
}
/// <summary>
/// Register the correct logger and then call the shutdownComponent method.
/// This will call shutdown on the loggers, we should expect to see certain exceptions.
/// </summary>
/// <param name="logger">Logger to register, this will only be used if className is null</param>
/// <param name="className">ClassName to instantiate a new distributed logger</param>
/// <param name="expectedExceptionType">Exception type which is expected to be thrown</param>
private void VerifyShutdownExceptions(ILogger logger, string className, Type expectedExceptionType)
{
InitializeLoggingService();
if (className != null)
{
#if FEATURE_ASSEMBLY_LOCATION
Assembly thisAssembly = Assembly.GetAssembly(typeof(LoggingService_Tests));
#else
Assembly thisAssembly = typeof(LoggingService_Tests).GetTypeInfo().Assembly;
#endif
string loggerAssemblyName = thisAssembly.FullName;
LoggerDescription centralLoggerDescrption = CreateLoggerDescription(className, loggerAssemblyName, true);
_initializedService.RegisterDistributedLogger(null, centralLoggerDescrption);
}
else
{
_initializedService.RegisterLogger(logger);
}
try
{
_initializedService.ShutdownComponent();
Assert.True(false, "No Exceptions Generated");
}
catch (Exception e)
{
if (e.GetType() != expectedExceptionType)
{
Assert.True(false, "Expected a " + expectedExceptionType + " but got a " + e.GetType() + " Stack:" + e.ToString());
}
}
}
/// <summary>
/// Create a logger description from the class name and logger assembly
/// This is used in any test which needs to register a distributed logger.
/// </summary>
/// <param name="loggerClassName">Fully qualified class name (don't for get ParentClass+Nestedclass, if nested)</param>
/// <param name="loggerAssemblyName">Assembly name which contains class</param>
/// <returns>A logger description which can be registered</returns>
private LoggerDescription CreateLoggerDescription(string loggerClassName, string loggerAssemblyName, bool forwardAllEvents)
{
string eventsToForward = "CustomEvent";
if (forwardAllEvents)
{
eventsToForward = "BuildStartedEvent;BuildFinishedEvent;ProjectStartedEvent;ProjectFinishedEvent;TargetStartedEvent;TargetFinishedEvent;TaskStartedEvent;TaskFinishedEvent;ErrorEvent;WarningEvent;HighMessageEvent;NormalMessageEvent;LowMessageEvent;CustomEvent;CommandLine";
}
LoggerDescription centralLoggerDescrption = new LoggerDescription
(
loggerClassName,
loggerAssemblyName,
null /*Not needed as we are loading from current assembly*/,
eventsToForward,
LoggerVerbosity.Diagnostic /*Not used, but the spirit of the logger is to forward everything so this is the most appropriate verbosity */
);
return centralLoggerDescrption;
}
/// <summary>
/// Creates a new <see cref="ConfigurableForwardingLogger"/> with the given verbosity.
/// </summary>
private ConfigurableForwardingLogger CreateConfigurableForwardingLogger(LoggerVerbosity verbosity)
{
return new ConfigurableForwardingLogger()
{
Verbosity = verbosity
};
}
#endregion
#region HelperClasses
/// <summary>
/// A forwarding logger which will throw an exception
/// </summary>
public class BaseFLThrowException : LoggerThrowException, IForwardingLogger
{
#region Constructor
/// <summary>
/// Create a forwarding logger which will throw an exception on initialize or shutdown
/// </summary>
/// <param name="throwOnShutdown">Throw exception on shutdown</param>
/// <param name="throwOnInitialize">Throw exception on initialize</param>
/// <param name="exception">Exception to throw</param>
internal BaseFLThrowException(bool throwOnShutdown, bool throwOnInitialize, Exception exception)
: base(throwOnShutdown, throwOnInitialize, exception)
{
}
#endregion
#region IForwardingLogger Members
/// <summary>
/// Not used, implemented due to interface
/// </summary>
/// <value>Notused</value>
public IEventRedirector BuildEventRedirector
{
get;
set;
}
/// <summary>
/// Not used, implemented due to interface
/// </summary>
/// <value>Not used</value>
public int NodeId
{
get;
set;
}
#endregion
}
/// <summary>
/// Forwarding logger which throws a logger exception in the shutdown method.
/// This is to test the logging service exception handling.
/// </summary>
public class ShutdownLoggerExceptionFL : BaseFLThrowException
{
/// <summary>
/// Create a logger which will throw a logger exception
/// in the shutdown method
/// </summary>
public ShutdownLoggerExceptionFL()
: base(true, false, new LoggerException("Hello"))
{
}
}
/// <summary>
/// Forwarding logger which will throw a general exception in the shutdown method
/// This is used to test the logging service shutdown handling method.
/// </summary>
public class ShutdownGeneralExceptionFL : BaseFLThrowException
{
/// <summary>
/// Create a logger which logs a general exception in the shutdown method
/// </summary>
public ShutdownGeneralExceptionFL()
: base(true, false, new Exception("Hello"))
{
}
}
/// <summary>
/// Forwarding logger which will throw a StackOverflowException
/// in the shutdown method. This is to test the shutdown exception handling
/// </summary>
public class ShutdownStackoverflowExceptionFL : BaseFLThrowException
{
/// <summary>
/// Create a logger which will throw a StackOverflow exception
/// in the shutdown method.
/// </summary>
public ShutdownStackoverflowExceptionFL()
: base(true, false, new StackOverflowException())
{
}
}
/// <summary>
/// Logger which can throw a defined exception in the initialize or shutdown methods
/// </summary>
public class LoggerThrowException : INodeLogger
{
#region Constructor
/// <summary>
/// Constructor to tell the logger when to throw an exception and what exception
/// to throw
/// </summary>
/// <param name="throwOnShutdown">True, throw the exception when shutdown is called</param>
/// <param name="throwOnInitialize">True, throw the exception when Initialize is called</param>
/// <param name="exception">The exception to throw</param>
internal LoggerThrowException(bool throwOnShutdown, bool throwOnInitialize, Exception exception)
{
ExceptionToThrow = exception;
ThrowExceptionOnShutdown = throwOnShutdown;
ThrowExceptionOnInitialize = throwOnInitialize;
}
#endregion
#region Properties
/// <summary>
/// Not used, implemented due to ILoggerInterface
/// </summary>
/// <value>Not used</value>
public LoggerVerbosity Verbosity
{
get;
set;
}
/// <summary>
/// Not used, implemented due to ILoggerInterface
/// </summary>
/// <value>Not used</value>
public string Parameters
{
get;
set;
}
/// <summary>
/// Should the exception be thrown on the call to shutdown
/// </summary>
/// <value>Not used</value>
protected bool ThrowExceptionOnShutdown
{
get;
set;
}
/// <summary>
/// Should the exception be thrown on the call to initialize
/// </summary>
/// <value>Not used</value>
protected bool ThrowExceptionOnInitialize
{
get;
set;
}
/// <summary>
/// The exception which will be thrown in shutdown or initialize
/// </summary>
/// <value>Not used</value>
protected Exception ExceptionToThrow
{
get;
set;
}
#endregion
#region ILogger Members
/// <summary>
/// Initialize the logger, throw an exception
/// if ThrowExceptionOnInitialize is set
/// </summary>
/// <param name="eventSource">Not used</param>
public void Initialize(IEventSource eventSource)
{
if (ThrowExceptionOnInitialize && ExceptionToThrow != null)
{
throw ExceptionToThrow;
}
}
/// <summary>
/// Shutdown the logger, throw an exception if
/// ThrowExceptionOnShutdown is set
/// </summary>
public void Shutdown()
{
if (ThrowExceptionOnShutdown && ExceptionToThrow != null)
{
throw ExceptionToThrow;
}
}
/// <summary>
/// Initialize using the INodeLogger Interface
/// </summary>
/// <param name="eventSource">Not used</param>
/// <param name="nodeCount">Not used</param>
public void Initialize(IEventSource eventSource, int nodeCount)
{
Initialize(eventSource);
}
#endregion
}
/// <summary>
/// Create a regular ILogger to test Registering ILoggers.
/// </summary>
public class RegularILogger : ILogger
{
#region Properties
/// <summary>
/// ParametersForTheLogger
/// </summary>
public string Parameters
{
get;
set;
}
/// <summary>
/// Verbosity
/// </summary>
public LoggerVerbosity Verbosity
{
get;
set;
}
/// <summary>
/// Number of times build started was logged
/// </summary>
internal int BuildStartedCount
{
get;
set;
}
/// <summary>
/// Number of times build finished was logged
/// </summary>
internal int BuildFinishedCount
{
get;
set;
}
/// <summary>
/// Initialize
/// </summary>
public void Initialize(IEventSource eventSource)
{
eventSource.AnyEventRaised +=
LoggerEventHandler;
}
/// <summary>
/// DoNothing
/// </summary>
public void Shutdown()
{
// do nothing
}
/// <summary>
/// Log the event
/// </summary>
internal void LoggerEventHandler(object sender, BuildEventArgs eventArgs)
{
if (eventArgs is BuildStartedEventArgs)
{
++BuildStartedCount;
}
if (eventArgs is BuildFinishedEventArgs)
{
++BuildFinishedCount;
}
}
}
/// <summary>
/// Create a regular ILogger which keeps track of how many of each event were logged
/// </summary>
public class TestLogger : ILogger
{
/// <summary>
/// Not Used
/// </summary>
/// <value>Not used</value>
public LoggerVerbosity Verbosity
{
get;
set;
}
/// <summary>
/// Do Nothing
/// </summary>
/// <value>Not Used</value>
public string Parameters
{
get;
set;
}
/// <summary>
/// Do Nothing
/// </summary>
/// <param name="eventSource">Not Used</param>
public void Initialize(IEventSource eventSource)
{
}
/// <summary>
/// Do Nothing
/// </summary>
public void Shutdown()
{
}
#endregion
}
/// <summary>
/// Create a non logging packet to test the packet handling code
/// </summary>
internal class NonLoggingPacket : INodePacket
{
#region Members
/// <summary>
/// Inform users of the class, this class is a BuildRequest packet
/// </summary>
public NodePacketType Type
{
get
{
return NodePacketType.BuildRequest;
}
}
/// <summary>
/// Serialize the packet
/// </summary>
public void Translate(ITranslator translator)
{
throw new NotImplementedException();
}
#endregion
}
#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.
/******************************************************************************
* 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 MinByte()
{
var test = new SimpleBinaryOpTest__MinByte();
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__MinByte
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(Byte);
private static Byte[] _data1 = new Byte[ElementCount];
private static Byte[] _data2 = new Byte[ElementCount];
private static Vector128<Byte> _clsVar1;
private static Vector128<Byte> _clsVar2;
private Vector128<Byte> _fld1;
private Vector128<Byte> _fld2;
private SimpleBinaryOpTest__DataTable<Byte> _dataTable;
static SimpleBinaryOpTest__MinByte()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MinValue)); _data2[i] = (byte)(random.Next(0, byte.MinValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar1), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar2), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__MinByte()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MinValue)); _data2[i] = (byte)(random.Next(0, byte.MinValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld1), ref Unsafe.As<Byte, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld2), ref Unsafe.As<Byte, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (byte)(random.Next(0, byte.MinValue)); _data2[i] = (byte)(random.Next(0, byte.MinValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<Byte>(_data1, _data2, new Byte[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Min(
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Min(
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Min(
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Min), new Type[] { typeof(Vector128<Byte>), typeof(Vector128<Byte>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Min(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<Byte>>(_dataTable.inArray2Ptr);
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArray2Ptr));
var result = Sse2.Min(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__MinByte();
var result = Sse2.Min(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Min(_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(Vector128<Byte> left, Vector128<Byte> right, void* result, [CallerMemberName] string method = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, 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 = "")
{
Byte[] inArray1 = new Byte[ElementCount];
Byte[] inArray2 = new Byte[ElementCount];
Byte[] outArray = new Byte[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Byte[] left, Byte[] right, Byte[] result, [CallerMemberName] string method = "")
{
if (Math.Min(left[0], right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if (Math.Min(left[i], right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Min)}<Byte>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
using System;
using AuthenticodeLint.Core.Asn;
using Xunit;
namespace AuthenticodeLint.Core.Tests
{
public class AsnGeneralizedTimeTests
{
[Fact]
public void ShouldDecodeSimpleLocalWithHours()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0A, //with a length of 10
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 2080121023
0x32, 0x31, 0x30, 0x32, 0x33
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTime(2080, 12, 10, 23, 00, 00, DateTimeKind.Local);
Assert.Equal(expectedDateTime, generalizedTime.Value.LocalDateTime);
Assert.Equal(expectedDateTime, generalizedTime.Value.DateTime);
}
[Fact]
public void ShouldDecodeSimpleLocalWithHoursAndMinutes()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0C, //with a length of 12
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 208012102345
0x32, 0x31, 0x30, 0x32, 0x33, 0x34, 0x35
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTime(2080, 12, 10, 23, 45, 00, DateTimeKind.Local);
Assert.Equal(expectedDateTime, generalizedTime.Value.LocalDateTime);
Assert.Equal(expectedDateTime, generalizedTime.Value.DateTime);
}
[Fact]
public void ShouldDecodeSimpleLocalWithHoursAndMinutesAndSeconds()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0E, //with a length of 14
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 20801210234557
0x32, 0x31, 0x30, 0x32, 0x33, 0x34, 0x35, 0x35, 0x37
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTime(2080, 12, 10, 23, 45, 57, DateTimeKind.Local);
Assert.Equal(expectedDateTime, generalizedTime.Value.LocalDateTime);
Assert.Equal(expectedDateTime, generalizedTime.Value.DateTime);
}
[Fact]
public void ShouldDecodeSimpleLocalWithHoursAndMinutesAndSecondsAndFractionalSeconds()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x12, //with a length of 18
0x32, 0x30, 0x38, 0x30, 0x31, 0x32, 0x31, //20801210234557.999
0x30, 0x32, 0x33, 0x34, 0x35, 0x35, 0x37,
0x2e, 0x39, 0x39, 0x39
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTime(2080, 12, 10, 23, 45, 57, DateTimeKind.Local).AddMilliseconds(999);
Assert.Equal(expectedDateTime, generalizedTime.Value.LocalDateTime);
Assert.Equal(expectedDateTime, generalizedTime.Value.DateTime);
}
[Fact]
public void ShouldDecodeSimpleUtcWithHours()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0B, //with a length of 11
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 2080121023Z
0x32, 0x31, 0x30, 0x32, 0x33, 0x5A
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2080, 12, 10, 23, 00, 00, TimeSpan.Zero);
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleUtcWithHoursAndMinutes()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0D, //with a length of 13
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 208012102345Z
0x32, 0x31, 0x30, 0x32, 0x33, 0x34, 0x35, 0x5A
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2080, 12, 10, 23, 45, 00, TimeSpan.Zero);
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleUtcWithHoursAndMinutesAndSeconds()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0F, //with a length of 15
0x32, 0x30, 0x38, 0x30, 0x31, //ASCII for 20801210234557Z
0x32, 0x31, 0x30, 0x32, 0x33, 0x34, 0x35, 0x35, 0x37, 0x5A
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2080, 12, 10, 23, 45, 57, TimeSpan.Zero);
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleUtcWithHoursAndMinutesAndSecondsAndFractionalSeconds()
{
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x13, //with a length of 19
0x32, 0x30, 0x38, 0x30, 0x31, 0x32, 0x31, //20801210234557.999Z
0x30, 0x32, 0x33, 0x34, 0x35, 0x35, 0x37,
0x2e, 0x39, 0x39, 0x39, 0x5A
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2080, 12, 10, 23, 45, 57, TimeSpan.Zero).AddMilliseconds(999);
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleOffsetWithHours()
{
//2014031106-0545
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x0F, //with a length of 15
0x32, 0x30, 0x31, 0x34, 0x30, 0x33, 0x31,
0x31, 0x30, 0x36, 0x2d, 0x30, 0x35, 0x34, 0x35
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2014, 03, 11, 06, 00, 00, -new TimeSpan(5, 45, 0));
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleOffsetWithHoursAndMinutes()
{
//201403110637-0545
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x11, //with a length of 17
0x32, 0x30, 0x31, 0x34, 0x30, 0x33, 0x31,
0x31, 0x30, 0x36, 0x33, 0x37, 0x2d, 0x30, 0x35, 0x34, 0x35
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2014, 03, 11, 06, 37, 00, -new TimeSpan(5, 45, 0));
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleOffsetWithHoursAndMinutesAndSeconds()
{
//20140311063701-0545
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x13, //with a length of 19
0x32, 0x30, 0x31, 0x34, 0x30, 0x33, 0x31,
0x31, 0x30, 0x36, 0x33, 0x37, 0x30, 0x31,
0x2d, 0x30, 0x35, 0x34, 0x35
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2014, 03, 11, 06, 37, 01, -new TimeSpan(5, 45, 0));
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[Fact]
public void ShouldDecodeSimpleOffsetWithHoursAndMinutesAndSecondsAndFractionalSeconds()
{
//20140311063701.999-0545
var data = new byte[]
{
0x18, //GeneralizedTime tag
0x17, //with a length of 23
0x32, 0x30, 0x31, 0x34, 0x30, 0x33, 0x31,
0x31, 0x30, 0x36, 0x33, 0x37, 0x30, 0x31,
0x2e, 0x39, 0x39, 0x39,
0x2d, 0x30, 0x35, 0x34, 0x35
};
var decoded = AsnDecoder.Decode(data);
var generalizedTime = Assert.IsType<AsnGeneralizedTime>(decoded);
var expectedDateTime = new DateTimeOffset(2014, 03, 11, 06, 37, 01, -new TimeSpan(5, 45, 0)).AddMilliseconds(999);
Assert.Equal(expectedDateTime, generalizedTime.Value);
}
[
Theory,
InlineData(new byte[] { 0x18, 0x00 }),
InlineData(new byte[] { 0x18, 0x0A, 0xFF, 0x30, 0x38, 0x30, 0x31, 0x32, 0x31, 0x30, 0x32, 0x33}),
InlineData(new byte[] { 0x18, 0x0A, 0x65, 0x30, 0x38, 0x30, 0x31, 0x32, 0x31, 0x30, 0x32, 0x33})
]
public void ShouldThrowOnInvalidInput(byte[] data)
{
Assert.Throws<AsnException>(() => AsnDecoder.Decode(data));
}
}
}
| |
//---------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Description: Shape element is a base class for shapes like Path,
// Rectangle, GlyphRun etc.
//
// History:
//
// 06/02/2003 : mleonov - created.
// 07/29/2004 : timothyc - Added ValidateValueCallback for enumeration
// properties
//
//---------------------------------------------------------------------------
using System.Diagnostics;
using System.Windows.Threading;
using System.Windows;
using System.Windows.Media;
using System.ComponentModel;
using MS.Internal;
using MS.Internal.PresentationFramework;
using System;
namespace System.Windows.Shapes
{
/// <summary>
/// Shape is a base class for shape elements
/// </summary>
[Localizability(LocalizationCategory.None, Readability=Readability.Unreadable)]
public abstract class Shape : FrameworkElement
{
#region Constructors
/// <summary>
/// Shape Constructor
/// </summary>
protected Shape()
{
}
#endregion
#region Properties
/// <summary>
/// DependencyProperty for the Stretch property.
/// </summary>
public static readonly DependencyProperty StretchProperty
= DependencyProperty.Register(
"Stretch", // Property name
typeof(Stretch), // Property type
typeof(Shape), // Property owner
new FrameworkPropertyMetadata(Stretch.None, FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsArrange));
/// <summary>
/// The Stretch property determines how the shape may be stretched to accommodate shape size
/// </summary>
public Stretch Stretch
{
get { return (Stretch)GetValue(StretchProperty); }
set { SetValue(StretchProperty, value); }
}
/// <summary>
/// The RenderedGeometry property returns the final rendered geometry
/// </summary>
public virtual Geometry RenderedGeometry
{
get
{
EnsureRenderedGeometry();
Geometry geometry = _renderedGeometry.CloneCurrentValue();
if (geometry == null || geometry == Geometry.Empty)
{
return Geometry.Empty;
}
// We need to return a frozen copy
if (Object.ReferenceEquals(geometry, _renderedGeometry))
{
// geometry is a reference to _renderedGeometry, so we need to copy
geometry = geometry.Clone();
geometry.Freeze();
}
return geometry;
}
}
/// <summary>
/// Return the transformation applied to the geometry before rendering
/// </summary>
public virtual Transform GeometryTransform
{
get
{
BoxedMatrix stretchMatrix = StretchMatrixField.GetValue(this);
if (stretchMatrix == null)
{
return Transform.Identity;
}
else
{
return new MatrixTransform(stretchMatrix.Value);
}
}
}
private static void OnPenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
// Called when any of the Stroke properties is invalidated.
// That means that the cached pen should be recalculated.
((Shape)d)._pen = null;
}
/// <summary>
/// Fill property
/// </summary>
[CommonDependencyProperty]
public static readonly DependencyProperty FillProperty =
DependencyProperty.Register(
"Fill",
typeof(Brush),
typeof(Shape),
new FrameworkPropertyMetadata(
(Brush) null,
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender));
/// <summary>
/// Fill property
/// </summary>
public Brush Fill
{
get { return (Brush) GetValue(FillProperty); }
set { SetValue(FillProperty, value); }
}
/// <summary>
/// Stroke property
/// </summary>
[CommonDependencyProperty]
public static readonly DependencyProperty StrokeProperty =
DependencyProperty.Register(
"Stroke",
typeof(Brush),
typeof(Shape),
new FrameworkPropertyMetadata(
(Brush) null,
FrameworkPropertyMetadataOptions.AffectsMeasure |
FrameworkPropertyMetadataOptions.AffectsRender |
FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender,
new PropertyChangedCallback(OnPenChanged)));
/// <summary>
/// Stroke property
/// </summary>
public Brush Stroke
{
get { return (Brush) GetValue(StrokeProperty); }
set { SetValue(StrokeProperty, value); }
}
/// <summary>
/// StrokeThickness property
/// </summary>
[CommonDependencyProperty]
public static readonly DependencyProperty StrokeThicknessProperty =
DependencyProperty.Register(
"StrokeThickness",
typeof(double),
typeof(Shape),
new FrameworkPropertyMetadata(
1.0d,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)));
/// <summary>
/// StrokeThickness property
/// </summary>
[TypeConverter(typeof(LengthConverter))]
public double StrokeThickness
{
get { return (double) GetValue(StrokeThicknessProperty); }
set { SetValue(StrokeThicknessProperty, value); }
}
/// <summary>
/// StrokeStartLineCap property
/// </summary>
public static readonly DependencyProperty StrokeStartLineCapProperty =
DependencyProperty.Register(
"StrokeStartLineCap",
typeof(PenLineCap),
typeof(Shape),
new FrameworkPropertyMetadata(
PenLineCap.Flat,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsPenLineCapValid));
/// <summary>
/// StrokeStartLineCap property
/// </summary>
public PenLineCap StrokeStartLineCap
{
get { return (PenLineCap) GetValue(StrokeStartLineCapProperty); }
set { SetValue(StrokeStartLineCapProperty, value); }
}
/// <summary>
/// StrokeEndLineCap property
/// </summary>
public static readonly DependencyProperty StrokeEndLineCapProperty =
DependencyProperty.Register(
"StrokeEndLineCap",
typeof(PenLineCap),
typeof(Shape),
new FrameworkPropertyMetadata(
PenLineCap.Flat,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsPenLineCapValid));
/// <summary>
/// StrokeEndLineCap property
/// </summary>
public PenLineCap StrokeEndLineCap
{
get { return (PenLineCap) GetValue(StrokeEndLineCapProperty); }
set { SetValue(StrokeEndLineCapProperty, value); }
}
/// <summary>
/// StrokeDashCap property
/// </summary>
public static readonly DependencyProperty StrokeDashCapProperty =
DependencyProperty.Register(
"StrokeDashCap",
typeof(PenLineCap),
typeof(Shape),
new FrameworkPropertyMetadata(
PenLineCap.Flat,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsPenLineCapValid));
/// <summary>
/// StrokeDashCap property
/// </summary>
public PenLineCap StrokeDashCap
{
get { return (PenLineCap) GetValue(StrokeDashCapProperty); }
set { SetValue(StrokeDashCapProperty, value); }
}
/// <summary>
/// StrokeLineJoin property
/// </summary>
public static readonly DependencyProperty StrokeLineJoinProperty =
DependencyProperty.Register(
"StrokeLineJoin",
typeof(PenLineJoin),
typeof(Shape),
new FrameworkPropertyMetadata(
PenLineJoin.Miter,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)),
new ValidateValueCallback(System.Windows.Media.ValidateEnums.IsPenLineJoinValid));
/// <summary>
/// StrokeLineJoin property
/// </summary>
public PenLineJoin StrokeLineJoin
{
get { return (PenLineJoin) GetValue(StrokeLineJoinProperty); }
set { SetValue(StrokeLineJoinProperty, value); }
}
/// <summary>
/// StrokeMiterLimit property
/// </summary>
public static readonly DependencyProperty StrokeMiterLimitProperty =
DependencyProperty.Register(
"StrokeMiterLimit",
typeof(double),
typeof(Shape),
new FrameworkPropertyMetadata(
10.0,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)));
/// <summary>
/// StrokeMiterLimit property
/// </summary>
public double StrokeMiterLimit
{
get { return (double) GetValue(StrokeMiterLimitProperty); }
set { SetValue(StrokeMiterLimitProperty, value); }
}
/// <summary>
/// StrokeDashOffset property
/// </summary>
public static readonly DependencyProperty StrokeDashOffsetProperty =
DependencyProperty.Register(
"StrokeDashOffset",
typeof(double),
typeof(Shape),
new FrameworkPropertyMetadata(
0.0,
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)));
/// <summary>
/// StrokeDashOffset property
/// </summary>
public double StrokeDashOffset
{
get { return (double) GetValue(StrokeDashOffsetProperty); }
set { SetValue(StrokeDashOffsetProperty, value); }
}
/// <summary>
/// StrokeDashArray property
/// </summary>
public static readonly DependencyProperty StrokeDashArrayProperty =
DependencyProperty.Register(
"StrokeDashArray",
typeof(DoubleCollection),
typeof(Shape),
new FrameworkPropertyMetadata(
new FreezableDefaultValueFactory(DoubleCollection.Empty),
FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender,
new PropertyChangedCallback(OnPenChanged)));
/// <summary>
/// StrokeDashArray property
/// </summary>
public DoubleCollection StrokeDashArray
{
get { return (DoubleCollection) GetValue(StrokeDashArrayProperty); }
set { SetValue(StrokeDashArrayProperty, value); }
}
#endregion
#region Protected Methods
/// <summary>
/// Updates DesiredSize of the shape. Called by parent UIElement during is the first pass of layout.
/// </summary>
/// <param name="constraint">Constraint size is an "upper limit" that should not exceed.</param>
/// <returns>Shape's desired size.</returns>
protected override Size MeasureOverride(Size constraint)
{
CacheDefiningGeometry();
Size newSize;
Stretch mode = Stretch;
if (mode == Stretch.None)
{
newSize = GetNaturalSize();
}
else
{
newSize = GetStretchedRenderSize(mode, GetStrokeThickness(), constraint, GetDefiningGeometryBounds());
}
if (SizeIsInvalidOrEmpty(newSize))
{
// We've encountered a numerical error. Don't draw anything.
newSize = new Size(0,0);
_renderedGeometry = Geometry.Empty;
}
return newSize;
}
/// <summary>
/// Compute the rendered geometry and the stretching transform.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
Size newSize;
Stretch mode = Stretch;
if (mode == Stretch.None)
{
StretchMatrixField.ClearValue(this);
ResetRenderedGeometry();
newSize = finalSize;
}
else
{
newSize = GetStretchedRenderSizeAndSetStretchMatrix(
mode, GetStrokeThickness(), finalSize, GetDefiningGeometryBounds());
}
if (SizeIsInvalidOrEmpty(newSize))
{
// We've encountered a numerical error. Don't draw anything.
newSize = new Size(0,0);
_renderedGeometry = Geometry.Empty;
}
return newSize;
}
/// <summary>
/// Render callback.
/// </summary>
protected override void OnRender(DrawingContext drawingContext)
{
EnsureRenderedGeometry();
if (_renderedGeometry != Geometry.Empty)
{
drawingContext.DrawGeometry(Fill, GetPen(), _renderedGeometry);
}
}
#endregion
#region Protected Properties
/// <summary>
/// Get the geometry that defines this shape
/// </summary>
protected abstract Geometry DefiningGeometry
{
get;
}
#endregion Protected Properties
#region Internal Methods
internal bool SizeIsInvalidOrEmpty(Size size)
{
return (DoubleUtil.IsNaN(size.Width) ||
DoubleUtil.IsNaN(size.Height) ||
size.IsEmpty);
}
internal bool IsPenNoOp
{
get
{
double strokeThickness = StrokeThickness;
return (Stroke == null) || DoubleUtil.IsNaN(strokeThickness) || DoubleUtil.IsZero(strokeThickness);
}
}
internal double GetStrokeThickness()
{
if (IsPenNoOp)
{
return 0;
}
else
{
return Math.Abs(StrokeThickness);
}
}
internal Pen GetPen()
{
if (IsPenNoOp)
{
return null;
}
if (_pen == null)
{
double thickness = 0.0;
double strokeThickness = StrokeThickness;
thickness = Math.Abs(strokeThickness);
// This pen is internal to the system and
// must not participate in freezable treeness
_pen = new Pen();
_pen.CanBeInheritanceContext = false;
_pen.Thickness = thickness;
_pen.Brush = Stroke;
_pen.StartLineCap = StrokeStartLineCap;
_pen.EndLineCap = StrokeEndLineCap;
_pen.DashCap = StrokeDashCap;
_pen.LineJoin = StrokeLineJoin;
_pen.MiterLimit = StrokeMiterLimit;
// StrokeDashArray is usually going to be its default value and GetValue
// on a mutable default has a per-instance cost associated with it so we'll
// try to avoid caching the default value
DoubleCollection strokeDashArray = null;
bool hasModifiers;
if (GetValueSource(StrokeDashArrayProperty, null, out hasModifiers)
!= BaseValueSourceInternal.Default || hasModifiers)
{
strokeDashArray = StrokeDashArray;
}
// Avoid creating the DashStyle if we can
double strokeDashOffset = StrokeDashOffset;
if (strokeDashArray != null || strokeDashOffset != 0.0)
{
_pen.DashStyle = new DashStyle(strokeDashArray, strokeDashOffset);
}
}
return _pen;
}
// Double verification helpers. Property system will verify type for us; we only need to verify the value.
internal static bool IsDoubleFiniteNonNegative(object o)
{
double d = (double)o;
return !(Double.IsInfinity(d) || DoubleUtil.IsNaN(d) || d < 0.0);
}
internal static bool IsDoubleFinite(object o)
{
double d = (double)o;
return !(Double.IsInfinity(d) || DoubleUtil.IsNaN(d));
}
internal static bool IsDoubleFiniteOrNaN(object o)
{
double d = (double)o;
return !(Double.IsInfinity(d));
}
internal virtual void CacheDefiningGeometry() {}
internal Size GetStretchedRenderSize(Stretch mode, double strokeThickness, Size availableSize, Rect geometryBounds)
{
double xScale, yScale, dX, dY;
Size renderSize;
GetStretchMetrics(mode, strokeThickness, availableSize, geometryBounds,
out xScale, out yScale, out dX, out dY, out renderSize);
return renderSize;
}
internal Size GetStretchedRenderSizeAndSetStretchMatrix(Stretch mode, double strokeThickness, Size availableSize, Rect geometryBounds)
{
double xScale, yScale, dX, dY;
Size renderSize;
GetStretchMetrics(mode, strokeThickness, availableSize, geometryBounds,
out xScale, out yScale, out dX, out dY, out renderSize);
// Construct the matrix
Matrix stretchMatrix = Matrix.Identity;
stretchMatrix.ScaleAt(xScale, yScale, geometryBounds.Location.X, geometryBounds.Location.Y);
stretchMatrix.Translate(dX, dY);
StretchMatrixField.SetValue(this, new BoxedMatrix(stretchMatrix));
ResetRenderedGeometry();
return renderSize;
}
internal void ResetRenderedGeometry()
{
// reset rendered geometry
_renderedGeometry = null;
}
internal void GetStretchMetrics(Stretch mode, double strokeThickness, Size availableSize, Rect geometryBounds,
out double xScale, out double yScale, out double dX, out double dY, out Size stretchedSize)
{
if (!geometryBounds.IsEmpty)
{
double margin = strokeThickness / 2;
bool hasThinDimension = false;
// Initialization for mode == Fill
xScale = Math.Max(availableSize.Width - strokeThickness, 0);
yScale = Math.Max(availableSize.Height - strokeThickness, 0);
dX = margin - geometryBounds.Left;
dY = margin - geometryBounds.Top;
// Compute the scale factors from the geometry to the size.
// The scale factors are ratios, and they have already been initialize to the numerators.
// To prevent fp overflow, we need to make sure that numerator / denomiator < limit;
// To do that without actually deviding, we check that denominator > numerator / limit.
// We take 1/epsilon as the limit, so the check is denominator > numerator * epsilon
// See Dev10 bug #453150.
// If the scale is infinite in both dimensions, return the natural size.
// If it's infinite in only one dimension, for non-fill stretch modes we constrain the size based
// on the unconstrained dimension.
// If our shape is "thin", i.e. a horizontal or vertical line, we can ignore non-fill stretches.
if (geometryBounds.Width > xScale * Double.Epsilon)
{
xScale /= geometryBounds.Width;
}
else
{
xScale = 1;
// We can ignore uniform and uniform-to-fill stretches if we have a vertical line.
if (geometryBounds.Width == 0)
{
hasThinDimension = true;
}
}
if (geometryBounds.Height > yScale * Double.Epsilon)
{
yScale /= geometryBounds.Height;
}
else
{
yScale = 1;
// We can ignore uniform and uniform-to-fill stretches if we have a horizontal line.
if (geometryBounds.Height == 0)
{
hasThinDimension = true;
}
}
// Because this case was handled by the caller
Debug.Assert(mode != Stretch.None);
// We are initialized for Fill, but for the other modes
// If one of our dimensions is thin, uniform stretches are
// meaningless, so we treat the stretch as fill.
if (mode != Stretch.Fill && !hasThinDimension)
{
if (mode == Stretch.Uniform)
{
if (yScale > xScale)
{
// Resize to fit the size's width
yScale = xScale;
}
else // if xScale >= yScale
{
// Resize to fit the size's height
xScale = yScale;
}
}
else
{
Debug.Assert(mode == Stretch.UniformToFill);
if (xScale > yScale)
{
// Resize to fill the size vertically, spilling out horizontally
yScale = xScale;
}
else // if yScale >= xScale
{
// Resize to fill the size horizontally, spilling out vertically
xScale = yScale;
}
}
}
stretchedSize = new Size(geometryBounds.Width * xScale + strokeThickness, geometryBounds.Height * yScale + strokeThickness);
}
else
{
xScale = yScale = 1;
dX = dY = 0;
stretchedSize = new Size(0,0);
}
}
/// <summary>
/// Get the natural size of the geometry that defines this shape
/// </summary>
internal virtual Size GetNaturalSize()
{
Geometry geometry = DefiningGeometry;
Debug.Assert(geometry != null);
//
// For the purposes of computing layout size, don't consider dashing. This will give us
// slightly different bounds, but the computation will be faster and more stable.
//
// NOTE: If GetPen() is ever made public, we will need to change this logic so the user
// isn't affected by our surreptitious change of DashStyle.
//
Pen pen = GetPen();
DashStyle style = null;
if (pen != null)
{
style = pen.DashStyle;
if (style != null)
{
pen.DashStyle = null;
}
}
Rect bounds = geometry.GetRenderBounds(pen);
if (style != null)
{
pen.DashStyle = style;
}
return new Size(Math.Max(bounds.Right, 0),
Math.Max(bounds.Bottom, 0));
}
/// <summary>
/// Get the bonds of the geometry that defines this shape
/// </summary>
internal virtual Rect GetDefiningGeometryBounds()
{
Geometry geometry = DefiningGeometry;
Debug.Assert(geometry != null);
return geometry.Bounds;
}
internal void EnsureRenderedGeometry()
{
if (_renderedGeometry == null)
{
_renderedGeometry = DefiningGeometry;
Debug.Assert(_renderedGeometry != null);
if (Stretch != Stretch.None)
{
Geometry currentValue = _renderedGeometry.CloneCurrentValue();
if (Object.ReferenceEquals(_renderedGeometry, currentValue))
{
_renderedGeometry = currentValue.Clone();
}
else
{
_renderedGeometry = currentValue;
}
Transform renderedTransform = _renderedGeometry.Transform;
BoxedMatrix boxedStretchMatrix = StretchMatrixField.GetValue(this);
Matrix stretchMatrix = (boxedStretchMatrix == null) ? Matrix.Identity : boxedStretchMatrix.Value;
if (renderedTransform == null || renderedTransform.IsIdentity)
{
_renderedGeometry.Transform = new MatrixTransform(stretchMatrix);
}
else
{
_renderedGeometry.Transform = new MatrixTransform(renderedTransform.Value * stretchMatrix);
}
}
}
}
#endregion Internal Methods
#region Private Fields
private Pen _pen = null;
private Geometry _renderedGeometry = Geometry.Empty;
private static UncommonField<BoxedMatrix> StretchMatrixField = new UncommonField<BoxedMatrix>(null);
#endregion Private Fields
}
internal class BoxedMatrix
{
public BoxedMatrix(Matrix value)
{
Value = value;
}
public Matrix Value;
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.WiFiDirect;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Security.Cryptography;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace SDKTemplate
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario1_Advertiser : Page
{
private MainPage rootPage = MainPage.Current;
private ObservableCollection<ConnectedDevice> ConnectedDevices = new ObservableCollection<ConnectedDevice>();
WiFiDirectAdvertisementPublisher _publisher;
WiFiDirectConnectionListener _listener;
List<WiFiDirectInformationElement> _informationElements = new List<WiFiDirectInformationElement>();
ConcurrentDictionary<StreamSocketListener, WiFiDirectDevice> _pendingConnections = new ConcurrentDictionary<StreamSocketListener, WiFiDirectDevice>();
public Scenario1_Advertiser()
{
this.InitializeComponent();
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
if (btnStopAdvertisement.IsEnabled)
{
StopAdvertisement();
}
}
private void btnStartAdvertisement_Click(object sender, RoutedEventArgs e)
{
_publisher = new WiFiDirectAdvertisementPublisher();
_publisher.StatusChanged += OnStatusChanged;
_listener = new WiFiDirectConnectionListener();
if (chkListener.IsChecked.Value)
{
try
{
// This can raise an exception if the machine does not support WiFi. Sorry.
_listener.ConnectionRequested += OnConnectionRequested;
}
catch (Exception ex)
{
rootPage.NotifyUser($"Error preparing Advertisement: {ex}", NotifyType.ErrorMessage);
return;
}
}
var discoverability = Utils.GetSelectedItemTag<WiFiDirectAdvertisementListenStateDiscoverability>(cmbListenState);
_publisher.Advertisement.ListenStateDiscoverability = discoverability;
_publisher.Advertisement.IsAutonomousGroupOwnerEnabled = chkPreferGroupOwnerMode.IsChecked.Value;
// Legacy settings are meaningful only if IsAutonomousGroupOwnerEnabled is true.
if (_publisher.Advertisement.IsAutonomousGroupOwnerEnabled && chkLegacySetting.IsChecked.Value)
{
_publisher.Advertisement.LegacySettings.IsEnabled = true;
if (!String.IsNullOrEmpty(txtPassphrase.Text))
{
var creds = new Windows.Security.Credentials.PasswordCredential();
creds.Password = txtPassphrase.Text;
_publisher.Advertisement.LegacySettings.Passphrase = creds;
}
if (!String.IsNullOrEmpty(txtSsid.Text))
{
_publisher.Advertisement.LegacySettings.Ssid = txtSsid.Text;
}
}
// Add the information elements.
foreach (WiFiDirectInformationElement informationElement in _informationElements)
{
_publisher.Advertisement.InformationElements.Add(informationElement);
}
_publisher.Start();
if (_publisher.Status == WiFiDirectAdvertisementPublisherStatus.Started)
{
btnStartAdvertisement.IsEnabled = false;
btnStopAdvertisement.IsEnabled = true;
rootPage.NotifyUser("Advertisement started.", NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser($"Advertisement failed to start. Status is {_publisher.Status}", NotifyType.ErrorMessage);
}
}
private void btnAddIe_Click(object sender, RoutedEventArgs e)
{
WiFiDirectInformationElement informationElement = new WiFiDirectInformationElement();
// Information element blob
DataWriter dataWriter = new DataWriter();
dataWriter.UnicodeEncoding = UnicodeEncoding.Utf8;
dataWriter.ByteOrder = ByteOrder.LittleEndian;
dataWriter.WriteUInt32(dataWriter.MeasureString(txtInformationElement.Text));
dataWriter.WriteString(txtInformationElement.Text);
informationElement.Value = dataWriter.DetachBuffer();
// Organizational unit identifier (OUI)
informationElement.Oui = CryptographicBuffer.CreateFromByteArray(Globals.CustomOui);
// OUI Type
informationElement.OuiType = Globals.CustomOuiType;
// Save this information element so we can add it when we advertise.
_informationElements.Add(informationElement);
txtInformationElement.Text = "";
rootPage.NotifyUser("IE added successfully", NotifyType.StatusMessage);
}
private void btnStopAdvertisement_Click(object sender, RoutedEventArgs e)
{
StopAdvertisement();
rootPage.NotifyUser("Advertisement stopped successfully", NotifyType.StatusMessage);
}
private void StopAdvertisement()
{
_publisher.Stop();
_publisher.StatusChanged -= OnStatusChanged;
_listener.ConnectionRequested -= OnConnectionRequested;
connectionSettingsPanel.Reset();
_informationElements.Clear();
btnStartAdvertisement.IsEnabled = true;
btnStopAdvertisement.IsEnabled = false;
}
private async Task<bool> HandleConnectionRequestAsync(WiFiDirectConnectionRequest connectionRequest)
{
string deviceName = connectionRequest.DeviceInformation.Name;
bool isPaired = (connectionRequest.DeviceInformation.Pairing?.IsPaired == true) ||
(await IsAepPairedAsync(connectionRequest.DeviceInformation.Id));
// Show the prompt only in case of WiFiDirect reconnection or Legacy client connection.
if (isPaired || _publisher.Advertisement.LegacySettings.IsEnabled)
{
var messageDialog = new MessageDialog($"Connection request received from {deviceName}", "Connection Request");
// Add two commands, distinguished by their tag.
// The default command is "Decline", and if the user cancels, we treat it as "Decline".
messageDialog.Commands.Add(new UICommand("Accept", null, true));
messageDialog.Commands.Add(new UICommand("Decline", null, null));
messageDialog.DefaultCommandIndex = 1;
messageDialog.CancelCommandIndex = 1;
// Show the message dialog
var commandChosen = await messageDialog.ShowAsync();
if (commandChosen.Id == null)
{
return false;
}
}
rootPage.NotifyUser($"Connecting to {deviceName}...", NotifyType.StatusMessage);
// Pair device if not already paired and not using legacy settings
if (!isPaired && !_publisher.Advertisement.LegacySettings.IsEnabled)
{
if (!await connectionSettingsPanel.RequestPairDeviceAsync(connectionRequest.DeviceInformation.Pairing))
{
return false;
}
}
WiFiDirectDevice wfdDevice = null;
try
{
// IMPORTANT: FromIdAsync needs to be called from the UI thread
wfdDevice = await WiFiDirectDevice.FromIdAsync(connectionRequest.DeviceInformation.Id);
}
catch (Exception ex)
{
rootPage.NotifyUser($"Exception in FromIdAsync: {ex}", NotifyType.ErrorMessage);
return false;
}
// Register for the ConnectionStatusChanged event handler
wfdDevice.ConnectionStatusChanged += OnConnectionStatusChanged;
var listenerSocket = new StreamSocketListener();
// Save this (listenerSocket, wfdDevice) pair so we can hook it up when the socket connection is made.
_pendingConnections[listenerSocket] = wfdDevice;
var EndpointPairs = wfdDevice.GetConnectionEndpointPairs();
listenerSocket.ConnectionReceived += OnSocketConnectionReceived;
try
{
await listenerSocket.BindEndpointAsync(EndpointPairs[0].LocalHostName, Globals.strServerPort);
}
catch (Exception ex)
{
rootPage.NotifyUser($"Connect operation threw an exception: {ex.Message}", NotifyType.ErrorMessage);
return false;
}
rootPage.NotifyUser($"Devices connected on L2, listening on IP Address: {EndpointPairs[0].LocalHostName}" +
$" Port: {Globals.strServerPort}", NotifyType.StatusMessage);
return true;
}
private async void OnConnectionRequested(WiFiDirectConnectionListener sender, WiFiDirectConnectionRequestedEventArgs connectionEventArgs)
{
WiFiDirectConnectionRequest connectionRequest = connectionEventArgs.GetConnectionRequest();
bool success = await Dispatcher.RunTaskAsync(async () =>
{
return await HandleConnectionRequestAsync(connectionRequest);
});
if (!success)
{
// Decline the connection request
rootPage.NotifyUserFromBackground($"Connection request from {connectionRequest.DeviceInformation.Name} was declined", NotifyType.ErrorMessage);
connectionRequest.Dispose();
}
}
private async Task<bool> IsAepPairedAsync(string deviceId)
{
List<string> additionalProperties = new List<string>();
additionalProperties.Add("System.Devices.Aep.DeviceAddress");
String deviceSelector = $"System.Devices.Aep.AepId:=\"{deviceId}\"";
DeviceInformation devInfo = null;
try
{
devInfo = await DeviceInformation.CreateFromIdAsync(deviceId, additionalProperties);
}
catch (Exception ex)
{
rootPage.NotifyUser("DeviceInformation.CreateFromIdAsync threw an exception: " + ex.Message, NotifyType.ErrorMessage);
}
if (devInfo == null)
{
rootPage.NotifyUser("Device Information is null", NotifyType.ErrorMessage);
return false;
}
deviceSelector = $"System.Devices.Aep.DeviceAddress:=\"{devInfo.Properties["System.Devices.Aep.DeviceAddress"]}\"";
DeviceInformationCollection pairedDeviceCollection = await DeviceInformation.FindAllAsync(deviceSelector, null, DeviceInformationKind.Device);
return pairedDeviceCollection.Count > 0;
}
private async void OnStatusChanged(WiFiDirectAdvertisementPublisher sender, WiFiDirectAdvertisementPublisherStatusChangedEventArgs statusEventArgs)
{
if (statusEventArgs.Status == WiFiDirectAdvertisementPublisherStatus.Started)
{
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
if (sender.Advertisement.LegacySettings.IsEnabled)
{
// Show the autogenerated passphrase and SSID.
if (String.IsNullOrEmpty(txtPassphrase.Text))
{
txtPassphrase.Text = _publisher.Advertisement.LegacySettings.Passphrase.Password;
}
if (String.IsNullOrEmpty(txtSsid.Text))
{
txtSsid.Text = _publisher.Advertisement.LegacySettings.Ssid;
}
}
});
}
rootPage.NotifyUserFromBackground($"Advertisement: Status: {statusEventArgs.Status}, Error: {statusEventArgs.Error}", NotifyType.StatusMessage);
return;
}
private void OnSocketConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
{
rootPage.NotifyUser("Connecting to remote side on L4 layer...", NotifyType.StatusMessage);
StreamSocket serverSocket = args.Socket;
// Look up the WiFiDirectDevice associated with this StreamSocketListener.
WiFiDirectDevice wfdDevice;
if (!_pendingConnections.TryRemove(sender, out wfdDevice))
{
rootPage.NotifyUser("Unexpected connection ignored.", NotifyType.ErrorMessage);
serverSocket.Dispose();
return;
}
SocketReaderWriter socketRW = new SocketReaderWriter(serverSocket, rootPage);
// The first message sent is the name of the connection.
string message = await socketRW.ReadMessageAsync();
// Add this connection to the list of active connections.
ConnectedDevices.Add(new ConnectedDevice(message ?? "(unnamed)", wfdDevice, socketRW));
while (message != null)
{
message = await socketRW.ReadMessageAsync();
}
});
}
private void OnConnectionStatusChanged(WiFiDirectDevice sender, object arg)
{
rootPage.NotifyUserFromBackground($"Connection status changed: {sender.ConnectionStatus}", NotifyType.StatusMessage);
if (sender.ConnectionStatus == WiFiDirectConnectionStatus.Disconnected)
{
// TODO: Should we remove this connection from the list?
// (Yes, probably.)
}
}
private async void btnSendMessage_Click(object sender, RoutedEventArgs e)
{
var connectedDevice = (ConnectedDevice)lvConnectedDevices.SelectedItem;
await connectedDevice.SocketRW.WriteMessageAsync(txtSendMessage.Text);
}
private void btnCloseDevice_Click(object sender, RoutedEventArgs e)
{
var connectedDevice = (ConnectedDevice)lvConnectedDevices.SelectedItem;
ConnectedDevices.Remove(connectedDevice);
// Close socket and WiFiDirect object
connectedDevice.Dispose();
}
}
}
| |
using UnityEngine;
using System.Collections;
namespace Uzu
{
/// <summary>
/// Configuration for an audio controller.
/// </summary>
public struct AudioControllerConfig
{
/// <summary>
/// The max # of audio sources that this controller can handle.
/// </summary>
public int AudioSourceMaxCount { get; set; }
/// <summary>
/// Reference to the loader used to load this controller's audio clips.
/// </summary>
public AudioLoader AudioLoader { get; set; }
}
/// <summary>
/// Handles playing of audio.
/// </summary>
public class AudioController : MonoBehaviour
{
/// <summary>
/// Options passed when playing a sound.
/// </summary>
public struct PlayOptions
{
public bool Loop;
public Vector3 Position;
public float Volume;
public float FadeInTime;
}
/// <summary>
/// Initializes the audio controller.
/// </summary>
public void Initialize (AudioControllerConfig config)
{
// AudioSource allocation.
{
int maxCount = Mathf.Max (1, config.AudioSourceMaxCount);
_availableSources = new FixedList<AudioSource> (maxCount);
_availableSourceInfoIndices = new FixedList<int> (maxCount);
_activeSourceInfoIndices = new FixedList<int> (maxCount);
_sourceInfos = new FixedList<AudioSourceInfo> (maxCount);
for (int i = 0; i < maxCount; i++) {
GameObject go = new GameObject ("AudioSource_" + i);
Transform xform = go.transform;
xform.parent = this.transform;
AudioSource audioSource = go.AddComponent<AudioSource> ();
ReturnSourceToPool (audioSource);
_availableSourceInfoIndices.Add (i);
_sourceInfos.Add (new AudioSourceInfo ());
}
}
_audioLoader = config.AudioLoader;
if (_audioLoader == null) {
Debug.LogError ("AudioLoader not set!");
}
}
/// <summary>
/// Gets the # of available audio sources remaining.
/// </summary>
public int GetAvailableSourceCount ()
{
return _availableSources.Count;
}
public bool IsHandleValid (AudioHandle handle)
{
return GetSourceInfo (handle) != null;
}
/// <summary>
/// Mute.
/// </summary>
public bool IsMuted {
get { return _isMuted; }
set { _isMuted = value; }
}
public AudioHandle Play (string clipId, PlayOptions options)
{
AudioClip clip = GetClip (clipId);
if (clip != null) {
AudioHandle handle = GetSource ();
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
AudioSource source = sourceInfo.Source;
source.clip = clip;
source.loop = options.Loop;
source.transform.localPosition = options.Position;
sourceInfo.ClipId = clipId;
sourceInfo.TargetVolume = options.Volume;
if (options.FadeInTime > 0.0f &&
!_isMuted) {
sourceInfo.VolumeFluctuationSpeed = sourceInfo.TargetVolume / options.FadeInTime;
source.volume = 0.0f;
}
else {
SetSourceVolume (sourceInfo, sourceInfo.TargetVolume);
}
source.Play ();
handle._handle_audio_source = source;
}
return handle;
}
return new AudioHandle ();
}
public bool IsPlaying (AudioHandle handle)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
return sourceInfo.Source.isPlaying;
}
return false;
}
public void Stop (AudioHandle handle)
{
Stop (handle, 0.0f);
}
public void Stop (AudioHandle handle, float fadeOutTime)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
if (fadeOutTime > 0.0f &&
!_isMuted) {
sourceInfo.VolumeFluctuationSpeed = -sourceInfo.Source.volume / fadeOutTime;
sourceInfo.TargetVolume = 0.0f;
}
else {
sourceInfo.Source.Stop ();
}
}
}
public void StopAll ()
{
for (int i = 0; i < _activeSourceInfoIndices.Count; i++) {
AudioSourceInfo sourceInfo = _sourceInfos [_activeSourceInfoIndices [i]];
sourceInfo.Source.Stop ();
}
}
public string GetClipId (AudioHandle handle)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
return sourceInfo.ClipId;
}
return string.Empty;
}
public void SetVolume (AudioHandle handle, float volume)
{
SetVolume (handle, volume, 0.0f);
}
public void SetVolume (AudioHandle handle, float volume, float duration)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
if (duration > 0.0f &&
!_isMuted) {
float deltaVolume = volume - sourceInfo.Source.volume;
sourceInfo.VolumeFluctuationSpeed = deltaVolume / duration;
sourceInfo.TargetVolume = volume;
}
else {
SetSourceVolume (sourceInfo, volume);
}
}
}
public float GetVolume (AudioHandle handle)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
return sourceInfo.Source.volume;
}
return 0.0f;
}
public void SetPitch (AudioHandle handle, float pitch)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
sourceInfo.Source.pitch = pitch;
}
}
public float GetPitch (AudioHandle handle)
{
AudioSourceInfo sourceInfo = GetSourceInfo (handle);
if (sourceInfo != null) {
return sourceInfo.Source.pitch;
}
return 1.0f;
}
#region Implementation.
private AudioLoader _audioLoader;
private FixedList<AudioSource> _availableSources;
private FixedList<int> _availableSourceInfoIndices;
private FixedList<int> _activeSourceInfoIndices;
private FixedList<AudioSourceInfo> _sourceInfos;
private bool _isMuted;
private bool _wasMuted;
private class AudioSourceInfo
{
/// <summary>
/// Unique identifier used to reverse-lookup this source info
/// to make sure it is actually valid.
/// </summary>
public int HandleId;
/// <summary>
/// The clipId used to create this source.
/// </summary>
public string ClipId;
/// <summary>
/// The AudioSource that this info is referring to.
/// </summary>
public AudioSource Source;
/// <summary>
/// The maximum volume this sound can reach.
/// </summary>
public float TargetVolume;
/// <summary>
/// Rate of change of volume during fade effects.
/// </summary>
public float VolumeFluctuationSpeed;
public AudioSourceInfo ()
{
Reset ();
}
public void Reset ()
{
HandleId = AudioHandle.INVALID_ID;
ClipId = string.Empty;
Source = null;
VolumeFluctuationSpeed = 0.0f;
TargetVolume = 1.0f;
}
}
#region Unique id generation.
/// <summary>
/// Handle counter.
/// Start from 1 since 0 is an invalid id.
/// </summary>
private int HANDLE_ID_CNT = 1;
private int CreateHandleId ()
{
// GUID could also be used, but this seems fine for now.
return HANDLE_ID_CNT++;
}
#endregion
private void SetSourceVolume (AudioSourceInfo sourceInfo, float volume)
{
if (_isMuted) {
sourceInfo.Source.volume = 0.0f;
}
else {
sourceInfo.Source.volume = volume;
}
sourceInfo.TargetVolume = volume;
}
private AudioClip GetClip (string clipId)
{
if (_audioLoader == null) {
Debug.LogWarning ("AudioLoader not registered.");
return null;
}
AudioClip clip = _audioLoader.GetClip (clipId);
if (clip == null) {
Debug.LogWarning ("AudioClip id [" + clipId + "] not found.");
}
return clip;
}
private AudioHandle GetSource ()
{
if (_availableSourceInfoIndices.Count > 0) {
int index = _availableSourceInfoIndices.Count - 1;
// Get a source.
AudioSource source = GetSourceFromPool (index);
// Get a source info index.
int infoIndex = _availableSourceInfoIndices [index];
_availableSourceInfoIndices.RemoveAt (index);
_activeSourceInfoIndices.Add (infoIndex);
// Set up the source info.
AudioSourceInfo sourceInfo = _sourceInfos [infoIndex];
Uzu.Dbg.Assert (sourceInfo.Source == null);
sourceInfo.Source = source;
Uzu.Dbg.Assert (sourceInfo.Source != null);
int handleId = CreateHandleId ();
sourceInfo.HandleId = handleId;
return new AudioHandle (handleId, infoIndex);
}
Debug.LogWarning ("No AudioSources available.");
return new AudioHandle ();
}
private AudioSourceInfo GetSourceInfo (AudioHandle handle)
{
if (handle.Id != AudioHandle.INVALID_ID) {
AudioSourceInfo sourceInfo = _sourceInfos [handle.Index];
// Verify handle integrity.
if (sourceInfo.HandleId == handle.Id) {
return sourceInfo;
}
}
return null;
}
private AudioSource GetSourceFromPool (int index)
{
AudioSource source = _availableSources [index];
_availableSources.RemoveAt (index);
source.gameObject.SetActive (true);
return source;
}
private void ReturnSourceToPool (AudioSource source)
{
source.gameObject.SetActive (false);
_availableSources.Add (source);
}
private bool _isPaused = false;
private void OnApplicationPause(bool isPaused)
{
// Shyam Memo (2014.09.18):
// Fix for issue introduced in Unity 4.5.4 where one extra frame
// is executed after applicationWillResignActive event and
// before applicationDidEnterBackground event. Since one extra
// frame executes, the Update method of the AudioController is cleaning
// up all the sounds.
//
// To fix this, we pause the AudioController in OnApplicationPause (which
// is called immediately after applicationWillResignActive, but
// before the next frame is executed), and skip updating of the
// AudioController for this extra frame. When the app resumes,
// _isPaused becomes false, and the controller continues its updates.
_isPaused = isPaused;
}
private void Update ()
{
// Don't update if system is paused.
if (_isPaused) {
return;
}
// Fade in / out processing.
{
for (int i = 0; i < _activeSourceInfoIndices.Count; i++) {
AudioSourceInfo sourceInfo = _sourceInfos [_activeSourceInfoIndices [i]];
// No change in volume - skip.
if (Mathf.Approximately (sourceInfo.VolumeFluctuationSpeed, 0.0f)) {
continue;
}
AudioSource source = sourceInfo.Source;
float deltaVolume = sourceInfo.VolumeFluctuationSpeed * Time.deltaTime;
float newVolume = source.volume + deltaVolume;
// Increasing volume (fade in).
if (sourceInfo.VolumeFluctuationSpeed > 0.0f) {
if (newVolume >= sourceInfo.TargetVolume) {
source.volume = sourceInfo.TargetVolume;
sourceInfo.VolumeFluctuationSpeed = 0.0f;
}
else {
source.volume = newVolume;
}
}
// Decreasing volume (fade out).
else {
if (newVolume <= sourceInfo.TargetVolume) {
source.volume = sourceInfo.TargetVolume;
sourceInfo.VolumeFluctuationSpeed = 0.0f;
if (Mathf.Approximately(source.volume, 0.0f)) {
source.Stop ();
}
}
else {
source.volume = newVolume;
}
}
}
}
// Clean up finished sounds.
{
for (int i = 0; i < _activeSourceInfoIndices.Count; /*i++*/) {
int sourceInfoIndex = _activeSourceInfoIndices [i];
AudioSourceInfo sourceInfo = _sourceInfos [sourceInfoIndex];
AudioSource source = sourceInfo.Source;
if (!source.isPlaying) {
// Reset state.
sourceInfo.Reset ();
// Remove from active pool.
{
// Move last element to avoid array copy.
int lastIndex = _activeSourceInfoIndices.Count - 1;
_activeSourceInfoIndices [i] = _activeSourceInfoIndices [lastIndex];
_activeSourceInfoIndices.RemoveAt (lastIndex);
}
// Add back to available pools.
_availableSourceInfoIndices.Add (sourceInfoIndex);
ReturnSourceToPool (source);
Uzu.Dbg.Assert (_availableSourceInfoIndices.Count == _availableSources.Count);
continue;
}
i++;
}
}
// Mute processing.
{
// Was there a change?
if (_isMuted != _wasMuted) {
if (_isMuted) {
// Mute all active sources.
for (int i = 0; i < _activeSourceInfoIndices.Count; i++) {
AudioSourceInfo sourceInfo = _sourceInfos [_activeSourceInfoIndices [i]];
sourceInfo.Source.volume = 0.0f;
}
}
else {
// Unmute all active sources.
for (int i = 0; i < _activeSourceInfoIndices.Count; i++) {
AudioSourceInfo sourceInfo = _sourceInfos [_activeSourceInfoIndices [i]];
sourceInfo.Source.volume = sourceInfo.TargetVolume;
}
}
}
_wasMuted = _isMuted;
}
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Threading.Tasks;
namespace System.Threading
{
public delegate void TimerCallback(object state);
// TimerQueue maintains a list of active timers. We use a single native timer to schedule all managed timers
// in the process.
//
// Perf assumptions: We assume that timers are created and destroyed frequently, but rarely actually fire.
// There are roughly two types of timer:
//
// - timeouts for operations. These are created and destroyed very frequently, but almost never fire, because
// the whole point is that the timer only fires if something has gone wrong.
//
// - scheduled background tasks. These typically do fire, but they usually have quite long durations.
// So the impact of spending a few extra cycles to fire these is negligible.
//
// Because of this, we want to choose a data structure with very fast insert and delete times, and we can live
// with linear traversal times when firing timers. However, we still want to minimize the number of timers
// we need to traverse while doing the linear walk: in cases where we have lots of long-lived timers as well as
// lots of short-lived timers, when the short-lived timers fire, they incur the cost of walking the long-lived ones.
//
// The data structure we've chosen is an unordered doubly-linked list of active timers. This gives O(1) insertion
// and removal, and O(N) traversal when finding expired timers. We maintain two such lists: one for all of the
// timers that'll next fire within a certain threshold, and one for the rest.
//
// Note that all instance methods of this class require that the caller hold a lock on the TimerQueue instance.
// We partition the timers across multiple TimerQueues, each with its own lock and set of short/long lists,
// in order to minimize contention when lots of threads are concurrently creating and destroying timers often.
internal partial class TimerQueue
{
#region Shared TimerQueue instances
public static TimerQueue[] Instances { get; } = CreateTimerQueues();
private static TimerQueue[] CreateTimerQueues()
{
var queues = new TimerQueue[Environment.ProcessorCount];
for (int i = 0; i < queues.Length; i++)
{
queues[i] = new TimerQueue(i);
}
return queues;
}
#endregion
#region interface to native timer
private bool _isTimerScheduled;
private int _currentTimerStartTicks;
private uint _currentTimerDuration;
private bool EnsureTimerFiresBy(uint requestedDuration)
{
// The VM's timer implementation does not work well for very long-duration timers.
// See kb 950807.
// So we'll limit our native timer duration to a "small" value.
// This may cause us to attempt to fire timers early, but that's ok -
// we'll just see that none of our timers has actually reached its due time,
// and schedule the native timer again.
const uint maxPossibleDuration = 0x0fffffff;
uint actualDuration = Math.Min(requestedDuration, maxPossibleDuration);
if (_isTimerScheduled)
{
uint elapsed = (uint)(TickCount - _currentTimerStartTicks);
if (elapsed >= _currentTimerDuration)
return true; //the timer's about to fire
uint remainingDuration = _currentTimerDuration - elapsed;
if (actualDuration >= remainingDuration)
return true; //the timer will fire earlier than this request
}
// If Pause is underway then do not schedule the timers
// A later update during resume will re-schedule
if (_pauseTicks != 0)
{
Debug.Assert(!_isTimerScheduled);
return true;
}
if (SetTimer(actualDuration))
{
_isTimerScheduled = true;
_currentTimerStartTicks = TickCount;
_currentTimerDuration = actualDuration;
return true;
}
return false;
}
#endregion
#region Firing timers
// The two lists of timers that are part of this TimerQueue. They conform to a single guarantee:
// no timer in _longTimers has an absolute next firing time <= _currentAbsoluteThreshold.
// That way, when FireNextTimers is invoked, we always process the short list, and we then only
// process the long list if the current time is greater than _currentAbsoluteThreshold (or
// if the short list is now empty and we need to process the long list to know when to next
// invoke FireNextTimers).
private TimerQueueTimer _shortTimers;
private TimerQueueTimer _longTimers;
// The current threshold, an absolute time where any timers scheduled to go off at or
// before this time must be queued to the short list.
private int _currentAbsoluteThreshold = ShortTimersThresholdMilliseconds;
// Default threshold that separates which timers target _shortTimers vs _longTimers. The threshold
// is chosen to balance the number of timers in the small list against the frequency with which
// we need to scan the long list. It's thus somewhat arbitrary and could be changed based on
// observed workload demand. The larger the number, the more timers we'll likely need to enumerate
// every time the timer fires, but also the more likely it is that when it does we won't
// need to look at the long list because the current time will be <= _currentAbsoluteThreshold.
private const int ShortTimersThresholdMilliseconds = 333;
// Time when Pause was called
private volatile int _pauseTicks = 0;
// Fire any timers that have expired, and update the native timer to schedule the rest of them.
// We're in a thread pool work item here, and if there are multiple timers to be fired, we want
// to queue all but the first one. The first may can then be invoked synchronously or queued,
// a task left up to our caller, which might be firing timers from multiple queues.
private void FireNextTimers()
{
// We fire the first timer on this thread; any other timers that need to be fired
// are queued to the ThreadPool.
TimerQueueTimer timerToFireOnThisThread = null;
lock (this)
{
// Since we got here, that means our previous timer has fired.
_isTimerScheduled = false;
bool haveTimerToSchedule = false;
uint nextTimerDuration = uint.MaxValue;
int nowTicks = TickCount;
// Sweep through the "short" timers. If the current tick count is greater than
// the current threshold, also sweep through the "long" timers. Finally, as part
// of sweeping the long timers, move anything that'll fire within the next threshold
// to the short list. It's functionally ok if more timers end up in the short list
// than is truly necessary (but not the opposite).
TimerQueueTimer timer = _shortTimers;
for (int listNum = 0; listNum < 2; listNum++) // short == 0, long == 1
{
while (timer != null)
{
Debug.Assert(timer._dueTime != Timeout.UnsignedInfinite, "A timer in the list must have a valid due time.");
// Save off the next timer to examine, in case our examination of this timer results
// in our deleting or moving it; we'll continue after with this saved next timer.
TimerQueueTimer next = timer._next;
uint elapsed = (uint)(nowTicks - timer._startTicks);
int remaining = (int)timer._dueTime - (int)elapsed;
if (remaining <= 0)
{
// Timer is ready to fire.
if (timer._period != Timeout.UnsignedInfinite)
{
// This is a repeating timer; schedule it to run again.
// Discount the extra amount of time that has elapsed since the previous firing time to
// prevent timer ticks from drifting. If enough time has already elapsed for the timer to fire
// again, meaning the timer can't keep up with the short period, have it fire 1 ms from now to
// avoid spinning without a delay.
timer._startTicks = nowTicks;
uint elapsedForNextDueTime = elapsed - timer._dueTime;
timer._dueTime = (elapsedForNextDueTime < timer._period) ?
timer._period - elapsedForNextDueTime :
1;
// Update the timer if this becomes the next timer to fire.
if (timer._dueTime < nextTimerDuration)
{
haveTimerToSchedule = true;
nextTimerDuration = timer._dueTime;
}
// Validate that the repeating timer is still on the right list. It's likely that
// it started in the long list and was moved to the short list at some point, so
// we now want to move it back to the long list if that's where it belongs. Note that
// if we're currently processing the short list and move it to the long list, we may
// end up revisiting it again if we also enumerate the long list, but we will have already
// updated the due time appropriately so that we won't fire it again (it's also possible
// but rare that we could be moving a timer from the long list to the short list here,
// if the initial due time was set to be long but the timer then had a short period).
bool targetShortList = (nowTicks + timer._dueTime) - _currentAbsoluteThreshold <= 0;
if (timer._short != targetShortList)
{
MoveTimerToCorrectList(timer, targetShortList);
}
}
else
{
// Not repeating; remove it from the queue
DeleteTimer(timer);
}
// If this is the first timer, we'll fire it on this thread (after processing
// all others). Otherwise, queue it to the ThreadPool.
if (timerToFireOnThisThread == null)
{
timerToFireOnThisThread = timer;
}
else
{
ThreadPool.UnsafeQueueUserWorkItemInternal(timer, preferLocal: false);
}
}
else
{
// This timer isn't ready to fire. Update the next time the native timer fires if necessary,
// and move this timer to the short list if its remaining time is now at or under the threshold.
if (remaining < nextTimerDuration)
{
haveTimerToSchedule = true;
nextTimerDuration = (uint)remaining;
}
if (!timer._short && remaining <= ShortTimersThresholdMilliseconds)
{
MoveTimerToCorrectList(timer, shortList: true);
}
}
timer = next;
}
// Switch to process the long list if necessary.
if (listNum == 0)
{
// Determine how much time remains between now and the current threshold. If time remains,
// we can skip processing the long list. We use > rather than >= because, although we
// know that if remaining == 0 no timers in the long list will need to be fired, we
// don't know without looking at them when we'll need to call FireNextTimers again. We
// could in that case just set the next firing to 1, but we may as well just iterate the
// long list now; otherwise, most timers created in the interim would end up in the long
// list and we'd likely end up paying for another invocation of FireNextTimers that could
// have been delayed longer (to whatever is the current minimum in the long list).
int remaining = _currentAbsoluteThreshold - nowTicks;
if (remaining > 0)
{
if (_shortTimers == null && _longTimers != null)
{
// We don't have any short timers left and we haven't examined the long list,
// which means we likely don't have an accurate nextTimerDuration.
// But we do know that nothing in the long list will be firing before or at _currentAbsoluteThreshold,
// so we can just set nextTimerDuration to the difference between then and now.
nextTimerDuration = (uint)remaining + 1;
haveTimerToSchedule = true;
}
break;
}
// Switch to processing the long list.
timer = _longTimers;
// Now that we're going to process the long list, update the current threshold.
_currentAbsoluteThreshold = nowTicks + ShortTimersThresholdMilliseconds;
}
}
// If we still have scheduled timers, update the timer to ensure it fires
// in time for the next one in line.
if (haveTimerToSchedule)
{
EnsureTimerFiresBy(nextTimerDuration);
}
}
// Fire the user timer outside of the lock!
timerToFireOnThisThread?.Fire();
}
#endregion
#region Queue implementation
public bool UpdateTimer(TimerQueueTimer timer, uint dueTime, uint period)
{
int nowTicks = TickCount;
// The timer can be put onto the short list if it's next absolute firing time
// is <= the current absolute threshold.
int absoluteDueTime = (int)(nowTicks + dueTime);
bool shouldBeShort = _currentAbsoluteThreshold - absoluteDueTime >= 0;
if (timer._dueTime == Timeout.UnsignedInfinite)
{
// If the timer wasn't previously scheduled, now add it to the right list.
timer._short = shouldBeShort;
LinkTimer(timer);
}
else if (timer._short != shouldBeShort)
{
// If the timer was previously scheduled, but this update should cause
// it to move over the list threshold in either direction, do so.
UnlinkTimer(timer);
timer._short = shouldBeShort;
LinkTimer(timer);
}
timer._dueTime = dueTime;
timer._period = (period == 0) ? Timeout.UnsignedInfinite : period;
timer._startTicks = nowTicks;
return EnsureTimerFiresBy(dueTime);
}
public void MoveTimerToCorrectList(TimerQueueTimer timer, bool shortList)
{
Debug.Assert(timer._dueTime != Timeout.UnsignedInfinite, "Expected timer to be on a list.");
Debug.Assert(timer._short != shortList, "Unnecessary if timer is already on the right list.");
// Unlink it from whatever list it's on, change its list association, then re-link it.
UnlinkTimer(timer);
timer._short = shortList;
LinkTimer(timer);
}
private void LinkTimer(TimerQueueTimer timer)
{
// Use timer._short to decide to which list to add.
ref TimerQueueTimer listHead = ref timer._short ? ref _shortTimers : ref _longTimers;
timer._next = listHead;
if (timer._next != null)
{
timer._next._prev = timer;
}
timer._prev = null;
listHead = timer;
}
private void UnlinkTimer(TimerQueueTimer timer)
{
TimerQueueTimer t = timer._next;
if (t != null)
{
t._prev = timer._prev;
}
if (_shortTimers == timer)
{
Debug.Assert(timer._short);
_shortTimers = t;
}
else if (_longTimers == timer)
{
Debug.Assert(!timer._short);
_longTimers = t;
}
t = timer._prev;
if (t != null)
{
t._next = timer._next;
}
// At this point the timer is no longer in a list, but its next and prev
// references may still point to other nodes. UnlinkTimer should thus be
// followed by something that overwrites those references, either with null
// if deleting the timer or other nodes if adding it to another list.
}
public void DeleteTimer(TimerQueueTimer timer)
{
if (timer._dueTime != Timeout.UnsignedInfinite)
{
UnlinkTimer(timer);
timer._prev = null;
timer._next = null;
timer._dueTime = Timeout.UnsignedInfinite;
timer._period = Timeout.UnsignedInfinite;
timer._startTicks = 0;
timer._short = false;
}
}
#endregion
}
// A timer in our TimerQueue.
internal sealed partial class TimerQueueTimer : IThreadPoolWorkItem
{
// The associated timer queue.
private readonly TimerQueue _associatedTimerQueue;
// All mutable fields of this class are protected by a lock on _associatedTimerQueue.
// The first six fields are maintained by TimerQueue.
// Links to the next and prev timers in the list.
internal TimerQueueTimer _next;
internal TimerQueueTimer _prev;
// true if on the short list; otherwise, false.
internal bool _short;
// The time, according to TimerQueue.TickCount, when this timer's current interval started.
internal int _startTicks;
// Timeout.UnsignedInfinite if we are not going to fire. Otherwise, the offset from _startTime when we will fire.
internal uint _dueTime;
// Timeout.UnsignedInfinite if we are a single-shot timer. Otherwise, the repeat interval.
internal uint _period;
// Info about the user's callback
private readonly TimerCallback _timerCallback;
private readonly object _state;
private readonly ExecutionContext _executionContext;
// When Timer.Dispose(WaitHandle) is used, we need to signal the wait handle only
// after all pending callbacks are complete. We set _canceled to prevent any callbacks that
// are already queued from running. We track the number of callbacks currently executing in
// _callbacksRunning. We set _notifyWhenNoCallbacksRunning only when _callbacksRunning
// reaches zero. Same applies if Timer.DisposeAsync() is used, except with a Task<bool>
// instead of with a provided WaitHandle.
private int _callbacksRunning;
private volatile bool _canceled;
private volatile object _notifyWhenNoCallbacksRunning; // may be either WaitHandle or Task<bool>
internal TimerQueueTimer(TimerCallback timerCallback, object state, uint dueTime, uint period, bool flowExecutionContext)
{
_timerCallback = timerCallback;
_state = state;
_dueTime = Timeout.UnsignedInfinite;
_period = Timeout.UnsignedInfinite;
if (flowExecutionContext)
{
_executionContext = ExecutionContext.Capture();
}
_associatedTimerQueue = TimerQueue.Instances[Thread.GetCurrentProcessorId() % TimerQueue.Instances.Length];
// After the following statement, the timer may fire. No more manipulation of timer state outside of
// the lock is permitted beyond this point!
if (dueTime != Timeout.UnsignedInfinite)
Change(dueTime, period);
}
internal bool Change(uint dueTime, uint period)
{
bool success;
lock (_associatedTimerQueue)
{
if (_canceled)
throw new ObjectDisposedException(null, SR.ObjectDisposed_Generic);
_period = period;
if (dueTime == Timeout.UnsignedInfinite)
{
_associatedTimerQueue.DeleteTimer(this);
success = true;
}
else
{
if (
#if CORECLR
// Don't emit this event during EventPipeController. This avoids initializing FrameworkEventSource during start-up which is expensive relative to the rest of start-up.
!EventPipeController.Initializing &&
#endif
FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferSendObj(this, 1, string.Empty, true, (int)dueTime, (int)period);
success = _associatedTimerQueue.UpdateTimer(this, dueTime, period);
}
}
return success;
}
public void Close()
{
lock (_associatedTimerQueue)
{
if (!_canceled)
{
_canceled = true;
_associatedTimerQueue.DeleteTimer(this);
}
}
}
public bool Close(WaitHandle toSignal)
{
bool success;
bool shouldSignal = false;
lock (_associatedTimerQueue)
{
if (_canceled)
{
success = false;
}
else
{
_canceled = true;
_notifyWhenNoCallbacksRunning = toSignal;
_associatedTimerQueue.DeleteTimer(this);
shouldSignal = _callbacksRunning == 0;
success = true;
}
}
if (shouldSignal)
SignalNoCallbacksRunning();
return success;
}
public ValueTask CloseAsync()
{
lock (_associatedTimerQueue)
{
object notifyWhenNoCallbacksRunning = _notifyWhenNoCallbacksRunning;
// Mark the timer as canceled if it's not already.
if (_canceled)
{
if (notifyWhenNoCallbacksRunning is WaitHandle)
{
// A previous call to Close(WaitHandle) stored a WaitHandle. We could try to deal with
// this case by using ThreadPool.RegisterWaitForSingleObject to create a Task that'll
// complete when the WaitHandle is set, but since arbitrary WaitHandle's can be supplied
// by the caller, it could be for an auto-reset event or similar where that caller's
// WaitOne on the WaitHandle could prevent this wrapper Task from completing. We could also
// change the implementation to support storing multiple objects, but that's not pay-for-play,
// and the existing Close(WaitHandle) already discounts this as being invalid, instead just
// returning false if you use it multiple times. Since first calling Timer.Dispose(WaitHandle)
// and then calling Timer.DisposeAsync is not something anyone is likely to or should do, we
// simplify by just failing in that case.
return new ValueTask(Task.FromException(new InvalidOperationException(SR.InvalidOperation_TimerAlreadyClosed)));
}
}
else
{
_canceled = true;
_associatedTimerQueue.DeleteTimer(this);
}
// We've deleted the timer, so if there are no callbacks queued or running,
// we're done and return an already-completed value task.
if (_callbacksRunning == 0)
{
return default;
}
Debug.Assert(
notifyWhenNoCallbacksRunning == null ||
notifyWhenNoCallbacksRunning is Task<bool>);
// There are callbacks queued or running, so we need to store a Task<bool>
// that'll be used to signal the caller when all callbacks complete. Do so as long as
// there wasn't a previous CloseAsync call that did.
if (notifyWhenNoCallbacksRunning == null)
{
var t = new Task<bool>((object)null, TaskCreationOptions.RunContinuationsAsynchronously);
_notifyWhenNoCallbacksRunning = t;
return new ValueTask(t);
}
// A previous CloseAsync call already hooked up a task. Just return it.
return new ValueTask((Task<bool>)notifyWhenNoCallbacksRunning);
}
}
void IThreadPoolWorkItem.Execute() => Fire(isThreadPool: true);
internal void Fire(bool isThreadPool = false)
{
bool canceled = false;
lock (_associatedTimerQueue)
{
canceled = _canceled;
if (!canceled)
_callbacksRunning++;
}
if (canceled)
return;
CallCallback(isThreadPool);
bool shouldSignal = false;
lock (_associatedTimerQueue)
{
_callbacksRunning--;
if (_canceled && _callbacksRunning == 0 && _notifyWhenNoCallbacksRunning != null)
shouldSignal = true;
}
if (shouldSignal)
SignalNoCallbacksRunning();
}
internal void SignalNoCallbacksRunning()
{
object toSignal = _notifyWhenNoCallbacksRunning;
Debug.Assert(toSignal is WaitHandle || toSignal is Task<bool>);
if (toSignal is WaitHandle wh)
{
EventWaitHandle.Set(wh.SafeWaitHandle);
}
else
{
((Task<bool>)toSignal).TrySetResult(true);
}
}
internal void CallCallback(bool isThreadPool)
{
if (FrameworkEventSource.Log.IsEnabled(EventLevel.Informational, FrameworkEventSource.Keywords.ThreadTransfer))
FrameworkEventSource.Log.ThreadTransferReceiveObj(this, 1, string.Empty);
// Call directly if EC flow is suppressed
ExecutionContext context = _executionContext;
if (context == null)
{
_timerCallback(_state);
}
else
{
if (isThreadPool)
{
ExecutionContext.RunFromThreadPoolDispatchLoop(Thread.CurrentThread, context, s_callCallbackInContext, this);
}
else
{
ExecutionContext.RunInternal(context, s_callCallbackInContext, this);
}
}
}
private static readonly ContextCallback s_callCallbackInContext = state =>
{
TimerQueueTimer t = (TimerQueueTimer)state;
t._timerCallback(t._state);
};
}
// TimerHolder serves as an intermediary between Timer and TimerQueueTimer, releasing the TimerQueueTimer
// if the Timer is collected.
// This is necessary because Timer itself cannot use its finalizer for this purpose. If it did,
// then users could control timer lifetimes using GC.SuppressFinalize/ReRegisterForFinalize.
// You might ask, wouldn't that be a good thing? Maybe (though it would be even better to offer this
// via first-class APIs), but Timer has never offered this, and adding it now would be a breaking
// change, because any code that happened to be suppressing finalization of Timer objects would now
// unwittingly be changing the lifetime of those timers.
internal sealed class TimerHolder
{
internal TimerQueueTimer _timer;
public TimerHolder(TimerQueueTimer timer)
{
_timer = timer;
}
~TimerHolder()
{
// If shutdown has started, another thread may be suspended while holding the timer lock.
// So we can't safely close the timer.
//
// Similarly, we should not close the timer during AD-unload's live-object finalization phase.
// A rude abort may have prevented us from releasing the lock.
//
// Note that in either case, the Timer still won't fire, because ThreadPool threads won't be
// allowed to run anymore.
if (Environment.HasShutdownStarted)
return;
_timer.Close();
}
public void Close()
{
_timer.Close();
GC.SuppressFinalize(this);
}
public bool Close(WaitHandle notifyObject)
{
bool result = _timer.Close(notifyObject);
GC.SuppressFinalize(this);
return result;
}
public ValueTask CloseAsync()
{
ValueTask result = _timer.CloseAsync();
GC.SuppressFinalize(this);
return result;
}
}
public sealed class Timer : MarshalByRefObject, IDisposable, IAsyncDisposable
{
private const uint MAX_SUPPORTED_TIMEOUT = (uint)0xfffffffe;
private TimerHolder _timer;
public Timer(TimerCallback callback,
object state,
int dueTime,
int period) :
this(callback, state, dueTime, period, flowExecutionContext: true)
{
}
internal Timer(TimerCallback callback,
object state,
int dueTime,
int period,
bool flowExecutionContext)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
TimerSetup(callback, state, (uint)dueTime, (uint)period, flowExecutionContext);
}
public Timer(TimerCallback callback,
object state,
TimeSpan dueTime,
TimeSpan period)
{
long dueTm = (long)dueTime.TotalMilliseconds;
if (dueTm < -1)
throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTm), SR.ArgumentOutOfRange_TimeoutTooLarge);
long periodTm = (long)period.TotalMilliseconds;
if (periodTm < -1)
throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (periodTm > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(periodTm), SR.ArgumentOutOfRange_PeriodTooLarge);
TimerSetup(callback, state, (uint)dueTm, (uint)periodTm);
}
[CLSCompliant(false)]
public Timer(TimerCallback callback,
object state,
uint dueTime,
uint period)
{
TimerSetup(callback, state, dueTime, period);
}
public Timer(TimerCallback callback,
object state,
long dueTime,
long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
TimerSetup(callback, state, (uint)dueTime, (uint)period);
}
public Timer(TimerCallback callback)
{
int dueTime = -1; // we want timer to be registered, but not activated. Requires caller to call
int period = -1; // Change after a timer instance is created. This is to avoid the potential
// for a timer to be fired before the returned value is assigned to the variable,
// potentially causing the callback to reference a bogus value (if passing the timer to the callback).
TimerSetup(callback, this, (uint)dueTime, (uint)period);
}
private void TimerSetup(TimerCallback callback,
object state,
uint dueTime,
uint period,
bool flowExecutionContext = true)
{
if (callback == null)
throw new ArgumentNullException(nameof(TimerCallback));
_timer = new TimerHolder(new TimerQueueTimer(callback, state, dueTime, period, flowExecutionContext));
}
public bool Change(int dueTime, int period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
return _timer._timer.Change((uint)dueTime, (uint)period);
}
public bool Change(TimeSpan dueTime, TimeSpan period)
{
return Change((long)dueTime.TotalMilliseconds, (long)period.TotalMilliseconds);
}
[CLSCompliant(false)]
public bool Change(uint dueTime, uint period)
{
return _timer._timer.Change(dueTime, period);
}
public bool Change(long dueTime, long period)
{
if (dueTime < -1)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (period < -1)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
if (dueTime > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(dueTime), SR.ArgumentOutOfRange_TimeoutTooLarge);
if (period > MAX_SUPPORTED_TIMEOUT)
throw new ArgumentOutOfRangeException(nameof(period), SR.ArgumentOutOfRange_PeriodTooLarge);
return _timer._timer.Change((uint)dueTime, (uint)period);
}
public bool Dispose(WaitHandle notifyObject)
{
if (notifyObject == null)
throw new ArgumentNullException(nameof(notifyObject));
return _timer.Close(notifyObject);
}
public void Dispose()
{
_timer.Close();
}
public ValueTask DisposeAsync()
{
return _timer.CloseAsync();
}
}
}
| |
using Orleans;
using Orleans.Runtime;
using Orleans.Streams;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.TestingHost;
using TestGrainInterfaces;
using Tests.GeoClusterTests;
using Xunit;
using Xunit.Abstractions;
using Orleans.Hosting;
using Orleans.Internal;
namespace UnitTests.GeoClusterTests
{
[TestCategory("GeoCluster")]
public class MultiClusterRegistrationTests : TestingClusterHost
{
private string[] ClusterNames;
private ClientWrapper[][] Clients;
private IEnumerable<KeyValuePair<string, ClientWrapper>> EnumerateClients()
{
for (int i = 0; i < ClusterNames.Length; i++)
foreach (var c in Clients[i])
yield return new KeyValuePair<string, ClientWrapper>(ClusterNames[i], c);
}
public MultiClusterRegistrationTests(ITestOutputHelper output) : base(output)
{
}
[SkippableFact]
public async Task TwoClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2));
var testtasks = new List<Task>();
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
foreach (var t in testtasks)
await t;
}
[SkippableFact(), TestCategory("Functional")]
public async Task ThreeClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 2));
var testtasks = new List<Task>();
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
foreach (var t in testtasks)
await t;
}
[SkippableFact]
public async Task FourClusterBattery()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () => StartClustersAndClients(2, 2, 1, 1));
var testtasks = new List<Task>();
for (int i = 0; i < 20; i++)
{
testtasks.Add(RunWithTimeout("Deact", 20000, Deact));
testtasks.Add(RunWithTimeout("SequentialCalls", 10000, SequentialCalls));
testtasks.Add(RunWithTimeout("ParallelCalls", 10000, ParallelCalls));
testtasks.Add(RunWithTimeout("ManyParallelCalls", 10000, ManyParallelCalls));
testtasks.Add(RunWithTimeout("ObserverBasedClientNotification", 10000, ObserverBasedClientNotification));
testtasks.Add(RunWithTimeout("StreamBasedClientNotification", 10000, StreamBasedClientNotification));
}
foreach (var t in testtasks)
await t;
}
private Task StartClustersAndClients(params short[] silos)
{
return StartClustersAndClients(null, silos);
}
public class SiloConfigurator : ISiloBuilderConfigurator
{
public void Configure(ISiloHostBuilder hostBuilder)
{
hostBuilder.AddSimpleMessageStreamProvider("SMSProvider");
}
}
private Task StartClustersAndClients(Action<TestClusterBuilder> configureTestCluster, params short[] silos)
{
WriteLog("Creating clusters and clients...");
var stopwatch = new System.Diagnostics.Stopwatch();
stopwatch.Start();
// use a random global service id for testing purposes
var globalserviceid = Guid.NewGuid();
random = new Random();
System.Threading.ThreadPool.SetMaxThreads(8, 8);
// Create clusters and clients
ClusterNames = new string[silos.Length];
Clients = new ClientWrapper[silos.Length][];
for (int i = 0; i < silos.Length; i++)
{
var numsilos = silos[i];
var clustername = ClusterNames[i] = ((char)('A' + i)).ToString();
var c = Clients[i] = new ClientWrapper[numsilos];
NewGeoCluster<SiloConfigurator>(globalserviceid, clustername, silos[i], configureTestCluster);
// create one client per silo
Parallel.For(0, numsilos, paralleloptions, (j) => c[j] = this.NewClient(
clustername,
j,
ClientWrapper.Factory,
clientBuilder => clientBuilder.AddSimpleMessageStreamProvider("SMSProvider")));
}
WriteLog("Clusters and clients are ready (elapsed = {0})", stopwatch.Elapsed);
// wait for configuration to stabilize
WaitForLivenessToStabilizeAsync().WaitWithThrow(TimeSpan.FromMinutes(1));
Clients[0][0].InjectClusterConfiguration(ClusterNames);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
stopwatch.Stop();
WriteLog("Multicluster is ready (elapsed = {0}).", stopwatch.Elapsed);
return Task.CompletedTask;
}
Random random;
public class ClientWrapper : ClientWrapperBase
{
public static readonly Func<string, int, string, Action<IClientBuilder>, ClientWrapper> Factory =
(name, gwPort, clusterId, clientConfigurator) => new ClientWrapper(name, gwPort, clusterId, clientConfigurator);
public ClientWrapper(string name, int gatewayport, string clusterId, Action<IClientBuilder> clientConfigurator) : base(name, gatewayport, clusterId, clientConfigurator)
{
this.systemManagement = this.GrainFactory.GetGrain<IManagementGrain>(0);
}
public int CallGrain(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Logger.Info("Call Grain {0}", grainRef);
Task<int> toWait = grainRef.SayHelloAsync();
toWait.Wait();
return toWait.GetResult();
}
public string GetRuntimeId(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Logger.Info("GetRuntimeId {0}", grainRef);
Task<string> toWait = grainRef.GetRuntimeId();
toWait.Wait();
return toWait.GetResult();
}
public void Deactivate(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Logger.Info("Deactivate {0}", grainRef);
Task toWait = grainRef.Deactivate();
toWait.GetResult();
}
public void EnableStreamNotifications(int i)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Logger.Info("EnableStreamNotifications {0}", grainRef);
Task toWait = grainRef.EnableStreamNotifications();
toWait.GetResult();
}
// observer-based notification
public void Subscribe(int i, IClusterTestListener listener)
{
var grainRef = this.GrainFactory.GetGrain<IClusterTestGrain>(i);
this.Logger.Info("Create Listener object {0}", grainRef);
listeners.Add(listener);
var obj = this.GrainFactory.CreateObjectReference<IClusterTestListener>(listener).Result;
listeners.Add(obj);
this.Logger.Info("Subscribe {0}", grainRef);
Task toWait = grainRef.Subscribe(obj);
toWait.GetResult();
}
List<IClusterTestListener> listeners = new List<IClusterTestListener>(); // keep them from being GCed
// stream-based notification
public void SubscribeStream(int i, IAsyncObserver<int> listener)
{
IStreamProvider streamProvider = this.Client.GetStreamProvider("SMSProvider");
Guid guid = new Guid(i, 0, 0, new byte[8]);
IAsyncStream<int> stream = streamProvider.GetStream<int>(guid, "notificationtest");
handle = stream.SubscribeAsync(listener).GetResult();
}
StreamSubscriptionHandle<int> handle;
public void InjectClusterConfiguration(string[] clusters, string comment = "", bool checkForLaggingSilos = true)
{
systemManagement.InjectMultiClusterConfiguration(clusters, comment, checkForLaggingSilos).Wait();
}
IManagementGrain systemManagement;
public string GetGrainRef(int i)
{
return this.GrainFactory.GetGrain<IClusterTestGrain>(i).ToString();
}
}
public class ClusterTestListener : IClusterTestListener, IAsyncObserver<int>
{
public ClusterTestListener(Action<int> oncall)
{
this.oncall = oncall;
}
private Action<int> oncall;
public void GotHello(int number)
{
count++;
oncall(number);
}
public Task OnNextAsync(int item, StreamSequenceToken token = null)
{
GotHello(item);
return Task.CompletedTask;
}
public Task OnCompletedAsync()
{
throw new NotImplementedException();
}
public Task OnErrorAsync(Exception ex)
{
throw new NotImplementedException();
}
public int count;
}
private int Next()
{
lock (random)
return random.Next();
}
private int[] Next(int count)
{
var result = new int[count];
lock (random)
for (int i = 0; i < count; i++)
result[i] = random.Next();
return result;
}
private async Task SequentialCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
var list = EnumerateClients().ToList();
// one call to each silo, in parallel
foreach (var c in list) c.Value.CallGrain(x);
// total number of increments should match
AssertEqual(list.Count() + 1, Clients[0][0].CallGrain(x), gref);
}
private async Task ParallelCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
var list = EnumerateClients().ToList();
// one call to each silo, in parallel
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
// total number of increments should match
AssertEqual(list.Count + 1, Clients[0][0].CallGrain(x), gref);
}
private async Task ManyParallelCalls()
{
await Task.Yield();
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// pick just one client per cluster, use it multiple times
var clients = Clients.Select(a => a[0]).ToList();
// concurrently increment (numupdates) times, distributed over the clients
Parallel.For(0, 20, paralleloptions, i => clients[i % clients.Count].CallGrain(x));
// total number of increments should match
AssertEqual(21, Clients[0][0].CallGrain(x), gref);
}
private async Task Deact()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put into cluster A
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
// ensure presence in all caches
var list = EnumerateClients().ToList();
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
Parallel.ForEach(list, paralleloptions, k => k.Value.CallGrain(x));
AssertEqual(2* list.Count() + 1, Clients[0][0].CallGrain(x), gref);
WriteLog("Grain {0} deactivating.", gref);
//deactivate
Clients[0][0].Deactivate(x);
// wait for deactivation to complete
await Task.Delay(5000);
WriteLog("Grain {0} reactivating.", gref);
// activate anew in cluster B
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(Clusters[ClusterNames[1]].Silos, silo => silo.SiloAddress.ToString() == newid);
WriteLog("Grain {0} Check that other clusters find new activation.", gref);
for (int i = 2; i < Clusters.Count; i++)
{
var idd = Clients[i][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, idd, ClusterNames[i]);
AssertEqual(newid, idd, gref);
}
}
private async Task ObserverBasedClientNotification()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
Clients[0][0].GetRuntimeId(x);
WriteLog("{0} created grain", gref);
var promises = new List<Task<int>>();
// create an observer on each client
Parallel.For(0, Clients.Length, paralleloptions, i =>
{
for (int jj = 0; jj < Clients[i].Length; jj++)
{
int j = jj;
var promise = new TaskCompletionSource<int>();
var listener = new ClusterTestListener((num) =>
{
WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref);
promise.TrySetResult(num);
});
lock(promises)
promises.Add(promise.Task);
Clients[i][j].Subscribe(x, listener);
WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref);
}
});
// call the grain
Clients[0][0].CallGrain(x);
await Task.WhenAll(promises);
var sortedresults = promises.Select(p => p.Result).OrderBy(num => num).ToArray();
// each client should get its own notification
for (int i = 0; i < sortedresults.Length; i++)
AssertEqual(sortedresults[i], i, gref);
}
private async Task StreamBasedClientNotification()
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
Clients[0][0].EnableStreamNotifications(x);
WriteLog("{0} created grain", gref);
var promises = new List<Task<int>>();
// create an observer on each client
Parallel.For(0, Clients.Length, paralleloptions, i =>
{
for (int jj = 0; jj < Clients[i].Length; jj++)
{
int j = jj;
var promise = new TaskCompletionSource<int>();
var listener = new ClusterTestListener((num) =>
{
WriteLog("{3} observedcall {2} on Client[{0}][{1}]", i, j, num, gref);
promise.TrySetResult(num);
});
lock (promises)
promises.Add(promise.Task);
Clients[i][j].SubscribeStream(x, listener);
WriteLog("{2} subscribed to Client[{0}][{1}]", i, j, gref);
}
});
// call the grain
Clients[0][0].CallGrain(x);
await Task.WhenAll(promises);
// each client should get same value
foreach (var p in promises)
AssertEqual(1, p.Result, gref);
}
[SkippableFact, TestCategory("Functional")]
public async Task BlockedDeact()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
return StartClustersAndClients(2, 2);
});
await RunWithTimeout("BlockedDeact", 10 * 1000, async () =>
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put into cluster A and access from cluster B
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
var id2 = Clients[1][0].GetRuntimeId(x);
AssertEqual(id2, id, gref);
// deactivate grain in cluster A, but block deactivation message to cluster B
WriteLog("Grain {0} deactivating.", gref);
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
Clients[0][0].Deactivate(x);
await Task.Delay(5000);
UnblockAllClusterCommunication(ClusterNames[0]);
// reactivate in cluster B. This should cause unregistration to be sent
WriteLog("Grain {0} reactivating.", gref);
// activate anew in cluster B
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(newid, Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
// connect from cluster A
val = Clients[0][0].CallGrain(x);
AssertEqual(2, val, gref);
});
}
[SkippableFact, TestCategory("Functional")]
public async Task CacheCleanup()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
return StartClustersAndClients(1, 1);
});
await RunWithTimeout("CacheCleanup", 1000000, async () =>
{
var x = Next();
var gref = Clients[0][0].GetGrainRef(x);
// put grain into cluster A
var id = Clients[0][0].GetRuntimeId(x);
WriteLog("Grain {0} at {1}", gref, id);
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == id);
// access the grain from B, causing
// causing entry to be installed in B's directory and/or B's directory caches
var id2 = Clients[1][0].GetRuntimeId(x);
AssertEqual(id2, id, gref);
// block communication from A to B
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
// change multi-cluster configuration to be only { B }, i.e. exclude A
WriteLog($"Removing A from multi-cluster");
Clients[1][0].InjectClusterConfiguration(new string[] { ClusterNames[1] }, "exclude A", false);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
// give the cache cleanup process time to remove all cached references in B
await Task.Delay(40000);
// now try to access the grain from cluster B
// if everything works correctly this should succeed, creating a new instances on B locally
// (if invalid caches were not removed this times out)
WriteLog("Grain {0} doubly-activating.", gref);
var val = Clients[1][0].CallGrain(x);
AssertEqual(1, val, gref);
var newid = Clients[1][0].GetRuntimeId(x);
WriteLog("{2} sees Grain {0} at {1}", gref, newid, ClusterNames[1]);
Assert.Contains(newid, Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
});
}
[SkippableFact, TestCategory("Functional")]
public async Task CacheCleanupMultiple()
{
await RunWithTimeout("Start Clusters and Clients", 180 * 1000, () =>
{
return StartClustersAndClients(3, 3);
});
await RunWithTimeout("CacheCleanupMultiple", 1000000, async () =>
{
int count = 100;
var grains = Next(count);
var grefs = grains.Select((x) => Clients[0][0].GetGrainRef(x)).ToList();
// put grains into cluster A
var ids = grains.Select((x,i) => Clients[0][i % 3].GetRuntimeId(x)).ToList();
WriteLog($"{count} Grains activated on A");
for (int i = 0; i < count; i++ )
Assert.Contains(Clusters[ClusterNames[0]].Silos, silo => silo.SiloAddress.ToString() == ids[i]);
// access all the grains living in A from all the clients of B
// causing entries to be installed in B's directory and in B's directory caches
for (int j = 0; j < 3; j++)
{
var ids2 = grains.Select((x) => Clients[1][j].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(ids2[i], ids[i], grefs[i]);
}
WriteLog($"{count} Grain references cached in B");
// block communication from A to B
BlockAllClusterCommunication(ClusterNames[0], ClusterNames[1]);
// change multi-cluster configuration to be only { B }, i.e. exclude A
WriteLog($"Removing A from multi-cluster");
Clients[1][0].InjectClusterConfiguration(new string[] { ClusterNames[1] }, "exclude A", false);
WaitForMultiClusterGossipToStabilizeAsync(false).WaitWithThrow(TimeSpan.FromMinutes(System.Diagnostics.Debugger.IsAttached ? 60 : 1));
// give the cache cleanup process time to remove all cached references in B
await Task.Delay(50000);
// call the grains from random clients of B
// if everything works correctly this should succeed, creating new instances on B locally
// (if invalid caches were not removed this times out)
var vals = grains.Select((x) => Clients[1][Math.Abs(x) % 3].CallGrain(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(1, vals[i], grefs[i]);
// check the placement of the new grains, from client 0
var newids = grains.Select((x) => Clients[1][0].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
Assert.Contains(newids[i], Clusters[ClusterNames[1]].Silos.Select(s => s.SiloAddress.ToString()));
// check the placement of these same grains, from other clients
for (int j = 1; j < 3; j++)
{
var ids2 = grains.Select((x) => Clients[1][j].GetRuntimeId(x)).ToList();
for (int i = 0; i < count; i++)
AssertEqual(ids2[i], newids[i], grefs[i]);
}
});
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Text;
using TestLibrary;
public class StringConcat2
{
public static int Main()
{
StringConcat2 sc2 = new StringConcat2();
TestLibrary.TestFramework.BeginTestCase("StringConcat2");
if (sc2.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
retVal = PosTest12() && retVal;
retVal = PosTest13() && retVal;
retVal = PosTest14() && retVal;
retVal = PosTest15() && retVal;
retVal = PosTest16() && retVal;
return retVal;
}
public bool PosTest1()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PostTest1:Concat two objects of object ");
try
{
ObjA = new object();
ObjB = new object();
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != ObjA.ToString() + ObjB.ToString())
{
TestLibrary.TestFramework.LogError("001", "Concat a random object ExpectResult is" + ObjA.ToString() + ObjB.ToString()+ ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PostTest2:Concat null object and null object");
try
{
ObjA = null;
ObjB = null;
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("003", "Concat null object and null object ExpectResult is" + string.Empty + " ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest3:Concat null object and empty");
try
{
ObjA = null;
ObjB = "";
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != string.Empty)
{
TestLibrary.TestFramework.LogError("005", "Concat null object and empty ExpectResult is equel" + string.Empty + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
string ActualResult;
string ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest4: Concat null and two tabs");
try
{
ObjB = null;
ObjA = new string('\t', 2);
ActualResult = string.Concat(ObjB,ObjA);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("007", "Concat null and two tabs ExpectResult is" +ObjA.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest5()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest5:Concat null and an object of int");
try
{
ObjA = null;
ObjB = new int();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("009", "Concat null and an object of int ExpectResult is equel" +ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest6()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest6: Concat null and an object of datetime");
try
{
ObjA = null;
ObjB = new DateTime();
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("011", "Concat null and an object of datetime ExpectResult is equel" + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest7()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest7: Concat null and an object of bool");
try
{
ObjA = null;
ObjB = new bool();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("013", "Concat nulland an object of bool ExpectResult is equel" +ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest8()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest8:Concat null and an object of random class instance");
try
{
ObjA = null;
ObjB = new StringConcat2();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("015", "Concat null and an object of random class instance ExpectResult is equel"+ ObjB.ToString() + " ,ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("016", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest9()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest9: Concat null and an object of Guid");
try
{
ObjA = null;
ObjB = new Guid();
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("017", "Concat null and an object of Guid ExpectResult is equel" + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("018", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest10()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest10:Concat null and an object of Random ");
try
{
ObjA = null;
ObjB = new Random(-55);
ActualResult = string.Concat(ObjA,ObjB);
if (ActualResult != ObjB.ToString())
{
TestLibrary.TestFramework.LogError("019", "Concat null and an object of Random ExpectResult is equel" + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("020", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest11()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest11:Concat an object and null ");
try
{
ObjA = new object();
ObjB = null;
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("021", "Concat an object and null ExpectResult is equel" + ObjA.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("022", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest12()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest12:Concat an object of Guid and null ");
try
{
ObjA = new Guid();
ObjB = null;
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString())
{
TestLibrary.TestFramework.LogError("023", "Concat an object of Guid and null ExpectResult is equel" + ObjA.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("024", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest13()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest13:Concat an object of Guid and an object ");
try
{
ObjA = new Guid();
ObjB = new object();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString() + ObjB.ToString())
{
TestLibrary.TestFramework.LogError("025", "Concat an object of Guid and null ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("026", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest14()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest14:Concat an objec and an object of datetime");
try
{
ObjA = new object();
ObjB = new DateTime();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString() + ObjB.ToString())
{
TestLibrary.TestFramework.LogError("027", "Concat an object and an object of datetime ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("028", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest15()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest15:Concat an object of datetime and an object of bool");
try
{
ObjA = new DateTime();
ObjB = new bool();
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString() + ObjB.ToString())
{
TestLibrary.TestFramework.LogError("029", "Concat an object of datetime and an object of bool ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("030", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
public bool PosTest16()
{
bool retVal = true;
string ActualResult;
object ObjA;
object ObjB;
TestLibrary.TestFramework.BeginScenario("PosTest16:Concat object of two number of less than 0");
try
{
ObjA = -123;
ObjB = -132;
ActualResult = string.Concat(ObjA, ObjB);
if (ActualResult != ObjA.ToString() + ObjB.ToString())
{
TestLibrary.TestFramework.LogError("031", "Concat object of two number of less than 0 ExpectResult is equel" + ObjA.ToString() + ObjB.ToString() + ",ActualResult is (" + ActualResult + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("032", "Unexpected exception" + e);
retVal = false;
}
return retVal;
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeRefactorings.ExtractMethod;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod
{
public class ExtractMethodTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace)
{
return new ExtractMethodCodeRefactoringProvider();
}
[WorkItem(540799, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540799")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestPartialSelection()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { bool b = true ; System . Console . WriteLine ( [|b != true|] ? b = true : b = false ) ; } } ",
@"class Program { static void Main ( string [ ] args ) { bool b = true ; System . Console . WriteLine ( {|Rename:NewMethod|} ( b ) ? b = true : b = false ) ; } private static bool NewMethod ( bool b ) { return b != true ; } } ",
index: 0);
}
[WorkItem(540796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540796")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestReadOfDataThatDoesNotFlowIn()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { int x = 1 ; object y = 0 ; [|int s = true ? fun ( x ) : fun ( y ) ;|] } private static T fun < T > ( T t ) { return t ; } } ",
@"class Program { static void Main ( string [ ] args ) { int x = 1 ; object y = 0 ; {|Rename:NewMethod|} ( x , y ) ; } private static void NewMethod ( int x , object y ) { int s = true ? fun ( x ) : fun ( y ) ; } private static T fun < T > ( T t ) { return t ; } } ",
index: 0);
}
[WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnGoto()
{
await TestMissingAsync(@"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { [|goto label2 ; return x * x ;|] } ; label2 : return ; } } ");
}
[WorkItem(540819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540819")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestOnStatementAfterUnconditionalGoto()
{
await TestAsync(
@"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { goto label2 ; [|return x * x ;|] } ; label2 : return ; } } ",
@"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { goto label2 ; return {|Rename:NewMethod|} ( x ) ; } ; label2 : return ; } private static int NewMethod ( int x ) { return x * x ; } } ",
index: 0);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnNamespace()
{
await TestAsync(
@"class Program { void Main ( ) { [|System|] . Console . WriteLine ( 4 ) ; } } ",
@"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private static void NewMethod ( ) { System . Console . WriteLine ( 4 ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnType()
{
await TestAsync(
@"class Program { void Main ( ) { [|System . Console|] . WriteLine ( 4 ) ; } } ",
@"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private static void NewMethod ( ) { System . Console . WriteLine ( 4 ) ; } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestMissingOnBase()
{
await TestAsync(
@"class Program { void Main ( ) { [|base|] . ToString ( ) ; } } ",
@"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private void NewMethod ( ) { base . ToString ( ) ; } } ");
}
[WorkItem(545623, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545623")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task TestOnActionInvocation()
{
await TestAsync(
@"using System ; class C { public static Action X { get ; set ; } } class Program { void Main ( ) { [|C . X|] ( ) ; } } ",
@"using System ; class C { public static Action X { get ; set ; } } class Program { void Main ( ) { {|Rename:GetX|} ( ) ( ) ; } private static Action GetX ( ) { return C . X ; } } ");
}
[WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DisambiguateCallSiteIfNecessary1()
{
await TestAsync(
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo([|x => 0|], y => 0, z, z);
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo<byte, byte>({|Rename:NewMethod|}(), y => 0, z, z);
}
private static Func<byte, byte> NewMethod()
{
return x => 0;
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
compareTokens: false);
}
[WorkItem(529841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529841"), WorkItem(714632, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/714632")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DisambiguateCallSiteIfNecessary2()
{
await TestAsync(
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo([|x => 0|], y => { return 0; }, z, z);
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
@"using System;
class Program
{
static void Main()
{
byte z = 0;
Foo<byte, byte>({|Rename:NewMethod|}(), y => { return 0; }, z, z);
}
private static Func<byte, byte> NewMethod()
{
return x => 0;
}
static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); }
static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); }
}",
compareTokens: false);
}
[WorkItem(530709, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530709")]
[WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DontOverparenthesize()
{
await TestAsync(
@"using System;
static class C
{
static void Ex(this string x) { }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Main()
{
Outer(y => Inner(x => [|x|].Ex(), y), - -1);
}
}
static class E
{
public static void Ex(this int x) { }
}",
@"using System;
static class C
{
static void Ex(this string x) { }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Main()
{
Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1);
}
private static string GetX(string x)
{
return x;
}
}
static class E
{
public static void Ex(this int x) { }
}",
parseOptions: Options.Regular);
}
[WorkItem(632182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/632182")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task DontOverparenthesizeGenerics()
{
await TestAsync(
@"using System;
static class C
{
static void Ex<T>(this string x) { }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Main()
{
Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1);
}
}
static class E
{
public static void Ex<T>(this int x) { }
}",
@"using System;
static class C
{
static void Ex<T>(this string x) { }
static void Inner(Action<string> x, string y) { }
static void Inner(Action<string> x, int y) { }
static void Inner(Action<int> x, int y) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
static void Main()
{
Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1);
}
private static string GetX(string x)
{
return x;
}
}
static class E
{
public static void Ex<T>(this int x) { }
}",
parseOptions: Options.Regular);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_1()
{
await TestAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct();
obj2.Do();|]
obj1.Do();
obj2.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2;
{|Rename:NewMethod|}(out obj1, out obj2);
obj1.Do();
obj2.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj2.Do();
}
}",
compareTokens: false);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_2()
{
await TestAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct();
obj2.Do();
/* Second Interesting comment. */
Construct obj3 = new Construct();
obj3.Do();|]
obj1.Do();
obj2.Do();
obj3.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2, obj3;
{|Rename:NewMethod|}(out obj1, out obj2, out obj3);
obj1.Do();
obj2.Do();
obj3.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj2.Do();
/* Second Interesting comment. */
obj3 = new Construct();
obj3.Do();
}
}",
compareTokens: false);
}
[WorkItem(984831, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/984831")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
public async Task PreserveCommentsBeforeDeclaration_3()
{
await TestAsync(
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
[|Construct obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
Construct obj2 = new Construct(), obj3 = new Construct();
obj2.Do();
obj3.Do();|]
obj1.Do();
obj2.Do();
obj3.Do();
}
}",
@"class Construct
{
public void Do() { }
static void Main(string[] args)
{
Construct obj1, obj2, obj3;
{|Rename:NewMethod|}(out obj1, out obj2, out obj3);
obj1.Do();
obj2.Do();
obj3.Do();
}
private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3)
{
obj1 = new Construct();
obj1.Do();
/* Interesting comment. */
obj2 = new Construct();
obj3 = new Construct();
obj2.Do();
obj3.Do();
}
}",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTuple()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| (int, int) x = (1, 2); |] System . Console . WriteLine ( x.Item1 ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationWithNames()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| (int a, int b) x = (1, 2); |] System . Console . WriteLine ( x.a ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationWithSomeNames()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| (int a, int) x = (1, 2); |] System . Console . WriteLine ( x.a ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int a, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleLiteralWithNames()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| (int, int) x = (a: 1, b: 2); |] System . Console . WriteLine ( x.Item1 ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int, int) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.Item1); } private static (int, int) NewMethod() { return (a: 1, b: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleDeclarationAndLiteralWithNames()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| (int a, int b) x = (c: 1, d: 2); |] System . Console . WriteLine ( x.a ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int a, int b) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.a); } private static (int a, int b) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleIntoVar()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| var x = (c: 1, d: 2); |] System . Console . WriteLine ( x.c ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int c, int d) x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static (int c, int d) NewMethod() { return (c: 1, d: 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task RefactorWithoutSystemValueTuple()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| var x = (c: 1, d: 2); |] System . Console . WriteLine ( x.c ); } } ",
@"class Program { static void Main ( string [ ] args ) { object x = {|Rename:NewMethod|}(); System.Console.WriteLine(x.c); } private static object NewMethod() { return (c: 1, d: 2); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
[WorkItem(11196, "https://github.com/dotnet/roslyn/issues/11196")]
public async Task TestTupleWithNestedNamedTuple()
{
// This is not the best refactoring, but this is an edge case
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [| var x = new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); |] System . Console . WriteLine ( x.c ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { (int, int, int, int, int, int, int, string, string) x = {|Rename:NewMethod|}(); System . Console . WriteLine ( x.c ); } private static (int, int, int, int, int, int, int, string, string) NewMethod() { return new System.ValueTuple<int, int, int, int, int, int, int, (string a, string b)>(1, 2, 3, 4, 5, 6, 7, (a: ""hello"", b: ""world"")); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
public async Task TestDeconstruction()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { var (x, y) = [| (1, 2) |]; System . Console . WriteLine ( x ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { var (x, y) = {|Rename:NewMethod|}(); System . Console . WriteLine ( x ); } private static (int, int) NewMethod() { return (1, 2); } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod), Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Tuples)]
public async Task TestDeconstruction2()
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { var (x, y) = (1, 2); var z = [| 3; |] System . Console . WriteLine ( z ); } } " + TestResources.NetFX.ValueTuple.tuplelib_cs,
@"class Program { static void Main ( string [ ] args ) { var (x, y) = (1, 2); int z = {|Rename:NewMethod|}(); System . Console . WriteLine ( z ); } private static int NewMethod() { return 3; } }" + TestResources.NetFX.ValueTuple.tuplelib_cs);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.OutVar)]
public async Task TestOutVar()
{
await TestAsync(
@"class C { static void M(int i) { int r; [|r = M1(out int y, i);|] System.Console.WriteLine(r + y); } } ",
@"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); }
private static void NewMethod(int i, out int r, out int y) { r = M1(out y, i); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task TestIsPattern()
{
await TestAsync(
@"class C { static void M(int i) { int r; [|r = M1(3 is int y, i);|] System.Console.WriteLine(r + y); } } ",
@"class C { static void M(int i) { int r; int y; {|Rename:NewMethod|}(i, out r, out y); System.Console.WriteLine(r + y); }
private static void NewMethod(int i, out int r, out int y) { r = M1(3 is int {|Conflict:y|}, i); } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task TestOutVarAndIsPattern()
{
await TestAsync(
@"class C
{
static void M()
{
int r;
[|r = M1(out /*out*/ int /*int*/ y /*y*/) + M2(3 is int z);|]
System.Console.WriteLine(r + y + z);
}
} ",
@"class C
{
static void M()
{
int r;
int y, z;
{|Rename:NewMethod|}(out r, out y, out z);
System.Console.WriteLine(r + y + z);
}
private static void NewMethod(out int r, out int y, out int z)
{
r = M1(out /*out*/ /*int*/ y /*y*/) + M2(3 is int {|Conflict:z|});
}
} ",
compareTokens: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task ConflictingOutVarLocals()
{
await TestAsync(
@"class C { static void M() { int r; [| r = M1(out int y); { M2(out int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } } ",
@"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); }
private static void NewMethod(out int r, out int y) { r = M1(out y); { M2(out int y); System.Console.Write(y); } } } ");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)]
[Test.Utilities.CompilerTrait(Test.Utilities.CompilerFeature.Patterns)]
public async Task ConflictingPatternLocals()
{
await TestAsync(
@"class C { static void M() { int r; [| r = M1(1 is int y); { M2(2 is int y); System.Console.Write(y); }|] System.Console.WriteLine(r + y); } } ",
@"class C { static void M() { int r; int y; {|Rename:NewMethod|}(out r, out y); System.Console.WriteLine(r + y); }
private static void NewMethod(out int r, out int y) { r = M1(1 is int {|Conflict:y|}); { M2(2 is int y); System.Console.Write(y); } } } ");
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Text;
using GitTools.Testing;
using GitVersion;
using GitVersion.BuildAgents;
using GitVersion.Configuration;
using GitVersion.Logging;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation.Cache;
using GitVersionCore.Tests.Helpers;
using LibGit2Sharp;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using NUnit.Framework;
using Shouldly;
using Environment = System.Environment;
namespace GitVersionCore.Tests
{
[TestFixture]
[Parallelizable(ParallelScope.None)]
public class GitVersionExecutorTests : TestBase
{
private IFileSystem fileSystem;
private ILog log;
private IGitVersionCache gitVersionCache;
private IGitPreparer gitPreparer;
private IServiceProvider sp;
[Test]
public void CacheKeySameAfterReNormalizing()
{
using var fixture = new EmptyRepositoryFixture();
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var targetBranch = "refs/head/master";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl, TargetBranch = targetBranch },
WorkingDirectory = fixture.RepositoryPath,
Settings = { NoNormalize = false }
};
var environment = new TestEnvironment();
environment.SetEnvironmentVariable(AzurePipelines.EnvironmentVariableName, "true");
sp = GetServiceProvider(gitVersionOptions, environment: environment);
var preparer = sp.GetService<IGitPreparer>();
preparer.Prepare();
var cacheKeyFactory = sp.GetService<IGitVersionCacheKeyFactory>();
var cacheKey1 = cacheKeyFactory.Create(null);
preparer.Prepare();
var cacheKey2 = cacheKeyFactory.Create(null);
cacheKey2.Value.ShouldBe(cacheKey1.Value);
}
[Test]
public void GitPreparerShouldNotFailWhenTargetPathNotInitialized()
{
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = null
};
Should.NotThrow(() =>
{
sp = GetServiceProvider(gitVersionOptions);
sp.GetService<IGitPreparer>();
});
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CacheKeyForWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl, TargetBranch = "master" },
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
var preparer = sp.GetService<IGitPreparer>();
preparer.Prepare();
var cacheKey = sp.GetService<IGitVersionCacheKeyFactory>().Create(null);
cacheKey.Value.ShouldNotBeEmpty();
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
public void CacheFileExistsOnDisk()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
var stringBuilder = new StringBuilder();
void Action(string s) => stringBuilder.AppendLine(s);
var logAppender = new TestLogAppender(Action);
log = new Log(logAppender);
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
var logsMessages = stringBuilder.ToString();
logsMessages.ShouldContain("Deserializing version variables from cache file", Case.Insensitive, logsMessages);
}
[Test]
public void CacheFileExistsOnDiskWhenOverrideConfigIsSpecifiedVersionShouldBeDynamicallyCalculatedWithoutSavingInCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
var cacheDirectory = gitVersionCache.GetCacheDirectory();
var cacheDirectoryTimestamp = fileSystem.GetLastDirectoryWrite(cacheDirectory);
var config = new ConfigurationBuilder().Add(new Config { TagPrefix = "prefix" }).Build();
gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath, ConfigInfo = { OverrideConfig = config } };
gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
var cachedDirectoryTimestampAfter = fileSystem.GetLastDirectoryWrite(cacheDirectory);
cachedDirectoryTimestampAfter.ShouldBe(cacheDirectoryTimestamp, "Cache was updated when override config was set");
}
[Test]
public void CacheFileIsMissing()
{
var stringBuilder = new StringBuilder();
void Action(string s) => stringBuilder.AppendLine(s);
var logAppender = new TestLogAppender(Action);
log = new Log(logAppender);
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, log, fixture.Repository);
gitVersionCalculator.CalculateVersionVariables();
var logsMessages = stringBuilder.ToString();
logsMessages.ShouldContain("yml not found", Case.Insensitive, logsMessages);
}
[Test]
public void ConfigChangeInvalidatesCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
versionVariables.FileName.ShouldNotBeNullOrEmpty();
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
var configPath = Path.Combine(fixture.RepositoryPath, DefaultConfigFileLocator.DefaultFileName);
fileSystem.WriteAllText(configPath, "next-version: 5.0");
gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, fs: fileSystem);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("5.0.0.0");
}
[Test]
public void NoCacheBypassesCache()
{
const string versionCacheFileContent = @"
Major: 4
Minor: 10
Patch: 3
PreReleaseTag: test.19
PreReleaseTagWithDash: -test.19
PreReleaseLabel: test
PreReleaseLabelWithDash: -test
PreReleaseNumber: 19
WeightedPreReleaseNumber: 19
BuildMetaData:
BuildMetaDataPadded:
FullBuildMetaData: Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
MajorMinorPatch: 4.10.3
SemVer: 4.10.3-test.19
LegacySemVer: 4.10.3-test19
LegacySemVerPadded: 4.10.3-test0019
AssemblySemVer: 4.10.3.0
AssemblySemFileVer: 4.10.3.0
FullSemVer: 4.10.3-test.19
InformationalVersion: 4.10.3-test.19+Branch.feature/test.Sha.dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
BranchName: feature/test
EscapedBranchName: feature-test
Sha: dd2a29aff0c948e1bdf3dabbe13e1576e70d5f9f
ShortSha: dd2a29af
NuGetVersionV2: 4.10.3-test0019
NuGetVersion: 4.10.3-test0019
NuGetPreReleaseTagV2: test0019
NuGetPreReleaseTag: test0019
VersionSourceSha: 4.10.2
CommitsSinceVersionSource: 19
CommitsSinceVersionSourcePadded: 0019
CommitDate: 2015-11-10
UncommittedChanges: 0
";
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
fixture.Repository.MakeACommit();
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
var versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
versionVariables.FileName.ShouldNotBeNullOrEmpty();
fileSystem.WriteAllText(versionVariables.FileName, versionCacheFileContent);
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("4.10.3.0");
gitVersionOptions.Settings.NoCache = true;
versionVariables = gitVersionCalculator.CalculateVersionVariables();
versionVariables.AssemblySemVer.ShouldBe("0.1.0.0");
}
[Test]
public void WorkingDirectoryWithoutGit()
{
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = Environment.SystemDirectory };
var exception = Assert.Throws<DirectoryNotFoundException>(() =>
{
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
gitVersionCalculator.CalculateVersionVariables();
});
exception.Message.ShouldContain("Cannot find the .git directory");
}
[Test]
public void WorkingDirectoryWithoutCommits()
{
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = fixture.RepositoryPath };
var exception = Assert.Throws<GitVersionException>(() =>
{
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions);
gitVersionCalculator.CalculateVersionVariables();
});
exception.Message.ShouldContain("No commits found on the current branch.");
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void GetProjectRootDirectoryWorkingDirectoryWithWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
gitVersionOptions.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(worktreePath);
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
public void GetProjectRootDirectoryNoWorktree()
{
using var fixture = new EmptyRepositoryFixture();
var targetUrl = "https://github.com/GitTools/GitVersion.git";
var gitVersionOptions = new GitVersionOptions
{
RepositoryInfo = { TargetUrl = targetUrl },
WorkingDirectory = fixture.RepositoryPath
};
sp = GetServiceProvider(gitVersionOptions);
var expectedPath = fixture.RepositoryPath.TrimEnd('/', '\\');
gitVersionOptions.ProjectRootDirectory.TrimEnd('/', '\\').ShouldBe(expectedPath);
}
[Test]
public void DynamicRepositoriesShouldNotErrorWithFailedToFindGitDirectory()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var gitVersionOptions = new GitVersionOptions
{
WorkingDirectory = fixture.RepositoryPath,
RepositoryInfo =
{
TargetUrl = "https://github.com/GitTools/GitVersion.git",
TargetBranch = "refs/head/master"
}
};
var gitVersionCalculator = GetGitVersionCalculator(gitVersionOptions, repository: fixture.Repository);
gitPreparer.Prepare();
gitVersionCalculator.CalculateVersionVariables();
}
[Test]
public void GetDotGitDirectoryNoWorktree()
{
using var fixture = new EmptyRepositoryFixture();
var gitVersionOptions = new GitVersionOptions
{
WorkingDirectory = fixture.RepositoryPath
};
sp = GetServiceProvider(gitVersionOptions);
var expectedPath = Path.Combine(fixture.RepositoryPath, ".git");
gitVersionOptions.DotGitDirectory.ShouldBe(expectedPath);
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void GetDotGitDirectoryWorktree()
{
using var fixture = new EmptyRepositoryFixture();
fixture.Repository.MakeACommit();
var worktreePath = Path.Combine(Directory.GetParent(fixture.RepositoryPath).FullName, Guid.NewGuid().ToString());
try
{
// create a branch and a new worktree for it
var repo = new Repository(fixture.RepositoryPath);
repo.Worktrees.Add("worktree", worktreePath, false);
var gitVersionOptions = new GitVersionOptions
{
WorkingDirectory = worktreePath
};
sp = GetServiceProvider(gitVersionOptions);
var expectedPath = Path.Combine(fixture.RepositoryPath, ".git");
gitVersionOptions.DotGitDirectory.ShouldBe(expectedPath);
}
finally
{
DirectoryHelper.DeleteDirectory(worktreePath);
}
}
[Test]
[Category(NoMono)]
[Description(NoMonoDescription)]
public void CalculateVersionFromWorktreeHead()
{
// Setup
using var fixture = new EmptyRepositoryFixture();
var repoDir = new DirectoryInfo(fixture.RepositoryPath);
var worktreePath = Path.Combine(repoDir.Parent.FullName, $"{repoDir.Name}-v1");
fixture.Repository.MakeATaggedCommit("v1.0.0");
var branchV1 = fixture.Repository.CreateBranch("support/1.0");
fixture.Repository.MakeATaggedCommit("v2.0.0");
fixture.Repository.Worktrees.Add(branchV1.CanonicalName, "1.0", worktreePath, false);
using var worktreeFixture = new LocalRepositoryFixture(new Repository(worktreePath));
var gitVersionOptions = new GitVersionOptions { WorkingDirectory = worktreeFixture.RepositoryPath };
var sut = GetGitVersionCalculator(gitVersionOptions);
// Execute
var version = sut.CalculateVersionVariables();
// Verify
version.SemVer.ShouldBe("1.0.0");
var commits = worktreeFixture.Repository.Head.Commits;
version.Sha.ShouldBe(commits.First().Sha);
}
private IGitVersionCalculateTool GetGitVersionCalculator(GitVersionOptions gitVersionOptions, ILog logger = null, IRepository repository = null, IFileSystem fs = null)
{
sp = GetServiceProvider(gitVersionOptions, logger, repository, fs);
fileSystem = sp.GetService<IFileSystem>();
log = sp.GetService<ILog>();
gitVersionCache = sp.GetService<IGitVersionCache>();
gitPreparer = sp.GetService<IGitPreparer>();
return sp.GetService<IGitVersionCalculateTool>();
}
private static IServiceProvider GetServiceProvider(GitVersionOptions gitVersionOptions, ILog log = null, IRepository repository = null, IFileSystem fileSystem = null, IEnvironment environment = null)
{
return ConfigureServices(services =>
{
if (log != null) services.AddSingleton(log);
if (fileSystem != null) services.AddSingleton(fileSystem);
if (repository != null) services.AddSingleton(repository);
if (environment != null) services.AddSingleton(environment);
services.AddSingleton(Options.Create(gitVersionOptions));
});
}
}
}
| |
namespace ASCOM.NexStar
{
partial class SetupDialogForm
{
/// <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()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetupDialogForm));
this.cmdOK = new System.Windows.Forms.Button();
this.cmdCancel = new System.Windows.Forms.Button();
this.picASCOM = new System.Windows.Forms.PictureBox();
this.label_port = new System.Windows.Forms.Label();
this.text_lat = new System.Windows.Forms.TextBox();
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tab_scope = new System.Windows.Forms.TabPage();
this.label4 = new System.Windows.Forms.Label();
this.checkBox1 = new System.Windows.Forms.CheckBox();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.comboBox2 = new System.Windows.Forms.ComboBox();
this.label_align = new System.Windows.Forms.Label();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.text_foc_len = new System.Windows.Forms.TextBox();
this.label_focal_len = new System.Windows.Forms.Label();
this.text_ap_obs = new System.Windows.Forms.TextBox();
this.text_ap_dia = new System.Windows.Forms.TextBox();
this.lable_apature_obs = new System.Windows.Forms.Label();
this.label_apature_dia = new System.Windows.Forms.Label();
this.tab_site = new System.Windows.Forms.TabPage();
this.label3 = new System.Windows.Forms.Label();
this.text_lst = new System.Windows.Forms.TextBox();
this.label_lst = new System.Windows.Forms.Label();
this.lable_evel = new System.Windows.Forms.Label();
this.lable_long = new System.Windows.Forms.Label();
this.lable_lat = new System.Windows.Forms.Label();
this.text_evel = new System.Windows.Forms.TextBox();
this.text_long = new System.Windows.Forms.TextBox();
((System.ComponentModel.ISupportInitialize)(this.picASCOM)).BeginInit();
this.tabControl1.SuspendLayout();
this.tab_scope.SuspendLayout();
this.tab_site.SuspendLayout();
this.SuspendLayout();
//
// cmdOK
//
this.cmdOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdOK.DialogResult = System.Windows.Forms.DialogResult.OK;
this.cmdOK.Location = new System.Drawing.Point(282, 118);
this.cmdOK.Name = "cmdOK";
this.cmdOK.Size = new System.Drawing.Size(59, 24);
this.cmdOK.TabIndex = 9;
this.cmdOK.Text = "OK";
this.cmdOK.UseVisualStyleBackColor = true;
this.cmdOK.Click += new System.EventHandler(this.cmdOK_Click);
//
// cmdCancel
//
this.cmdCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.cmdCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.cmdCancel.Location = new System.Drawing.Point(282, 151);
this.cmdCancel.Name = "cmdCancel";
this.cmdCancel.Size = new System.Drawing.Size(59, 25);
this.cmdCancel.TabIndex = 10;
this.cmdCancel.Text = "Cancel";
this.cmdCancel.UseVisualStyleBackColor = true;
this.cmdCancel.Click += new System.EventHandler(this.cmdCancel_Click);
//
// picASCOM
//
this.picASCOM.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.picASCOM.Cursor = System.Windows.Forms.Cursors.Hand;
this.picASCOM.Image = global::ASCOM.NexStar.Properties.Resources.ASCOM;
this.picASCOM.Location = new System.Drawing.Point(292, 9);
this.picASCOM.Name = "picASCOM";
this.picASCOM.Size = new System.Drawing.Size(48, 56);
this.picASCOM.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize;
this.picASCOM.TabIndex = 3;
this.picASCOM.TabStop = false;
this.picASCOM.Click += new System.EventHandler(this.BrowseToAscom);
this.picASCOM.DoubleClick += new System.EventHandler(this.BrowseToAscom);
//
// label_port
//
this.label_port.AutoSize = true;
this.label_port.Location = new System.Drawing.Point(3, 8);
this.label_port.Name = "label_port";
this.label_port.Size = new System.Drawing.Size(58, 13);
this.label_port.TabIndex = 0;
this.label_port.Text = "Comm Port";
//
// text_lat
//
this.text_lat.Location = new System.Drawing.Point(6, 25);
this.text_lat.Name = "text_lat";
this.text_lat.Size = new System.Drawing.Size(120, 20);
this.text_lat.TabIndex = 1;
this.text_lat.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_lat_KeyPress);
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tab_scope);
this.tabControl1.Controls.Add(this.tab_site);
this.tabControl1.Location = new System.Drawing.Point(6, 9);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(270, 170);
this.tabControl1.TabIndex = 0;
//
// tab_scope
//
this.tab_scope.BackColor = System.Drawing.SystemColors.Control;
this.tab_scope.Controls.Add(this.label4);
this.tab_scope.Controls.Add(this.checkBox1);
this.tab_scope.Controls.Add(this.label2);
this.tab_scope.Controls.Add(this.label1);
this.tab_scope.Controls.Add(this.comboBox2);
this.tab_scope.Controls.Add(this.label_align);
this.tab_scope.Controls.Add(this.comboBox1);
this.tab_scope.Controls.Add(this.text_foc_len);
this.tab_scope.Controls.Add(this.label_focal_len);
this.tab_scope.Controls.Add(this.text_ap_obs);
this.tab_scope.Controls.Add(this.text_ap_dia);
this.tab_scope.Controls.Add(this.lable_apature_obs);
this.tab_scope.Controls.Add(this.label_apature_dia);
this.tab_scope.Controls.Add(this.label_port);
this.tab_scope.Location = new System.Drawing.Point(4, 22);
this.tab_scope.Name = "tab_scope";
this.tab_scope.Padding = new System.Windows.Forms.Padding(3);
this.tab_scope.Size = new System.Drawing.Size(262, 144);
this.tab_scope.TabIndex = 1;
this.tab_scope.Text = "Scope";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(72, 110);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(15, 13);
this.label4.TabIndex = 9;
this.label4.Text = "%";
//
// checkBox1
//
this.checkBox1.AutoSize = true;
this.checkBox1.Location = new System.Drawing.Point(150, 109);
this.checkBox1.Name = "checkBox1";
this.checkBox1.Size = new System.Drawing.Size(83, 17);
this.checkBox1.TabIndex = 8;
this.checkBox1.Text = "Enable PEC";
this.checkBox1.UseVisualStyleBackColor = true;
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(216, 26);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(23, 13);
this.label2.TabIndex = 7;
this.label2.Text = "mm";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(72, 69);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(23, 13);
this.label1.TabIndex = 6;
this.label1.Text = "mm";
//
// comboBox2
//
this.comboBox2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox2.FormattingEnabled = true;
this.comboBox2.Location = new System.Drawing.Point(150, 68);
this.comboBox2.Name = "comboBox2";
this.comboBox2.Size = new System.Drawing.Size(66, 21);
this.comboBox2.TabIndex = 5;
//
// label_align
//
this.label_align.AutoSize = true;
this.label_align.Location = new System.Drawing.Point(148, 51);
this.label_align.Name = "label_align";
this.label_align.Size = new System.Drawing.Size(53, 13);
this.label_align.TabIndex = 0;
this.label_align.Text = "Alignment";
//
// comboBox1
//
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.Location = new System.Drawing.Point(6, 25);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(66, 21);
this.comboBox1.TabIndex = 1;
//
// text_foc_len
//
this.text_foc_len.Location = new System.Drawing.Point(150, 25);
this.text_foc_len.Name = "text_foc_len";
this.text_foc_len.Size = new System.Drawing.Size(66, 20);
this.text_foc_len.TabIndex = 4;
this.text_foc_len.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_foc_len_KeyPress);
//
// label_focal_len
//
this.label_focal_len.AutoSize = true;
this.label_focal_len.Location = new System.Drawing.Point(148, 8);
this.label_focal_len.Name = "label_focal_len";
this.label_focal_len.Size = new System.Drawing.Size(69, 13);
this.label_focal_len.TabIndex = 0;
this.label_focal_len.Text = "Focal Length";
//
// text_ap_obs
//
this.text_ap_obs.Location = new System.Drawing.Point(6, 109);
this.text_ap_obs.Name = "text_ap_obs";
this.text_ap_obs.Size = new System.Drawing.Size(66, 20);
this.text_ap_obs.TabIndex = 3;
this.text_ap_obs.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_ap_obs_KeyPress);
this.text_ap_obs.Leave += new System.EventHandler(this.text_ap_obs_Leave);
//
// text_ap_dia
//
this.text_ap_dia.Location = new System.Drawing.Point(6, 68);
this.text_ap_dia.Name = "text_ap_dia";
this.text_ap_dia.Size = new System.Drawing.Size(66, 20);
this.text_ap_dia.TabIndex = 2;
this.text_ap_dia.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_ap_dia_KeyPress);
this.text_ap_dia.Leave += new System.EventHandler(this.text_ap_dia_Leave);
//
// lable_apature_obs
//
this.lable_apature_obs.AutoSize = true;
this.lable_apature_obs.Location = new System.Drawing.Point(3, 92);
this.lable_apature_obs.Name = "lable_apature_obs";
this.lable_apature_obs.Size = new System.Drawing.Size(61, 13);
this.lable_apature_obs.TabIndex = 0;
this.lable_apature_obs.Text = "Obstruction";
//
// label_apature_dia
//
this.label_apature_dia.AutoSize = true;
this.label_apature_dia.Location = new System.Drawing.Point(3, 51);
this.label_apature_dia.Name = "label_apature_dia";
this.label_apature_dia.Size = new System.Drawing.Size(69, 13);
this.label_apature_dia.TabIndex = 0;
this.label_apature_dia.Text = "Aperture Dia.";
//
// tab_site
//
this.tab_site.BackColor = System.Drawing.SystemColors.Control;
this.tab_site.Controls.Add(this.label3);
this.tab_site.Controls.Add(this.text_lst);
this.tab_site.Controls.Add(this.label_lst);
this.tab_site.Controls.Add(this.lable_evel);
this.tab_site.Controls.Add(this.lable_long);
this.tab_site.Controls.Add(this.lable_lat);
this.tab_site.Controls.Add(this.text_evel);
this.tab_site.Controls.Add(this.text_long);
this.tab_site.Controls.Add(this.text_lat);
this.tab_site.Location = new System.Drawing.Point(4, 22);
this.tab_site.Name = "tab_site";
this.tab_site.Padding = new System.Windows.Forms.Padding(3);
this.tab_site.Size = new System.Drawing.Size(262, 144);
this.tab_site.TabIndex = 0;
this.tab_site.Text = "Site";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(72, 110);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(15, 13);
this.label3.TabIndex = 5;
this.label3.Text = "m";
//
// text_lst
//
this.text_lst.BackColor = System.Drawing.SystemColors.Window;
this.text_lst.Location = new System.Drawing.Point(150, 25);
this.text_lst.Name = "text_lst";
this.text_lst.ReadOnly = true;
this.text_lst.Size = new System.Drawing.Size(60, 20);
this.text_lst.TabIndex = 4;
this.text_lst.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label_lst
//
this.label_lst.AutoSize = true;
this.label_lst.Location = new System.Drawing.Point(148, 8);
this.label_lst.Name = "label_lst";
this.label_lst.Size = new System.Drawing.Size(27, 13);
this.label_lst.TabIndex = 0;
this.label_lst.Text = "LST";
//
// lable_evel
//
this.lable_evel.AutoSize = true;
this.lable_evel.Location = new System.Drawing.Point(3, 92);
this.lable_evel.Name = "lable_evel";
this.lable_evel.Size = new System.Drawing.Size(51, 13);
this.lable_evel.TabIndex = 0;
this.lable_evel.Text = "Elevation";
//
// lable_long
//
this.lable_long.AutoSize = true;
this.lable_long.Location = new System.Drawing.Point(3, 51);
this.lable_long.Name = "lable_long";
this.lable_long.Size = new System.Drawing.Size(54, 13);
this.lable_long.TabIndex = 0;
this.lable_long.Text = "Longitude";
//
// lable_lat
//
this.lable_lat.AutoSize = true;
this.lable_lat.Location = new System.Drawing.Point(3, 8);
this.lable_lat.Margin = new System.Windows.Forms.Padding(0);
this.lable_lat.Name = "lable_lat";
this.lable_lat.Size = new System.Drawing.Size(45, 13);
this.lable_lat.TabIndex = 0;
this.lable_lat.Text = "Latitude";
//
// text_evel
//
this.text_evel.Location = new System.Drawing.Point(6, 109);
this.text_evel.Name = "text_evel";
this.text_evel.Size = new System.Drawing.Size(66, 20);
this.text_evel.TabIndex = 3;
this.text_evel.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_evel_KeyPress);
//
// text_long
//
this.text_long.Location = new System.Drawing.Point(6, 68);
this.text_long.Name = "text_long";
this.text_long.Size = new System.Drawing.Size(120, 20);
this.text_long.TabIndex = 2;
this.text_long.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.text_long_KeyPress);
//
// SetupDialogForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(350, 187);
this.Controls.Add(this.tabControl1);
this.Controls.Add(this.picASCOM);
this.Controls.Add(this.cmdCancel);
this.Controls.Add(this.cmdOK);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "SetupDialogForm";
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "NexStar Setup";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SetupDialogForm_FormClosing);
this.Load += new System.EventHandler(this.SetupDialogForm_Load);
((System.ComponentModel.ISupportInitialize)(this.picASCOM)).EndInit();
this.tabControl1.ResumeLayout(false);
this.tab_scope.ResumeLayout(false);
this.tab_scope.PerformLayout();
this.tab_site.ResumeLayout(false);
this.tab_site.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdOK;
private System.Windows.Forms.Button cmdCancel;
private System.Windows.Forms.PictureBox picASCOM;
private System.Windows.Forms.Label label_port;
private System.Windows.Forms.TextBox text_lat;
private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tab_site;
private System.Windows.Forms.Label lable_evel;
private System.Windows.Forms.Label lable_long;
private System.Windows.Forms.Label lable_lat;
private System.Windows.Forms.TextBox text_evel;
private System.Windows.Forms.TextBox text_long;
private System.Windows.Forms.TabPage tab_scope;
private System.Windows.Forms.TextBox text_foc_len;
private System.Windows.Forms.Label label_focal_len;
private System.Windows.Forms.TextBox text_ap_obs;
private System.Windows.Forms.TextBox text_ap_dia;
private System.Windows.Forms.Label lable_apature_obs;
private System.Windows.Forms.Label label_apature_dia;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.TextBox text_lst;
private System.Windows.Forms.Label label_lst;
private System.Windows.Forms.ComboBox comboBox2;
private System.Windows.Forms.Label label_align;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.CheckBox checkBox1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
}
}
| |
// 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.
//
// Exposes features of the Garbage Collector to managed code.
//
using System;
using System.Threading;
using System.Runtime;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Diagnostics;
using System.Security;
using Internal.Runtime.Augments;
namespace System
{
// !!!!!!!!!!!!!!!!!!!!!!!
// Make sure you change the def in rtu\gc.h if you change this!
public enum GCCollectionMode
{
Default = 0,
Forced = 1,
Optimized = 2
}
public enum GCNotificationStatus
{
Succeeded = 0,
Failed = 1,
Canceled = 2,
Timeout = 3,
NotApplicable = 4
}
internal enum InternalGCCollectionMode
{
NonBlocking = 0x00000001,
Blocking = 0x00000002,
Optimized = 0x00000004,
Compacting = 0x00000008,
}
internal enum StartNoGCRegionStatus
{
Succeeded = 0,
NotEnoughMemory = 1,
AmountTooLarge = 2,
AlreadyInProgress = 3
}
internal enum EndNoGCRegionStatus
{
Succeeded = 0,
NotInProgress = 1,
GCInduced = 2,
AllocationExceeded = 3
}
public static class GC
{
public static int GetGeneration(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
return RuntimeImports.RhGetGeneration(obj);
}
/// <summary>
/// Returns the current generation number of the target
/// of a specified <see cref="System.WeakReference"/>.
/// </summary>
/// <param name="wr">The WeakReference whose target is the object
/// whose generation will be returned</param>
/// <returns>The generation of the target of the WeakReference</returns>
/// <exception cref="ArgumentNullException">The target of the weak reference
/// has already been garbage collected.</exception>
public static int GetGeneration(WeakReference wr)
{
// note - this throws an NRE if given a null weak reference. This isn't
// documented, but it's the behavior of Desktop and CoreCLR.
Object handleRef = RuntimeImports.RhHandleGet(wr.m_handle);
if (handleRef == null)
{
throw new ArgumentNullException(nameof(wr));
}
int result = RuntimeImports.RhGetGeneration(handleRef);
KeepAlive(wr);
return result;
}
// Forces a collection of all generations from 0 through Generation.
public static void Collect(int generation)
{
Collect(generation, GCCollectionMode.Default);
}
// Garbage collect all generations.
public static void Collect()
{
//-1 says to GC all generations.
RuntimeImports.RhCollect(-1, InternalGCCollectionMode.Blocking);
}
public static void Collect(int generation, GCCollectionMode mode)
{
Collect(generation, mode, true);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking)
{
Collect(generation, mode, blocking, false);
}
public static void Collect(int generation, GCCollectionMode mode, bool blocking, bool compacting)
{
if (generation < 0)
{
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
}
if ((mode < GCCollectionMode.Default) || (mode > GCCollectionMode.Optimized))
{
throw new ArgumentOutOfRangeException(nameof(mode), SR.ArgumentOutOfRange_Enum);
}
int iInternalModes = 0;
if (mode == GCCollectionMode.Optimized)
{
iInternalModes |= (int)InternalGCCollectionMode.Optimized;
}
if (compacting)
{
iInternalModes |= (int)InternalGCCollectionMode.Compacting;
}
if (blocking)
{
iInternalModes |= (int)InternalGCCollectionMode.Blocking;
}
else if (!compacting)
{
iInternalModes |= (int)InternalGCCollectionMode.NonBlocking;
}
RuntimeImports.RhCollect(generation, (InternalGCCollectionMode)iInternalModes);
}
/// <summary>
/// Specifies that a garbage collection notification should be raised when conditions are favorable
/// for a full garbage collection and when the collection has been completed.
/// </summary>
/// <param name="maxGenerationThreshold">A number between 1 and 99 that specifies when the notification
/// should be raised based on the objects allocated in Gen 2.</param>
/// <param name="largeObjectHeapThreshold">A number between 1 and 99 that specifies when the notification
/// should be raised based on the objects allocated in the large object heap.</param>
/// <exception cref="ArgumentOutOfRangeException">If either of the two arguments are not between 1 and 99</exception>
/// <exception cref="InvalidOperationException">If Concurrent GC is enabled</exception>"
public static void RegisterForFullGCNotification(int maxGenerationThreshold, int largeObjectHeapThreshold)
{
if (maxGenerationThreshold < 1 || maxGenerationThreshold > 99)
{
throw new ArgumentOutOfRangeException(
nameof(maxGenerationThreshold),
String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99));
}
if (largeObjectHeapThreshold < 1 || largeObjectHeapThreshold > 99)
{
throw new ArgumentOutOfRangeException(
nameof(largeObjectHeapThreshold),
String.Format(SR.ArgumentOutOfRange_Bounds_Lower_Upper, 1, 99));
}
// This is not documented on MSDN, but CoreCLR throws when the GC's
// RegisterForFullGCNotification returns false
if (!RuntimeImports.RhRegisterForFullGCNotification(maxGenerationThreshold, largeObjectHeapThreshold))
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
/// <summary>
/// Returns the status of a registered notification about whether a blocking garbage collection
/// is imminent. May wait indefinitely for a full collection.
/// </summary>
/// <returns>The status of a registered full GC notification</returns>
public static GCNotificationStatus WaitForFullGCApproach()
{
return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(-1);
}
/// <summary>
/// Returns the status of a registered notification about whether a blocking garbage collection
/// is imminent. May wait up to a given timeout for a full collection.
/// </summary>
/// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param>
/// <returns>The status of a registered full GC notification</returns>
public static GCNotificationStatus WaitForFullGCApproach(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
nameof(millisecondsTimeout),
SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCApproach(millisecondsTimeout);
}
/// <summary>
/// Returns the status of a registered notification about whether a blocking garbage collection
/// has completed. May wait indefinitely for a full collection.
/// </summary>
/// <returns>The status of a registered full GC notification</returns>
public static GCNotificationStatus WaitForFullGCComplete()
{
return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(-1);
}
/// <summary>
/// Returns the status of a registered notification about whether a blocking garbage collection
/// has completed. May wait up to a specified timeout for a full collection.
/// </summary>
/// <param name="millisecondsTimeout">The timeout on waiting for a full collection</param>
/// <returns></returns>
public static GCNotificationStatus WaitForFullGCComplete(int millisecondsTimeout)
{
if (millisecondsTimeout < -1)
{
throw new ArgumentOutOfRangeException(
nameof(millisecondsTimeout),
SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
return (GCNotificationStatus)RuntimeImports.RhWaitForFullGCComplete(millisecondsTimeout);
}
/// <summary>
/// Cancels an outstanding full GC notification.
/// </summary>
/// <exception cref="InvalidOperationException">Raised if called
/// with concurrent GC enabled</exception>
public static void CancelFullGCNotification()
{
if (!RuntimeImports.RhCancelFullGCNotification())
{
throw new InvalidOperationException(SR.InvalidOperation_NotWithConcurrentGC);
}
}
/// <summary>
/// Attempts to disallow garbage collection during execution of a critical path.
/// </summary>
/// <param name="totalSize">Disallows garbage collection if a specified amount of
/// of memory is available.</param>
/// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns>
/// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested
/// is too large for the GC to accommodate</exception>
/// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception>
public static bool TryStartNoGCRegion(long totalSize)
{
return StartNoGCRegionWorker(totalSize, false, 0, false);
}
/// <summary>
/// Attempts to disallow garbage collection during execution of a critical path.
/// </summary>
/// <param name="totalSize">Disallows garbage collection if a specified amount of
/// of memory is available.</param>
/// <param name="lohSize">Disallows garbagte collection if a specified amount of
/// large object heap space is available.</param>
/// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns>
/// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested
/// is too large for the GC to accomodate</exception>
/// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception>
public static bool TryStartNoGCRegion(long totalSize, long lohSize)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, false);
}
/// <summary>
/// Attempts to disallow garbage collection during execution of a critical path.
/// </summary>
/// <param name="totalSize">Disallows garbage collection if a specified amount of
/// of memory is available.</param>
/// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC
/// is performed if the requested amount of memory is not available</param>
/// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns>
/// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested
/// is too large for the GC to accomodate</exception>
/// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception>
public static bool TryStartNoGCRegion(long totalSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, false, 0, disallowFullBlockingGC);
}
/// <summary>
/// Attempts to disallow garbage collection during execution of a critical path.
/// </summary>
/// <param name="totalSize">Disallows garbage collection if a specified amount of
/// of memory is available.</param>
/// <param name="lohSize">Disallows garbagte collection if a specified amount of
/// large object heap space is available.</param>
/// <param name="disallowFullBlockingGC">Controls whether or not a full blocking GC
/// is performed if the requested amount of memory is not available</param>
/// <returns>True if the disallowing of garbage collection was successful, False otherwise</returns>
/// <exception cref="ArgumentOutOfRangeException">If the amount of memory requested
/// is too large for the GC to accomodate</exception>
/// <exception cref="InvalidOperationException">If the GC is already in a NoGCRegion</exception>
public static bool TryStartNoGCRegion(long totalSize, long lohSize, bool disallowFullBlockingGC)
{
return StartNoGCRegionWorker(totalSize, true, lohSize, disallowFullBlockingGC);
}
private static bool StartNoGCRegionWorker(long totalSize, bool hasLohSize, long lohSize, bool disallowFullBlockingGC)
{
if (totalSize <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(totalSize),
SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(totalSize)));
}
if (hasLohSize)
{
if (lohSize <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(lohSize),
SR.Format(SR.ArgumentOutOfRange_MustBePositive, nameof(lohSize)));
}
if (lohSize > totalSize)
{
throw new ArgumentOutOfRangeException(nameof(lohSize), SR.ArgumentOutOfRange_NoGCLohSizeGreaterTotalSize);
}
}
StartNoGCRegionStatus status =
(StartNoGCRegionStatus)RuntimeImports.RhStartNoGCRegion(totalSize, hasLohSize, lohSize, disallowFullBlockingGC);
switch (status)
{
case StartNoGCRegionStatus.NotEnoughMemory:
return false;
case StartNoGCRegionStatus.AlreadyInProgress:
throw new InvalidOperationException(SR.InvalidOperationException_AlreadyInNoGCRegion);
case StartNoGCRegionStatus.AmountTooLarge:
throw new ArgumentOutOfRangeException(nameof(totalSize), SR.ArgumentOutOfRangeException_NoGCRegionSizeTooLarge);
}
Debug.Assert(status == StartNoGCRegionStatus.Succeeded);
return true;
}
/// <summary>
/// Exits the current no GC region.
/// </summary>
/// <exception cref="InvalidOperationException">If the GC is not in a no GC region</exception>
/// <exception cref="InvalidOperationException">If the no GC region was exited due to an induced GC</exception>
/// <exception cref="InvalidOperationException">If the no GC region was exited due to memory allocations
/// exceeding the amount given to <see cref="TryStartNoGCRegion(long)"/></exception>
public static void EndNoGCRegion()
{
EndNoGCRegionStatus status = (EndNoGCRegionStatus)RuntimeImports.RhEndNoGCRegion();
if (status == EndNoGCRegionStatus.NotInProgress)
{
throw new InvalidOperationException(
SR.InvalidOperationException_NoGCRegionNotInProgress);
}
else if (status == EndNoGCRegionStatus.GCInduced)
{
throw new InvalidOperationException(
SR.InvalidOperationException_NoGCRegionInduced);
}
else if (status == EndNoGCRegionStatus.AllocationExceeded)
{
throw new InvalidOperationException(
SR.InvalidOperationException_NoGCRegionAllocationExceeded);
}
}
// Block until the next finalization pass is complete.
public static void WaitForPendingFinalizers()
{
RuntimeImports.RhWaitForPendingFinalizers(RuntimeThread.ReentrantWaitsEnabled);
}
public static void SuppressFinalize(Object obj)
{
if (obj == null)
{
throw new ArgumentNullException(nameof(obj));
}
RuntimeImports.RhSuppressFinalize(obj);
}
public static void ReRegisterForFinalize(Object obj)
{
if (obj == null)
throw new ArgumentNullException(nameof(obj));
RuntimeImports.RhReRegisterForFinalize(obj);
}
[Intrinsic]
[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static void KeepAlive(Object obj)
{
}
// Returns the maximum GC generation. Currently assumes only 1 heap.
//
public static int MaxGeneration
{
get { return RuntimeImports.RhGetMaxGcGeneration(); }
}
public static int CollectionCount(int generation)
{
if (generation < 0)
throw new ArgumentOutOfRangeException(nameof(generation), SR.ArgumentOutOfRange_GenericPositive);
return RuntimeImports.RhGetGcCollectionCount(generation, false);
}
// Support for AddMemoryPressure and RemoveMemoryPressure below.
private const uint PressureCount = 4;
#if BIT64
private const uint MinGCMemoryPressureBudget = 4 * 1024 * 1024;
#else
private const uint MinGCMemoryPressureBudget = 3 * 1024 * 1024;
#endif
private const uint MaxGCMemoryPressureRatio = 10;
private static int[] s_gcCounts = new int[] { 0, 0, 0 };
private static long[] s_addPressure = new long[] { 0, 0, 0, 0 };
private static long[] s_removePressure = new long[] { 0, 0, 0, 0 };
private static uint s_iteration = 0;
/// <summary>
/// Resets the pressure accounting after a gen2 GC has occured.
/// </summary>
private static void CheckCollectionCount()
{
if (s_gcCounts[2] != CollectionCount(2))
{
for (int i = 0; i < 3; i++)
{
s_gcCounts[i] = CollectionCount(i);
}
s_iteration++;
uint p = s_iteration % PressureCount;
s_addPressure[p] = 0;
s_removePressure[p] = 0;
}
}
private static long InterlockedAddMemoryPressure(ref long pAugend, long addend)
{
long oldMemValue;
long newMemValue;
do
{
oldMemValue = pAugend;
newMemValue = oldMemValue + addend;
// check for overflow
if (newMemValue < oldMemValue)
{
newMemValue = long.MaxValue;
}
} while (Interlocked.CompareExchange(ref pAugend, newMemValue, oldMemValue) != oldMemValue);
return newMemValue;
}
/// <summary>
/// New AddMemoryPressure implementation (used by RCW and the CLRServicesImpl class)
/// 1. Less sensitive than the original implementation (start budget 3 MB)
/// 2. Focuses more on newly added memory pressure
/// 3. Budget adjusted by effectiveness of last 3 triggered GC (add / remove ratio, max 10x)
/// 4. Budget maxed with 30% of current managed GC size
/// 5. If Gen2 GC is happening naturally, ignore past pressure
///
/// Here's a brief description of the ideal algorithm for Add/Remove memory pressure:
/// Do a GC when (HeapStart is less than X * MemPressureGrowth) where
/// - HeapStart is GC Heap size after doing the last GC
/// - MemPressureGrowth is the net of Add and Remove since the last GC
/// - X is proportional to our guess of the ummanaged memory death rate per GC interval,
/// and would be calculated based on historic data using standard exponential approximation:
/// Xnew = UMDeath/UMTotal * 0.5 + Xprev
/// </summary>
/// <param name="bytesAllocated"></param>
public static void AddMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
#if !BIT64
if (bytesAllocated > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
#endif
CheckCollectionCount();
uint p = s_iteration % PressureCount;
long newMemValue = InterlockedAddMemoryPressure(ref s_addPressure[p], bytesAllocated);
Debug.Assert(PressureCount == 4, "GC.AddMemoryPressure contains unrolled loops which depend on the PressureCount");
if (newMemValue >= MinGCMemoryPressureBudget)
{
long add = s_addPressure[0] + s_addPressure[1] + s_addPressure[2] + s_addPressure[3] - s_addPressure[p];
long rem = s_removePressure[0] + s_removePressure[1] + s_removePressure[2] + s_removePressure[3] - s_removePressure[p];
long budget = MinGCMemoryPressureBudget;
if (s_iteration >= PressureCount) // wait until we have enough data points
{
// Adjust according to effectiveness of GC
// Scale budget according to past m_addPressure / m_remPressure ratio
if (add >= rem * MaxGCMemoryPressureRatio)
{
budget = MinGCMemoryPressureBudget * MaxGCMemoryPressureRatio;
}
else if (add > rem)
{
Debug.Assert(rem != 0);
// Avoid overflow by calculating addPressure / remPressure as fixed point (1 = 1024)
budget = (add * 1024 / rem) * budget / 1024;
}
}
// If still over budget, check current managed heap size
if (newMemValue >= budget)
{
long heapOver3 = RuntimeImports.RhGetCurrentObjSize() / 3;
if (budget < heapOver3) //Max
{
budget = heapOver3;
}
if (newMemValue >= budget)
{
// last check - if we would exceed 20% of GC "duty cycle", do not trigger GC at this time
if ((RuntimeImports.RhGetGCNow() - RuntimeImports.RhGetLastGCStartTime(2)) > (RuntimeImports.RhGetLastGCDuration(2) * 5))
{
RuntimeImports.RhCollect(2, InternalGCCollectionMode.NonBlocking);
CheckCollectionCount();
}
}
}
}
}
public static void RemoveMemoryPressure(long bytesAllocated)
{
if (bytesAllocated <= 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_NeedPosNum);
}
#if !BIT64
if (bytesAllocated > Int32.MaxValue)
{
throw new ArgumentOutOfRangeException(nameof(bytesAllocated),
SR.ArgumentOutOfRange_MustBeNonNegInt32);
}
#endif
CheckCollectionCount();
uint p = s_iteration % PressureCount;
InterlockedAddMemoryPressure(ref s_removePressure[p], bytesAllocated);
}
public static long GetTotalMemory(bool forceFullCollection)
{
long size = RuntimeImports.RhGetGcTotalMemory();
if (forceFullCollection)
{
// If we force a full collection, we will run the finalizers on all
// existing objects and do a collection until the value stabilizes.
// The value is "stable" when either the value is within 5% of the
// previous call to GetTotalMemory, or if we have been sitting
// here for more than x times (we don't want to loop forever here).
int reps = 20; // Number of iterations
long diff;
do
{
GC.WaitForPendingFinalizers();
GC.Collect();
long newSize = RuntimeImports.RhGetGcTotalMemory();
diff = (newSize - size) * 100 / size;
size = newSize;
}
while (reps-- > 0 && !(-5 < diff && diff < 5));
}
return size;
}
public static long GetAllocatedBytesForCurrentThread()
{
return RuntimeImports.RhGetAllocatedBytesForCurrentThread();
}
}
}
| |
// 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.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace System.Security.Cryptography
{
public class CryptoStream : Stream, IDisposable
{
// Member variables
private readonly Stream _stream;
private readonly ICryptoTransform _transform;
private byte[] _inputBuffer; // read from _stream before _Transform
private int _inputBufferIndex;
private int _inputBlockSize;
private byte[] _outputBuffer; // buffered output of _Transform
private int _outputBufferIndex;
private int _outputBlockSize;
private bool _canRead;
private bool _canWrite;
private bool _finalBlockTransformed;
private SemaphoreSlim _lazyAsyncActiveSemaphore;
private readonly bool _leaveOpen;
// Constructors
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
: this(stream, transform, mode, false)
{
}
public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode, bool leaveOpen)
{
_stream = stream;
_transform = transform;
_leaveOpen = leaveOpen;
switch (mode)
{
case CryptoStreamMode.Read:
if (!(_stream.CanRead)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotReadable, nameof(stream)));
_canRead = true;
break;
case CryptoStreamMode.Write:
if (!(_stream.CanWrite)) throw new ArgumentException(SR.Format(SR.Argument_StreamNotWritable, nameof(stream)));
_canWrite = true;
break;
default:
throw new ArgumentException(SR.Argument_InvalidValue);
}
InitializeBuffer();
}
public override bool CanRead
{
get { return _canRead; }
}
// For now, assume we can never seek into the middle of a cryptostream
// and get the state right. This is too strict.
public override bool CanSeek
{
get { return false; }
}
public override bool CanWrite
{
get { return _canWrite; }
}
public override long Length
{
get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); }
}
public override long Position
{
get { throw new NotSupportedException(SR.NotSupported_UnseekableStream); }
set { throw new NotSupportedException(SR.NotSupported_UnseekableStream); }
}
public bool HasFlushedFinalBlock
{
get { return _finalBlockTransformed; }
}
// The flush final block functionality used to be part of close, but that meant you couldn't do something like this:
// MemoryStream ms = new MemoryStream();
// CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
// cs.Write(foo, 0, foo.Length);
// cs.Close();
// and get the encrypted data out of ms, because the cs.Close also closed ms and the data went away.
// so now do this:
// cs.Write(foo, 0, foo.Length);
// cs.FlushFinalBlock() // which can only be called once
// byte[] ciphertext = ms.ToArray();
// cs.Close();
public void FlushFinalBlock() =>
FlushFinalBlockAsync(useAsync: false).GetAwaiter().GetResult();
private async Task FlushFinalBlockAsync(bool useAsync)
{
if (_finalBlockTransformed)
throw new NotSupportedException(SR.Cryptography_CryptoStream_FlushFinalBlockTwice);
_finalBlockTransformed = true;
// Transform and write out the final bytes.
if (_canWrite)
{
Debug.Assert(_outputBufferIndex == 0, "The output index can only ever be non-zero when in read mode.");
byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex);
if (useAsync)
{
await _stream.WriteAsync(new ReadOnlyMemory<byte>(finalBytes)).ConfigureAwait(false);
}
else
{
_stream.Write(finalBytes, 0, finalBytes.Length);
}
}
// If the inner stream is a CryptoStream, then we want to call FlushFinalBlock on it too, otherwise just Flush.
CryptoStream innerCryptoStream = _stream as CryptoStream;
if (innerCryptoStream != null)
{
if (!innerCryptoStream.HasFlushedFinalBlock)
{
await innerCryptoStream.FlushFinalBlockAsync(useAsync).ConfigureAwait(false);
}
}
else
{
if (useAsync)
{
await _stream.FlushAsync().ConfigureAwait(false);
}
else
{
_stream.Flush();
}
}
// zeroize plain text material before returning
if (_inputBuffer != null)
Array.Clear(_inputBuffer, 0, _inputBuffer.Length);
if (_outputBuffer != null)
Array.Clear(_outputBuffer, 0, _outputBuffer.Length);
}
public override void Flush()
{
return;
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overridden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (GetType() != typeof(CryptoStream))
return base.FlushAsync(cancellationToken);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException(SR.NotSupported_UnseekableStream);
}
public override void SetLength(long value)
{
throw new NotSupportedException(SR.NotSupported_UnseekableStream);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckReadArguments(buffer, offset, count);
return ReadAsyncInternal(buffer, offset, count, cancellationToken);
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(ReadAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override int EndRead(IAsyncResult asyncResult) =>
TaskToApm.End<int>(asyncResult);
private async Task<int> ReadAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
SemaphoreSlim semaphore = AsyncActiveSemaphore;
await semaphore.WaitAsync().ForceAsync();
try
{
return await ReadAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); // ConfigureAwait not needed as ForceAsync was used
}
finally
{
semaphore.Release();
}
}
public override int ReadByte()
{
// If we have enough bytes in the buffer such that reading 1 will still leave bytes
// in the buffer, then take the faster path of simply returning the first byte.
// (This unfortunately still involves shifting down the bytes in the buffer, as it
// does in Read. If/when that's fixed for Read, it should be fixed here, too.)
if (_outputBufferIndex > 1)
{
byte b = _outputBuffer[0];
Buffer.BlockCopy(_outputBuffer, 1, _outputBuffer, 0, _outputBufferIndex - 1);
_outputBufferIndex -= 1;
return b;
}
// Otherwise, fall back to the more robust but expensive path of using the base
// Stream.ReadByte to call Read.
return base.ReadByte();
}
public override void WriteByte(byte value)
{
// If there's room in the input buffer such that even with this byte we wouldn't
// complete a block, simply add the byte to the input buffer.
if (_inputBufferIndex + 1 < _inputBlockSize)
{
_inputBuffer[_inputBufferIndex++] = value;
return;
}
// Otherwise, the logic is complicated, so we simply fall back to the base
// implementation that'll use Write.
base.WriteByte(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
CheckReadArguments(buffer, offset, count);
return ReadAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult();
}
private void CheckReadArguments(byte[] buffer, int offset, int count)
{
if (!CanRead)
throw new NotSupportedException(SR.NotSupported_UnreadableStream);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
private async Task<int> ReadAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync)
{
// read <= count bytes from the input stream, transforming as we go.
// Basic idea: first we deliver any bytes we already have in the
// _OutputBuffer, because we know they're good. Then, if asked to deliver
// more bytes, we read & transform a block at a time until either there are
// no bytes ready or we've delivered enough.
int bytesToDeliver = count;
int currentOutputIndex = offset;
if (_outputBufferIndex != 0)
{
// we have some already-transformed bytes in the output buffer
if (_outputBufferIndex <= count)
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, _outputBufferIndex);
bytesToDeliver -= _outputBufferIndex;
currentOutputIndex += _outputBufferIndex;
int toClear = _outputBuffer.Length - _outputBufferIndex;
CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear));
_outputBufferIndex = 0;
}
else
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, offset, count);
Buffer.BlockCopy(_outputBuffer, count, _outputBuffer, 0, _outputBufferIndex - count);
_outputBufferIndex -= count;
int toClear = _outputBuffer.Length - _outputBufferIndex;
CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear));
return (count);
}
}
// _finalBlockTransformed == true implies we're at the end of the input stream
// if we got through the previous if block then _OutputBufferIndex = 0, meaning
// we have no more transformed bytes to give
// so return count-bytesToDeliver, the amount we were able to hand back
// eventually, we'll just always return 0 here because there's no more to read
if (_finalBlockTransformed)
{
return (count - bytesToDeliver);
}
// ok, now loop until we've delivered enough or there's nothing available
int amountRead = 0;
int numOutputBytes;
// OK, see first if it's a multi-block transform and we can speed up things
int blocksToProcess = bytesToDeliver / _outputBlockSize;
if (blocksToProcess > 1 && _transform.CanTransformMultipleBlocks)
{
int numWholeBlocksInBytes = blocksToProcess * _inputBlockSize;
byte[] tempInputBuffer = ArrayPool<byte>.Shared.Rent(numWholeBlocksInBytes);
byte[] tempOutputBuffer = null;
try
{
amountRead = useAsync ?
await _stream.ReadAsync(new Memory<byte>(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex), cancellationToken) : // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread
_stream.Read(tempInputBuffer, _inputBufferIndex, numWholeBlocksInBytes - _inputBufferIndex);
int totalInput = _inputBufferIndex + amountRead;
// If there's still less than a block, copy the new data into the hold buffer and move to the slow read.
if (totalInput < _inputBlockSize)
{
Buffer.BlockCopy(tempInputBuffer, _inputBufferIndex, _inputBuffer, _inputBufferIndex, amountRead);
_inputBufferIndex = totalInput;
}
else
{
// Copy any held data into tempInputBuffer now that we know we're proceeding
Buffer.BlockCopy(_inputBuffer, 0, tempInputBuffer, 0, _inputBufferIndex);
CryptographicOperations.ZeroMemory(new Span<byte>(_inputBuffer, 0, _inputBufferIndex));
amountRead += _inputBufferIndex;
_inputBufferIndex = 0;
// Make amountRead an integral multiple of _InputBlockSize
int numWholeReadBlocks = amountRead / _inputBlockSize;
int numWholeReadBlocksInBytes = numWholeReadBlocks * _inputBlockSize;
int numIgnoredBytes = amountRead - numWholeReadBlocksInBytes;
if (numIgnoredBytes != 0)
{
_inputBufferIndex = numIgnoredBytes;
Buffer.BlockCopy(tempInputBuffer, numWholeReadBlocksInBytes, _inputBuffer, 0, numIgnoredBytes);
}
tempOutputBuffer = ArrayPool<byte>.Shared.Rent(numWholeReadBlocks * _outputBlockSize);
numOutputBytes = _transform.TransformBlock(tempInputBuffer, 0, numWholeReadBlocksInBytes, tempOutputBuffer, 0);
Buffer.BlockCopy(tempOutputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
// Clear what was written while we know how much that was
CryptographicOperations.ZeroMemory(new Span<byte>(tempOutputBuffer, 0, numOutputBytes));
ArrayPool<byte>.Shared.Return(tempOutputBuffer);
tempOutputBuffer = null;
bytesToDeliver -= numOutputBytes;
currentOutputIndex += numOutputBytes;
}
}
finally
{
// If we rented and then an exception happened we don't know how much was written to,
// clear the whole thing and return it.
if (tempOutputBuffer != null)
{
CryptographicOperations.ZeroMemory(tempOutputBuffer);
ArrayPool<byte>.Shared.Return(tempOutputBuffer);
tempOutputBuffer = null;
}
CryptographicOperations.ZeroMemory(new Span<byte>(tempInputBuffer, 0, numWholeBlocksInBytes));
ArrayPool<byte>.Shared.Return(tempInputBuffer);
tempInputBuffer = null;
}
}
// try to fill _InputBuffer so we have something to transform
while (bytesToDeliver > 0)
{
while (_inputBufferIndex < _inputBlockSize)
{
amountRead = useAsync ?
await _stream.ReadAsync(new Memory<byte>(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex), cancellationToken) : // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread
_stream.Read(_inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex);
// first, check to see if we're at the end of the input stream
if (amountRead == 0) goto ProcessFinalBlock;
_inputBufferIndex += amountRead;
}
numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0);
_inputBufferIndex = 0;
if (bytesToDeliver >= numOutputBytes)
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, numOutputBytes);
CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, 0, numOutputBytes));
currentOutputIndex += numOutputBytes;
bytesToDeliver -= numOutputBytes;
}
else
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_outputBufferIndex = numOutputBytes - bytesToDeliver;
Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex);
int toClear = _outputBuffer.Length - _outputBufferIndex;
CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear));
return count;
}
}
return count;
ProcessFinalBlock:
// if so, then call TransformFinalBlock to get whatever is left
byte[] finalBytes = _transform.TransformFinalBlock(_inputBuffer, 0, _inputBufferIndex);
// now, since _OutputBufferIndex must be 0 if we're in the while loop at this point,
// reset it to be what we just got back
_outputBuffer = finalBytes;
_outputBufferIndex = finalBytes.Length;
// set the fact that we've transformed the final block
_finalBlockTransformed = true;
// now, return either everything we just got or just what's asked for, whichever is smaller
if (bytesToDeliver < _outputBufferIndex)
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, bytesToDeliver);
_outputBufferIndex -= bytesToDeliver;
Buffer.BlockCopy(_outputBuffer, bytesToDeliver, _outputBuffer, 0, _outputBufferIndex);
int toClear = _outputBuffer.Length - _outputBufferIndex;
CryptographicOperations.ZeroMemory(new Span<byte>(_outputBuffer, _outputBufferIndex, toClear));
return (count);
}
else
{
Buffer.BlockCopy(_outputBuffer, 0, buffer, currentOutputIndex, _outputBufferIndex);
bytesToDeliver -= _outputBufferIndex;
_outputBufferIndex = 0;
CryptographicOperations.ZeroMemory(_outputBuffer);
return (count - bytesToDeliver);
}
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
CheckWriteArguments(buffer, offset, count);
return WriteAsyncInternal(buffer, offset, count, cancellationToken);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) =>
TaskToApm.Begin(WriteAsync(buffer, offset, count, CancellationToken.None), callback, state);
public override void EndWrite(IAsyncResult asyncResult) =>
TaskToApm.End(asyncResult);
private async Task WriteAsyncInternal(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// To avoid a race with a stream's position pointer & generating race
// conditions with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
SemaphoreSlim semaphore = AsyncActiveSemaphore;
await semaphore.WaitAsync().ForceAsync();
try
{
await WriteAsyncCore(buffer, offset, count, cancellationToken, useAsync: true); // ConfigureAwait not needed due to earlier ForceAsync
}
finally
{
semaphore.Release();
}
}
public override void Write(byte[] buffer, int offset, int count)
{
CheckWriteArguments(buffer, offset, count);
WriteAsyncCore(buffer, offset, count, default(CancellationToken), useAsync: false).GetAwaiter().GetResult();
}
private void CheckWriteArguments(byte[] buffer, int offset, int count)
{
if (!CanWrite)
throw new NotSupportedException(SR.NotSupported_UnwritableStream);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
}
private async Task WriteAsyncCore(byte[] buffer, int offset, int count, CancellationToken cancellationToken, bool useAsync)
{
// write <= count bytes to the output stream, transforming as we go.
// Basic idea: using bytes in the _InputBuffer first, make whole blocks,
// transform them, and write them out. Cache any remaining bytes in the _InputBuffer.
int bytesToWrite = count;
int currentInputIndex = offset;
// if we have some bytes in the _InputBuffer, we have to deal with those first,
// so let's try to make an entire block out of it
if (_inputBufferIndex > 0)
{
if (count >= _inputBlockSize - _inputBufferIndex)
{
// we have enough to transform at least a block, so fill the input block
Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, _inputBlockSize - _inputBufferIndex);
currentInputIndex += (_inputBlockSize - _inputBufferIndex);
bytesToWrite -= (_inputBlockSize - _inputBufferIndex);
_inputBufferIndex = _inputBlockSize;
// Transform the block and write it out
}
else
{
// not enough to transform a block, so just copy the bytes into the _InputBuffer
// and return
Buffer.BlockCopy(buffer, offset, _inputBuffer, _inputBufferIndex, count);
_inputBufferIndex += count;
return;
}
}
Debug.Assert(_outputBufferIndex == 0, "The output index can only ever be non-zero when in read mode.");
// At this point, either the _InputBuffer is full, empty, or we've already returned.
// If full, let's process it -- we now know the _OutputBuffer is empty
int numOutputBytes;
if (_inputBufferIndex == _inputBlockSize)
{
numOutputBytes = _transform.TransformBlock(_inputBuffer, 0, _inputBlockSize, _outputBuffer, 0);
// write out the bytes we just got
if (useAsync)
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_outputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread
else
_stream.Write(_outputBuffer, 0, numOutputBytes);
// reset the _InputBuffer
_inputBufferIndex = 0;
}
while (bytesToWrite > 0)
{
if (bytesToWrite >= _inputBlockSize)
{
// We have at least an entire block's worth to transform
int numWholeBlocks = bytesToWrite / _inputBlockSize;
// If the transform will handle multiple blocks at once, do that
if (_transform.CanTransformMultipleBlocks && numWholeBlocks > 1)
{
int numWholeBlocksInBytes = numWholeBlocks * _inputBlockSize;
byte[] tempOutputBuffer = ArrayPool<byte>.Shared.Rent(numWholeBlocks * _outputBlockSize);
numOutputBytes = 0;
try
{
numOutputBytes =
_transform.TransformBlock(buffer, currentInputIndex, numWholeBlocksInBytes, tempOutputBuffer, 0);
if (useAsync)
{
await _stream.WriteAsync(new ReadOnlyMemory<byte>(tempOutputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread
}
else
{
_stream.Write(tempOutputBuffer, 0, numOutputBytes);
}
currentInputIndex += numWholeBlocksInBytes;
bytesToWrite -= numWholeBlocksInBytes;
}
finally
{
CryptographicOperations.ZeroMemory(new Span<byte>(tempOutputBuffer, 0, numOutputBytes));
ArrayPool<byte>.Shared.Return(tempOutputBuffer);
tempOutputBuffer = null;
}
}
else
{
// do it the slow way
numOutputBytes = _transform.TransformBlock(buffer, currentInputIndex, _inputBlockSize, _outputBuffer, 0);
if (useAsync)
await _stream.WriteAsync(new ReadOnlyMemory<byte>(_outputBuffer, 0, numOutputBytes), cancellationToken); // ConfigureAwait not needed, as useAsync is only true if we're already on a TP thread
else
_stream.Write(_outputBuffer, 0, numOutputBytes);
currentInputIndex += _inputBlockSize;
bytesToWrite -= _inputBlockSize;
}
}
else
{
// In this case, we don't have an entire block's worth left, so store it up in the
// input buffer, which by now must be empty.
Buffer.BlockCopy(buffer, currentInputIndex, _inputBuffer, 0, bytesToWrite);
_inputBufferIndex += bytesToWrite;
return;
}
}
return;
}
public void Clear()
{
Close();
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (!_finalBlockTransformed)
{
FlushFinalBlock();
}
if (!_leaveOpen)
{
_stream.Dispose();
}
}
}
finally
{
try
{
// Ensure we don't try to transform the final block again if we get disposed twice
// since it's null after this
_finalBlockTransformed = true;
// we need to clear all the internal buffers
if (_inputBuffer != null)
Array.Clear(_inputBuffer, 0, _inputBuffer.Length);
if (_outputBuffer != null)
Array.Clear(_outputBuffer, 0, _outputBuffer.Length);
_inputBuffer = null;
_outputBuffer = null;
_canRead = false;
_canWrite = false;
}
finally
{
base.Dispose(disposing);
}
}
}
public override ValueTask DisposeAsync()
{
return GetType() != typeof(CryptoStream) ?
base.DisposeAsync() :
DisposeAsyncCore();
}
private async ValueTask DisposeAsyncCore()
{
// Same logic as in Dispose, but with async counterparts
try
{
if (!_finalBlockTransformed)
{
await FlushFinalBlockAsync(useAsync: true).ConfigureAwait(false);
}
if (!_leaveOpen)
{
await _stream.DisposeAsync().ConfigureAwait(false);
}
}
finally
{
// Ensure we don't try to transform the final block again if we get disposed twice
// since it's null after this
_finalBlockTransformed = true;
// we need to clear all the internal buffers
if (_inputBuffer != null)
{
Array.Clear(_inputBuffer, 0, _inputBuffer.Length);
}
if (_outputBuffer != null)
{
Array.Clear(_outputBuffer, 0, _outputBuffer.Length);
}
_inputBuffer = null;
_outputBuffer = null;
_canRead = false;
_canWrite = false;
}
}
// Private methods
private void InitializeBuffer()
{
if (_transform != null)
{
_inputBlockSize = _transform.InputBlockSize;
_inputBuffer = new byte[_inputBlockSize];
_outputBlockSize = _transform.OutputBlockSize;
_outputBuffer = new byte[_outputBlockSize];
}
}
private SemaphoreSlim AsyncActiveSemaphore
{
get
{
// Lazily-initialize _lazyAsyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _lazyAsyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
}
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
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 WebsitePanel.EnterpriseServer;
using WebsitePanel.Providers.Database;
namespace WebsitePanel.Portal
{
public partial class SqlEditUser : WebsitePanelModuleBase
{
SqlUser item = null;
protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Visible = (PanelRequest.ItemID > 0);
BindItem();
}
private void BindDatabases(int packageId)
{
try
{
SqlDatabase[] databases = ES.Services.DatabaseServers.GetSqlDatabases(packageId,
SqlDatabases.GetDatabasesGroupName(Settings), false);
dlDatabases.DataSource = databases;
dlDatabases.DataBind();
}
catch (Exception ex)
{
ShowErrorMessage("SQL_GET_DATABASE", ex);
return;
}
}
private void BindItem()
{
string policyName = (SqlDatabases.GetDatabasesGroupName(Settings).ToLower().StartsWith("mssql"))
? UserSettings.MSSQL_POLICY : UserSettings.MYSQL_POLICY;
try
{
if (!IsPostBack)
{
// load item if required
if (PanelRequest.ItemID > 0)
{
// existing item
try
{
item = ES.Services.DatabaseServers.GetSqlUser(PanelRequest.ItemID);
}
catch (Exception ex)
{
ShowErrorMessage("SQL_GET_USER", ex);
return;
}
if (item != null)
{
// save package info
ViewState["PackageId"] = item.PackageId;
usernameControl.SetPackagePolicy(item.PackageId, policyName, "UserNamePolicy");
passwordControl.SetPackagePolicy(item.PackageId, policyName, "UserPasswordPolicy");
BindDatabases(item.PackageId);
}
else
RedirectToBrowsePage();
}
else
{
// new item
ViewState["PackageId"] = PanelSecurity.PackageId;
usernameControl.SetPackagePolicy(PanelSecurity.PackageId, policyName, "UserNamePolicy");
passwordControl.SetPackagePolicy(PanelSecurity.PackageId, policyName, "UserPasswordPolicy");
BindDatabases(PanelSecurity.PackageId);
}
}
// load provider control
LoadProviderControl((int)ViewState["PackageId"], SqlDatabases.GetDatabasesGroupName(Settings),
providerControl, "EditUser.ascx");
IDatabaseEditUserControl ctrl = (IDatabaseEditUserControl)providerControl.Controls[0];
ctrl.InitControl(SqlDatabases.GetDatabasesGroupName(Settings));
if (!IsPostBack)
{
// bind item to controls
if (item != null)
{
// bind item to controls
usernameControl.Text = item.Name;
usernameControl.EditMode = true;
passwordControl.EditMode = true;
foreach (string database in item.Databases)
{
foreach (ListItem li in dlDatabases.Items)
{
if (String.Compare(database, li.Value, true) == 0)
{
li.Selected = true;
break;
}
}
}
// other controls
ctrl.BindItem(item);
}
}
}
catch
{
ShowWarningMessage("INIT_SERVICE_ITEM_FORM");
DisableFormControls(this, btnCancel);
return;
}
}
private void SaveItem()
{
if (!Page.IsValid)
return;
// get form data
SqlUser item = new SqlUser();
item.Id = PanelRequest.ItemID;
item.PackageId = PanelSecurity.PackageId;
item.Name = usernameControl.Text;
item.Password = passwordControl.Password;
List<string> databases = new List<string>();
foreach (ListItem li in dlDatabases.Items)
{
if (li.Selected)
databases.Add(li.Value);
}
item.Databases = databases.ToArray();
// get other props
IDatabaseEditUserControl ctrl = (IDatabaseEditUserControl)providerControl.Controls[0];
ctrl.SaveItem(item);
if (PanelRequest.ItemID == 0)
{
// new item
try
{
int result = ES.Services.DatabaseServers.AddSqlUser(item, SqlDatabases.GetDatabasesGroupName(Settings));
// Show an error message if the operation has failed to complete
if (result < 0)
{
ShowResultMessageWithContactForm(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("SQL_ADD_USER", ex);
return;
}
}
else
{
// existing item
try
{
int result = ES.Services.DatabaseServers.UpdateSqlUser(item);
// Show an error message if the operation has failed to complete
if (result < 0)
{
ShowResultMessageWithContactForm(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("SQL_UPDATE_USER", ex);
return;
}
}
// return
RedirectSpaceHomePage();
}
private void DeleteItem()
{
// delete
try
{
int result = ES.Services.DatabaseServers.DeleteSqlUser(PanelRequest.ItemID);
// Show an error message if the operation has failed to complete
if (result < 0)
{
ShowResultMessageWithContactForm(result);
return;
}
}
catch (Exception ex)
{
ShowErrorMessage("SQL_DELETE_USER", ex);
return;
}
// return
RedirectSpaceHomePage();
}
protected void btnSave_Click(object sender, EventArgs e)
{
SaveItem();
}
protected void btnCancel_Click(object sender, EventArgs e)
{
RedirectSpaceHomePage();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
DeleteItem();
}
}
}
| |
// 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;
namespace System.Linq.Expressions
{
/// <summary>
/// Strongly-typed and parameterized exception factory.
/// </summary>
internal static partial class Error
{
/// <summary>
/// ArgumentException with message like "reducible nodes must override Expression.Reduce()"
/// </summary>
internal static Exception ReducibleMustOverrideReduce()
{
return new ArgumentException(Strings.ReducibleMustOverrideReduce);
}
/// <summary>
/// ArgumentException with message like "node cannot reduce to itself or null"
/// </summary>
internal static Exception MustReduceToDifferent()
{
return new ArgumentException(Strings.MustReduceToDifferent);
}
/// <summary>
/// ArgumentException with message like "cannot assign from the reduced node type to the original node type"
/// </summary>
internal static Exception ReducedNotCompatible()
{
return new ArgumentException(Strings.ReducedNotCompatible);
}
/// <summary>
/// ArgumentException with message like "Setter must have parameters."
/// </summary>
internal static Exception SetterHasNoParams()
{
return new ArgumentException(Strings.SetterHasNoParams);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a managed pointer type."
/// </summary>
internal static Exception PropertyCannotHaveRefType()
{
return new ArgumentException(Strings.PropertyCannotHaveRefType);
}
/// <summary>
/// ArgumentException with message like "Indexing parameters of getter and setter must match."
/// </summary>
internal static Exception IndexesOfSetGetMustMatch()
{
return new ArgumentException(Strings.IndexesOfSetGetMustMatch);
}
/// <summary>
/// ArgumentException with message like "Accessor method should not have VarArgs."
/// </summary>
internal static Exception AccessorsCannotHaveVarArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveVarArgs);
}
/// <summary>
/// ArgumentException with message like "Accessor indexes cannot be passed ByRef."
/// </summary>
internal static Exception AccessorsCannotHaveByRefArgs()
{
return new ArgumentException(Strings.AccessorsCannotHaveByRefArgs);
}
/// <summary>
/// ArgumentException with message like "Bounds count cannot be less than 1"
/// </summary>
internal static Exception BoundsCannotBeLessThanOne()
{
return new ArgumentException(Strings.BoundsCannotBeLessThanOne);
}
/// <summary>
/// ArgumentException with message like "type must not be ByRef"
/// </summary>
internal static Exception TypeMustNotBeByRef()
{
return new ArgumentException(Strings.TypeMustNotBeByRef);
}
/// <summary>
/// ArgumentException with message like "Type doesn't have constructor with a given signature"
/// </summary>
internal static Exception TypeDoesNotHaveConstructorForTheSignature()
{
return new ArgumentException(Strings.TypeDoesNotHaveConstructorForTheSignature);
}
/// <summary>
/// ArgumentException with message like "Setter should have void type."
/// </summary>
internal static Exception SetterMustBeVoid()
{
return new ArgumentException(Strings.SetterMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Property type must match the value type of setter"
/// </summary>
internal static Exception PropertyTyepMustMatchSetter()
{
return new ArgumentException(Strings.PropertyTyepMustMatchSetter);
}
/// <summary>
/// ArgumentException with message like "Both accessors must be static."
/// </summary>
internal static Exception BothAccessorsMustBeStatic()
{
return new ArgumentException(Strings.BothAccessorsMustBeStatic);
}
/// <summary>
/// ArgumentException with message like "Static method requires null instance, non-static method requires non-null instance."
/// </summary>
internal static Exception OnlyStaticMethodsHaveNullInstance()
{
return new ArgumentException(Strings.OnlyStaticMethodsHaveNullInstance);
}
/// <summary>
/// ArgumentException with message like "Property cannot have a void type."
/// </summary>
internal static Exception PropertyTypeCannotBeVoid()
{
return new ArgumentException(Strings.PropertyTypeCannotBeVoid);
}
/// <summary>
/// ArgumentException with message like "Can only unbox from an object or interface type to a value type."
/// </summary>
internal static Exception InvalidUnboxType()
{
return new ArgumentException(Strings.InvalidUnboxType);
}
/// <summary>
/// ArgumentException with message like "Argument must not have a value type."
/// </summary>
internal static Exception ArgumentMustNotHaveValueType()
{
return new ArgumentException(Strings.ArgumentMustNotHaveValueType);
}
/// <summary>
/// ArgumentException with message like "must be reducible node"
/// </summary>
internal static Exception MustBeReducible()
{
return new ArgumentException(Strings.MustBeReducible);
}
/// <summary>
/// ArgumentException with message like "Default body must be supplied if case bodies are not System.Void."
/// </summary>
internal static Exception DefaultBodyMustBeSupplied()
{
return new ArgumentException(Strings.DefaultBodyMustBeSupplied);
}
/// <summary>
/// ArgumentException with message like "MethodBuilder does not have a valid TypeBuilder"
/// </summary>
internal static Exception MethodBuilderDoesNotHaveTypeBuilder()
{
return new ArgumentException(Strings.MethodBuilderDoesNotHaveTypeBuilder);
}
/// <summary>
/// ArgumentException with message like "Label type must be System.Void if an expression is not supplied"
/// </summary>
internal static Exception LabelMustBeVoidOrHaveExpression()
{
return new ArgumentException(Strings.LabelMustBeVoidOrHaveExpression);
}
/// <summary>
/// ArgumentException with message like "Type must be System.Void for this label argument"
/// </summary>
internal static Exception LabelTypeMustBeVoid()
{
return new ArgumentException(Strings.LabelTypeMustBeVoid);
}
/// <summary>
/// ArgumentException with message like "Quoted expression must be a lambda"
/// </summary>
internal static Exception QuotedExpressionMustBeLambda()
{
return new ArgumentException(Strings.QuotedExpressionMustBeLambda);
}
/// <summary>
/// ArgumentException with message like "Variable '{0}' uses unsupported type '{1}'. Reference types are not supported for variables."
/// </summary>
internal static Exception VariableMustNotBeByRef(object p0, object p1)
{
return new ArgumentException(Strings.VariableMustNotBeByRef(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Found duplicate parameter '{0}'. Each ParameterExpression in the list must be a unique object."
/// </summary>
internal static Exception DuplicateVariable(object p0)
{
return new ArgumentException(Strings.DuplicateVariable(p0));
}
/// <summary>
/// ArgumentException with message like "Start and End must be well ordered"
/// </summary>
internal static Exception StartEndMustBeOrdered()
{
return new ArgumentException(Strings.StartEndMustBeOrdered);
}
/// <summary>
/// ArgumentException with message like "fault cannot be used with catch or finally clauses"
/// </summary>
internal static Exception FaultCannotHaveCatchOrFinally()
{
return new ArgumentException(Strings.FaultCannotHaveCatchOrFinally);
}
/// <summary>
/// ArgumentException with message like "try must have at least one catch, finally, or fault clause"
/// </summary>
internal static Exception TryMustHaveCatchFinallyOrFault()
{
return new ArgumentException(Strings.TryMustHaveCatchFinallyOrFault);
}
/// <summary>
/// ArgumentException with message like "Body of catch must have the same type as body of try."
/// </summary>
internal static Exception BodyOfCatchMustHaveSameTypeAsBodyOfTry()
{
return new ArgumentException(Strings.BodyOfCatchMustHaveSameTypeAsBodyOfTry);
}
/// <summary>
/// InvalidOperationException with message like "Extension node must override the property {0}."
/// </summary>
internal static Exception ExtensionNodeMustOverrideProperty(object p0)
{
return new InvalidOperationException(Strings.ExtensionNodeMustOverrideProperty(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must be static."
/// </summary>
internal static Exception UserDefinedOperatorMustBeStatic(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustBeStatic(p0));
}
/// <summary>
/// ArgumentException with message like "User-defined operator method '{0}' must not be void."
/// </summary>
internal static Exception UserDefinedOperatorMustNotBeVoid(object p0)
{
return new ArgumentException(Strings.UserDefinedOperatorMustNotBeVoid(p0));
}
/// <summary>
/// InvalidOperationException with message like "No coercion operator is defined between types '{0}' and '{1}'."
/// </summary>
internal static Exception CoercionOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.CoercionOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The unary operator {0} is not defined for the type '{1}'."
/// </summary>
internal static Exception UnaryOperatorNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.UnaryOperatorNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The binary operator {0} is not defined for the types '{1}' and '{2}'."
/// </summary>
internal static Exception BinaryOperatorNotDefined(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.BinaryOperatorNotDefined(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Reference equality is not defined for the types '{0}' and '{1}'."
/// </summary>
internal static Exception ReferenceEqualityNotDefined(object p0, object p1)
{
return new InvalidOperationException(Strings.ReferenceEqualityNotDefined(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The operands for operator '{0}' do not match the parameters of method '{1}'."
/// </summary>
internal static Exception OperandTypesDoNotMatchParameters(object p0, object p1)
{
return new InvalidOperationException(Strings.OperandTypesDoNotMatchParameters(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "The return type of overload method for operator '{0}' does not match the parameter type of conversion method '{1}'."
/// </summary>
internal static Exception OverloadOperatorTypeDoesNotMatchConversionType(object p0, object p1)
{
return new InvalidOperationException(Strings.OverloadOperatorTypeDoesNotMatchConversionType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Conversion is not supported for arithmetic types without operator overloading."
/// </summary>
internal static Exception ConversionIsNotSupportedForArithmeticTypes()
{
return new InvalidOperationException(Strings.ConversionIsNotSupportedForArithmeticTypes);
}
/// <summary>
/// ArgumentException with message like "Argument must be array"
/// </summary>
internal static Exception ArgumentMustBeArray()
{
return new ArgumentException(Strings.ArgumentMustBeArray);
}
/// <summary>
/// ArgumentException with message like "Argument must be boolean"
/// </summary>
internal static Exception ArgumentMustBeBoolean()
{
return new ArgumentException(Strings.ArgumentMustBeBoolean);
}
/// <summary>
/// ArgumentException with message like "The user-defined equality method '{0}' must return a boolean value."
/// </summary>
internal static Exception EqualityMustReturnBoolean(object p0)
{
return new ArgumentException(Strings.EqualityMustReturnBoolean(p0));
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo or PropertyInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfo()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfo);
}
/// <summary>
/// ArgumentException with message like "Argument must be either a FieldInfo, PropertyInfo or MethodInfo"
/// </summary>
internal static Exception ArgumentMustBeFieldInfoOrPropertyInfoOrMethod()
{
return new ArgumentException(Strings.ArgumentMustBeFieldInfoOrPropertyInfoOrMethod);
}
/// <summary>
/// ArgumentException with message like "Argument must be an instance member"
/// </summary>
internal static Exception ArgumentMustBeInstanceMember()
{
return new ArgumentException(Strings.ArgumentMustBeInstanceMember);
}
/// <summary>
/// ArgumentException with message like "Argument must be of an integer type"
/// </summary>
internal static Exception ArgumentMustBeInteger()
{
return new ArgumentException(Strings.ArgumentMustBeInteger);
}
/// <summary>
/// ArgumentException with message like "Argument for array index must be of type Int32"
/// </summary>
internal static Exception ArgumentMustBeArrayIndexType()
{
return new ArgumentException(Strings.ArgumentMustBeArrayIndexType);
}
/// <summary>
/// ArgumentException with message like "Argument must be single dimensional array type"
/// </summary>
internal static Exception ArgumentMustBeSingleDimensionalArrayType()
{
return new ArgumentException(Strings.ArgumentMustBeSingleDimensionalArrayType);
}
/// <summary>
/// ArgumentException with message like "Argument types do not match"
/// </summary>
internal static Exception ArgumentTypesMustMatch()
{
return new ArgumentException(Strings.ArgumentTypesMustMatch);
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize elements of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeElementThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeElementThroughProperty(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot auto initialize members of value type through property '{0}', use assignment instead"
/// </summary>
internal static Exception CannotAutoInitializeValueTypeMemberThroughProperty(object p0)
{
return new InvalidOperationException(Strings.CannotAutoInitializeValueTypeMemberThroughProperty(p0));
}
/// <summary>
/// ArgumentException with message like "The type used in TypeAs Expression must be of reference or nullable type, {0} is neither"
/// </summary>
internal static Exception IncorrectTypeForTypeAs(object p0)
{
return new ArgumentException(Strings.IncorrectTypeForTypeAs(p0));
}
/// <summary>
/// InvalidOperationException with message like "Coalesce used with type that cannot be null"
/// </summary>
internal static Exception CoalesceUsedOnNonNullType()
{
return new InvalidOperationException(Strings.CoalesceUsedOnNonNullType);
}
/// <summary>
/// InvalidOperationException with message like "An expression of type '{0}' cannot be used to initialize an array of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeCannotInitializeArrayType(object p0, object p1)
{
return new InvalidOperationException(Strings.ExpressionTypeCannotInitializeArrayType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for constructor parameter of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchConstructorParameter(object p0, object p1)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchConstructorParameter(p0, p1);
}
/// <summary>
/// ArgumentException with message like " Argument type '{0}' does not match the corresponding member type '{1}'"
/// </summary>
internal static Exception ArgumentTypeDoesNotMatchMember(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentTypeDoesNotMatchMember(p0, p1));
}
/// <summary>
/// ArgumentException with message like " The member '{0}' is not declared on type '{1}' being created"
/// </summary>
internal static Exception ArgumentMemberNotDeclOnType(object p0, object p1)
{
return new ArgumentException(Strings.ArgumentMemberNotDeclOnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}' of method '{2}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchMethodParameter(object p0, object p1, object p2)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchMethodParameter(p0, p1, p2);
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for parameter of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchParameter(object p0, object p1)
{
return Dynamic.Utils.Error.ExpressionTypeDoesNotMatchParameter(p0, p1);
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for return type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchReturn(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchReturn(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for assignment to type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchAssignment(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchAssignment(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be used for label of type '{1}'"
/// </summary>
internal static Exception ExpressionTypeDoesNotMatchLabel(object p0, object p1)
{
return new ArgumentException(Strings.ExpressionTypeDoesNotMatchLabel(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Expression of type '{0}' cannot be invoked"
/// </summary>
internal static Exception ExpressionTypeNotInvocable(object p0)
{
return new ArgumentException(Strings.ExpressionTypeNotInvocable(p0));
}
/// <summary>
/// ArgumentException with message like "Field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception FieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.FieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance field '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstanceFieldNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstanceFieldNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Field '{0}.{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception FieldInfoNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.FieldInfoNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Incorrect number of indexes"
/// </summary>
internal static Exception IncorrectNumberOfIndexes()
{
return new ArgumentException(Strings.IncorrectNumberOfIndexes);
}
/// <summary>
/// InvalidOperationException with message like "Incorrect number of arguments supplied for lambda invocation"
/// </summary>
internal static Exception IncorrectNumberOfLambdaArguments()
{
return Dynamic.Utils.Error.IncorrectNumberOfLambdaArguments();
}
/// <summary>
/// ArgumentException with message like "Incorrect number of parameters supplied for lambda declaration"
/// </summary>
internal static Exception IncorrectNumberOfLambdaDeclarationParameters()
{
return new ArgumentException(Strings.IncorrectNumberOfLambdaDeclarationParameters);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments supplied for call to method '{0}'"
/// </summary>
internal static Exception IncorrectNumberOfMethodCallArguments(object p0)
{
return Dynamic.Utils.Error.IncorrectNumberOfMethodCallArguments(p0);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for constructor"
/// </summary>
internal static Exception IncorrectNumberOfConstructorArguments()
{
return Dynamic.Utils.Error.IncorrectNumberOfConstructorArguments();
}
/// <summary>
/// ArgumentException with message like " Incorrect number of members for constructor"
/// </summary>
internal static Exception IncorrectNumberOfMembersForGivenConstructor()
{
return new ArgumentException(Strings.IncorrectNumberOfMembersForGivenConstructor);
}
/// <summary>
/// ArgumentException with message like "Incorrect number of arguments for the given members "
/// </summary>
internal static Exception IncorrectNumberOfArgumentsForMembers()
{
return new ArgumentException(Strings.IncorrectNumberOfArgumentsForMembers);
}
/// <summary>
/// ArgumentException with message like "Lambda type parameter must be derived from System.Delegate"
/// </summary>
internal static Exception LambdaTypeMustBeDerivedFromSystemDelegate()
{
return new ArgumentException(Strings.LambdaTypeMustBeDerivedFromSystemDelegate);
}
/// <summary>
/// ArgumentException with message like "Member '{0}' not field or property"
/// </summary>
internal static Exception MemberNotFieldOrProperty(object p0)
{
return new ArgumentException(Strings.MemberNotFieldOrProperty(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} contains generic parameters"
/// </summary>
internal static Exception MethodContainsGenericParameters(object p0)
{
return new ArgumentException(Strings.MethodContainsGenericParameters(p0));
}
/// <summary>
/// ArgumentException with message like "Method {0} is a generic method definition"
/// </summary>
internal static Exception MethodIsGeneric(object p0)
{
return new ArgumentException(Strings.MethodIsGeneric(p0));
}
/// <summary>
/// ArgumentException with message like "The method '{0}.{1}' is not a property accessor"
/// </summary>
internal static Exception MethodNotPropertyAccessor(object p0, object p1)
{
return new ArgumentException(Strings.MethodNotPropertyAccessor(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveGetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveGetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'set' accessor"
/// </summary>
internal static Exception PropertyDoesNotHaveSetter(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveSetter(p0));
}
/// <summary>
/// ArgumentException with message like "The property '{0}' has no 'get' or 'set' accessors"
/// </summary>
internal static Exception PropertyDoesNotHaveAccessor(object p0)
{
return new ArgumentException(Strings.PropertyDoesNotHaveAccessor(p0));
}
/// <summary>
/// ArgumentException with message like "'{0}' is not a member of type '{1}'"
/// </summary>
internal static Exception NotAMemberOfType(object p0, object p1)
{
return new ArgumentException(Strings.NotAMemberOfType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForType(p0, p1));
}
/// <summary>
/// PlatformNotSupportedException with message like "The instruction '{0}' is not supported for nullable type '{1}'"
/// </summary>
internal static Exception ExpressionNotSupportedForNullableType(object p0, object p1)
{
return new PlatformNotSupportedException(Strings.ExpressionNotSupportedForNullableType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "ParameterExpression of type '{0}' cannot be used for delegate parameter of type '{1}'"
/// </summary>
internal static Exception ParameterExpressionNotValidAsDelegate(object p0, object p1)
{
return new ArgumentException(Strings.ParameterExpressionNotValidAsDelegate(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception PropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.PropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}' that takes no argument is not defined for type '{1}'"
/// </summary>
internal static Exception InstancePropertyWithoutParameterNotDefinedForType(object p0, object p1)
{
return new ArgumentException(Strings.InstancePropertyWithoutParameterNotDefinedForType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Instance property '{0}{1}' is not defined for type '{2}'"
/// </summary>
internal static Exception InstancePropertyWithSpecifiedParametersNotDefinedForType(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstancePropertyWithSpecifiedParametersNotDefinedForType(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Method '{0}' declared on type '{1}' cannot be called with instance of type '{2}'"
/// </summary>
internal static Exception InstanceAndMethodTypeMismatch(object p0, object p1, object p2)
{
return new ArgumentException(Strings.InstanceAndMethodTypeMismatch(p0, p1, p2));
}
/// <summary>
/// ArgumentException with message like "Type '{0}' does not have a default constructor"
/// </summary>
internal static Exception TypeMissingDefaultConstructor(object p0)
{
return new ArgumentException(Strings.TypeMissingDefaultConstructor(p0));
}
/// <summary>
/// ArgumentException with message like "List initializers must contain at least one initializer"
/// </summary>
internal static Exception ListInitializerWithZeroMembers()
{
return new ArgumentException(Strings.ListInitializerWithZeroMembers);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be named 'Add'"
/// </summary>
internal static Exception ElementInitializerMethodNotAdd()
{
return new ArgumentException(Strings.ElementInitializerMethodNotAdd);
}
/// <summary>
/// ArgumentException with message like "Parameter '{0}' of element initializer method '{1}' must not be a pass by reference parameter"
/// </summary>
internal static Exception ElementInitializerMethodNoRefOutParam(object p0, object p1)
{
return new ArgumentException(Strings.ElementInitializerMethodNoRefOutParam(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Element initializer method must have at least 1 parameter"
/// </summary>
internal static Exception ElementInitializerMethodWithZeroArgs()
{
return new ArgumentException(Strings.ElementInitializerMethodWithZeroArgs);
}
/// <summary>
/// ArgumentException with message like "Element initializer method must be an instance method"
/// </summary>
internal static Exception ElementInitializerMethodStatic()
{
return new ArgumentException(Strings.ElementInitializerMethodStatic);
}
/// <summary>
/// ArgumentException with message like "Type '{0}' is not IEnumerable"
/// </summary>
internal static Exception TypeNotIEnumerable(object p0)
{
return new ArgumentException(Strings.TypeNotIEnumerable(p0));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected coalesce operator."
/// </summary>
internal static Exception UnexpectedCoalesceOperator()
{
return new InvalidOperationException(Strings.UnexpectedCoalesceOperator);
}
/// <summary>
/// InvalidOperationException with message like "Cannot cast from type '{0}' to type '{1}"
/// </summary>
internal static Exception InvalidCast(object p0, object p1)
{
return new InvalidOperationException(Strings.InvalidCast(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Unhandled binary: {0}"
/// </summary>
internal static Exception UnhandledBinary(object p0)
{
return new ArgumentException(Strings.UnhandledBinary(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled binding "
/// </summary>
internal static Exception UnhandledBinding()
{
return new ArgumentException(Strings.UnhandledBinding);
}
/// <summary>
/// ArgumentException with message like "Unhandled Binding Type: {0}"
/// </summary>
internal static Exception UnhandledBindingType(object p0)
{
return new ArgumentException(Strings.UnhandledBindingType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled convert: {0}"
/// </summary>
internal static Exception UnhandledConvert(object p0)
{
return new ArgumentException(Strings.UnhandledConvert(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled Expression Type: {0}"
/// </summary>
internal static Exception UnhandledExpressionType(object p0)
{
return new ArgumentException(Strings.UnhandledExpressionType(p0));
}
/// <summary>
/// ArgumentException with message like "Unhandled unary: {0}"
/// </summary>
internal static Exception UnhandledUnary(object p0)
{
return new ArgumentException(Strings.UnhandledUnary(p0));
}
/// <summary>
/// ArgumentException with message like "Unknown binding type"
/// </summary>
internal static Exception UnknownBindingType()
{
return new ArgumentException(Strings.UnknownBindingType);
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have identical parameter and return types."
/// </summary>
internal static Exception UserDefinedOpMustHaveConsistentTypes(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveConsistentTypes(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must return the same type as its parameter or a derived type."
/// </summary>
internal static Exception UserDefinedOpMustHaveValidReturnType(object p0, object p1)
{
return new ArgumentException(Strings.UserDefinedOpMustHaveValidReturnType(p0, p1));
}
/// <summary>
/// ArgumentException with message like "The user-defined operator method '{1}' for operator '{0}' must have associated boolean True and False operators."
/// </summary>
internal static Exception LogicalOperatorMustHaveBooleanOperators(object p0, object p1)
{
return new ArgumentException(Strings.LogicalOperatorMustHaveBooleanOperators(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' exists on type '{1}'."
/// </summary>
internal static Exception MethodDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "No generic method '{0}' on type '{1}' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic. "
/// </summary>
internal static Exception GenericMethodWithArgsDoesNotExistOnType(object p0, object p1)
{
return new InvalidOperationException(Strings.GenericMethodWithArgsDoesNotExistOnType(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one method '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception MethodWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.MethodWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "More than one property '{0}' on type '{1}' is compatible with the supplied arguments."
/// </summary>
internal static Exception PropertyWithMoreThanOneMatch(object p0, object p1)
{
return new InvalidOperationException(Strings.PropertyWithMoreThanOneMatch(p0, p1));
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of a Func type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForFunc()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForFunc);
}
/// <summary>
/// ArgumentException with message like "An incorrect number of type args were specified for the declaration of an Action type."
/// </summary>
internal static Exception IncorrectNumberOfTypeArgsForAction()
{
return new ArgumentException(Strings.IncorrectNumberOfTypeArgsForAction);
}
/// <summary>
/// ArgumentException with message like "Argument type cannot be System.Void."
/// </summary>
internal static Exception ArgumentCannotBeOfTypeVoid()
{
return new ArgumentException(Strings.ArgumentCannotBeOfTypeVoid);
}
/// <summary>
/// ArgumentException with message like "Invalid operation: '{0}'"
/// </summary>
internal static Exception InvalidOperation(object p0)
{
return new ArgumentException(Strings.InvalidOperation(p0));
}
/// <summary>
/// ArgumentOutOfRangeException with message like "{0} must be greater than or equal to {1}"
/// </summary>
internal static Exception OutOfRange(object p0, object p1)
{
return new ArgumentOutOfRangeException(Strings.OutOfRange(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Cannot redefine label '{0}' in an inner block."
/// </summary>
internal static Exception LabelTargetAlreadyDefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetAlreadyDefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to undefined label '{0}'."
/// </summary>
internal static Exception LabelTargetUndefined(object p0)
{
return new InvalidOperationException(Strings.LabelTargetUndefined(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a finally block."
/// </summary>
internal static Exception ControlCannotLeaveFinally()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFinally);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot leave a filter test."
/// </summary>
internal static Exception ControlCannotLeaveFilterTest()
{
return new InvalidOperationException(Strings.ControlCannotLeaveFilterTest);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to ambiguous label '{0}'."
/// </summary>
internal static Exception AmbiguousJump(object p0)
{
return new InvalidOperationException(Strings.AmbiguousJump(p0));
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter a try block."
/// </summary>
internal static Exception ControlCannotEnterTry()
{
return new InvalidOperationException(Strings.ControlCannotEnterTry);
}
/// <summary>
/// InvalidOperationException with message like "Control cannot enter an expression--only statements can be jumped into."
/// </summary>
internal static Exception ControlCannotEnterExpression()
{
return new InvalidOperationException(Strings.ControlCannotEnterExpression);
}
/// <summary>
/// InvalidOperationException with message like "Cannot jump to non-local label '{0}' with a value. Only jumps to labels defined in outer blocks can pass values."
/// </summary>
internal static Exception NonLocalJumpWithValue(object p0)
{
return new InvalidOperationException(Strings.NonLocalJumpWithValue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Extension should have been reduced."
/// </summary>
internal static Exception ExtensionNotReduced()
{
return new InvalidOperationException(Strings.ExtensionNotReduced);
}
/// <summary>
/// InvalidOperationException with message like "CompileToMethod cannot compile constant '{0}' because it is a non-trivial value, such as a live object. Instead, create an expression tree that can construct this value."
/// </summary>
internal static Exception CannotCompileConstant(object p0)
{
return new InvalidOperationException(Strings.CannotCompileConstant(p0));
}
/// <summary>
/// NotSupportedException with message like "Dynamic expressions are not supported by CompileToMethod. Instead, create an expression tree that uses System.Runtime.CompilerServices.CallSite."
/// </summary>
internal static Exception CannotCompileDynamic()
{
return new NotSupportedException(Strings.CannotCompileDynamic);
}
/// <summary>
/// InvalidOperationException with message like "Invalid lvalue for assignment: {0}."
/// </summary>
internal static Exception InvalidLvalue(object p0)
{
return new InvalidOperationException(Strings.InvalidLvalue(p0));
}
/// <summary>
/// InvalidOperationException with message like "Invalid member type: {0}."
/// </summary>
internal static Exception InvalidMemberType(object p0)
{
return new InvalidOperationException(Strings.InvalidMemberType(p0));
}
/// <summary>
/// InvalidOperationException with message like "unknown lift type: '{0}'."
/// </summary>
internal static Exception UnknownLiftType(object p0)
{
return new InvalidOperationException(Strings.UnknownLiftType(p0));
}
/// <summary>
/// ArgumentException with message like "Invalid output directory."
/// </summary>
internal static Exception InvalidOutputDir()
{
return new ArgumentException(Strings.InvalidOutputDir);
}
/// <summary>
/// ArgumentException with message like "Invalid assembly name or file extension."
/// </summary>
internal static Exception InvalidAsmNameOrExtension()
{
return new ArgumentException(Strings.InvalidAsmNameOrExtension);
}
/// <summary>
/// ArgumentException with message like "Cannot create instance of {0} because it contains generic parameters"
/// </summary>
internal static Exception IllegalNewGenericParams(object p0)
{
return new ArgumentException(Strings.IllegalNewGenericParams(p0));
}
/// <summary>
/// InvalidOperationException with message like "variable '{0}' of type '{1}' referenced from scope '{2}', but it is not defined"
/// </summary>
internal static Exception UndefinedVariable(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.UndefinedVariable(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Cannot close over byref parameter '{0}' referenced in lambda '{1}'"
/// </summary>
internal static Exception CannotCloseOverByRef(object p0, object p1)
{
return new InvalidOperationException(Strings.CannotCloseOverByRef(p0, p1));
}
/// <summary>
/// InvalidOperationException with message like "Unexpected VarArgs call to method '{0}'"
/// </summary>
internal static Exception UnexpectedVarArgsCall(object p0)
{
return new InvalidOperationException(Strings.UnexpectedVarArgsCall(p0));
}
/// <summary>
/// InvalidOperationException with message like "Rethrow statement is valid only inside a Catch block."
/// </summary>
internal static Exception RethrowRequiresCatch()
{
return new InvalidOperationException(Strings.RethrowRequiresCatch);
}
/// <summary>
/// InvalidOperationException with message like "Try expression is not allowed inside a filter body."
/// </summary>
internal static Exception TryNotAllowedInFilter()
{
return new InvalidOperationException(Strings.TryNotAllowedInFilter);
}
/// <summary>
/// InvalidOperationException with message like "When called from '{0}', rewriting a node of type '{1}' must return a non-null value of the same type. Alternatively, override '{2}' and change it to not visit children of this type."
/// </summary>
internal static Exception MustRewriteToSameNode(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteToSameNode(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewriting child expression from type '{0}' to type '{1}' is not allowed, because it would change the meaning of the operation. If this is intentional, override '{2}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteChildToSameType(object p0, object p1, object p2)
{
return new InvalidOperationException(Strings.MustRewriteChildToSameType(p0, p1, p2));
}
/// <summary>
/// InvalidOperationException with message like "Rewritten expression calls operator method '{0}', but the original node had no operator method. If this is is intentional, override '{1}' and change it to allow this rewrite."
/// </summary>
internal static Exception MustRewriteWithoutMethod(object p0, object p1)
{
return new InvalidOperationException(Strings.MustRewriteWithoutMethod(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as an argument to method '{0}' because it has an argument with by-ref type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForMethodsWithRefArgs(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForMethodsWithRefArgs(p0));
}
/// <summary>
/// NotSupportedException with message like "TryExpression is not supported as a child expression when accessing a member on type '{0}' because it is a value type. Construct the tree so the TryExpression is not nested inside of this expression."
/// </summary>
internal static Exception TryNotSupportedForValueTypeInstances(object p0)
{
return new NotSupportedException(Strings.TryNotSupportedForValueTypeInstances(p0));
}
/// <summary>
/// InvalidOperationException with message like "Dynamic operations can only be performed in homogenous AppDomain."
/// </summary>
internal static Exception HomogenousAppDomainRequired()
{
return new InvalidOperationException(Strings.HomogenousAppDomainRequired);
}
/// <summary>
/// ArgumentException with message like "Test value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception TestValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.TestValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// ArgumentException with message like "Switch value of type '{0}' cannot be used for the comparison method parameter of type '{1}'"
/// </summary>
internal static Exception SwitchValueTypeDoesNotMatchComparisonMethodParameter(object p0, object p1)
{
return new ArgumentException(Strings.SwitchValueTypeDoesNotMatchComparisonMethodParameter(p0, p1));
}
/// <summary>
/// NotSupportedException with message like "DebugInfoGenerator created by CreatePdbGenerator can only be used with LambdaExpression.CompileToMethod."
/// </summary>
internal static Exception PdbGeneratorNeedsExpressionCompiler()
{
return new NotSupportedException(Strings.PdbGeneratorNeedsExpressionCompiler);
}
/// <summary>
/// The exception that is thrown when a null reference (Nothing in Visual Basic) is passed to a method that does not accept it as a valid argument.
/// </summary>
internal static Exception ArgumentNull(string paramName)
{
return new ArgumentNullException(paramName);
}
/// <summary>
/// The exception that is thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.
/// </summary>
internal static Exception ArgumentOutOfRange(string paramName)
{
return new ArgumentOutOfRangeException(paramName);
}
/// <summary>
/// The exception that is thrown when an invoked method is not supported, or when there is an attempt to read, seek, or write to a stream that does not support the invoked functionality.
/// </summary>
internal static Exception NotSupported()
{
return new NotSupportedException();
}
#if FEATURE_COMPILE
/// <summary>
/// NotImplementedException with message like "The operator '{0}' is not implemented for type '{1}'"
/// </summary>
internal static Exception OperatorNotImplementedForType(object p0, object p1)
{
return NotImplemented.ByDesignWithMessage(Strings.OperatorNotImplementedForType(p0, p1));
}
#endif
/// <summary>
/// ArgumentException with message like "The constructor should not be static"
/// </summary>
internal static Exception NonStaticConstructorRequired()
{
return new ArgumentException(Strings.NonStaticConstructorRequired);
}
/// <summary>
/// InvalidOperationException with message like "Can't compile a NewExpression with a constructor declared on an abstract class"
/// </summary>
internal static Exception NonAbstractConstructorRequired()
{
return new InvalidOperationException(Strings.NonAbstractConstructorRequired);
}
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Contoso.Provisioning.Hybrid
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#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.
/******************************************************************************
* 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 MultiplyHighUInt16()
{
var test = new SimpleBinaryOpTest__MultiplyHighUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Avx.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Avx.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Avx.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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__MultiplyHighUInt16
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(UInt16[] inArray1, UInt16[] inArray2, UInt16[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<UInt16>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<UInt16>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt16>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<UInt16, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<UInt16, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector256<UInt16> _fld1;
public Vector256<UInt16> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref testStruct._fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__MultiplyHighUInt16 testClass)
{
var result = Avx2.MultiplyHigh(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__MultiplyHighUInt16 testClass)
{
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<UInt16>>() / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[Op1ElementCount];
private static UInt16[] _data2 = new UInt16[Op2ElementCount];
private static Vector256<UInt16> _clsVar1;
private static Vector256<UInt16> _clsVar2;
private Vector256<UInt16> _fld1;
private Vector256<UInt16> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__MultiplyHighUInt16()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
}
public SimpleBinaryOpTest__MultiplyHighUInt16()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetUInt16(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetUInt16(); }
_dataTable = new DataTable(_data1, _data2, new UInt16[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.MultiplyHigh(
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.MultiplyHigh(
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyHigh), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyHigh), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.MultiplyHigh), new Type[] { typeof(Vector256<UInt16>), typeof(Vector256<UInt16>) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr)),
Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.MultiplyHigh(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector256<UInt16>* pClsVar1 = &_clsVar1)
fixed (Vector256<UInt16>* pClsVar2 = &_clsVar2)
{
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(pClsVar1)),
Avx.LoadVector256((UInt16*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector256<UInt16>>(_dataTable.inArray2Ptr);
var result = Avx2.MultiplyHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Avx.LoadVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.MultiplyHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray1Ptr));
var op2 = Avx.LoadAlignedVector256((UInt16*)(_dataTable.inArray2Ptr));
var result = Avx2.MultiplyHigh(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__MultiplyHighUInt16();
var result = Avx2.MultiplyHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__MultiplyHighUInt16();
fixed (Vector256<UInt16>* pFld1 = &test._fld1)
fixed (Vector256<UInt16>* pFld2 = &test._fld2)
{
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.MultiplyHigh(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector256<UInt16>* pFld1 = &_fld1)
fixed (Vector256<UInt16>* pFld2 = &_fld2)
{
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(pFld1)),
Avx.LoadVector256((UInt16*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.MultiplyHigh(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Avx2.MultiplyHigh(
Avx.LoadVector256((UInt16*)(&test._fld1)),
Avx.LoadVector256((UInt16*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt16> op1, Vector256<UInt16> op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[Op1ElementCount];
UInt16[] inArray2 = new UInt16[Op2ElementCount];
UInt16[] outArray = new UInt16[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<UInt16>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != BitConverter.ToUInt16(BitConverter.GetBytes((((uint)(left[0])) * right[0]) >> 16), 0))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != BitConverter.ToUInt16(BitConverter.GetBytes((((uint)(left[i])) * right[i]) >> 16), 0))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.MultiplyHigh)}<UInt16>(Vector256<UInt16>, Vector256<UInt16>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmEmergencyProcedures.
/// </summary>
public partial class frmBudOrgsD : System.Web.UI.Page
{
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
protected System.Web.UI.WebControls.Label Label2;
protected System.Web.UI.WebControls.Button btnAddTemp;
public SqlConnection epsDbConn=new SqlConnection(strDB);
int I;
int Rules = 0;
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
Load_Procedures();
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.processCommand);
}
#endregion
private void Load_Procedures()
{
if (Session["BRS"].ToString() == "0")
{
DataGrid1.Columns[2].HeaderText = "Budget";
DataGrid1.Columns[3].Visible=false;
DataGrid1.Columns[4].Visible=false;
DataGrid1.Columns[5].Visible=false;
DataGrid1.Columns[6].Visible=false;
DataGrid1.Columns[7].Visible = false;
lblContents.Text="The above budget has been distributed to the following"
+ " internal units and/or external organizations. You may"
+ " add or remove organizations from this list using the buttons"
+ " titled 'Add' and 'Remove' respectively.";
}
else if (Session["Status"].ToString() == "Formulation")
{
DataGrid1.Columns[3].Visible=false;
DataGrid1.Columns[4].Visible=false;
DataGrid1.Columns[5].Visible=false;
lblContents.Text="The above budget will be distributed to the following"
+ " internal units and/or external organizations. You may"
+ " add or remove organizations from this list using the buttons"
+ " titled 'Add' and 'Remove' respectively.";
}
else if (Session["Status"].ToString() == "Open")
{
DataGrid1.Columns[2].Visible=false;
lblContents.Text="The above budget has been distributed to the following"
+ " internal units and/or external organizations. You may"
+ " add or remove organizations from this list using the buttons"
+ " titled 'Add' and 'Remove' respectively. You may change the current"
+ " budget by adding the amount to be added or reduced in the column titled '+/- Current Budget'.";
}
else
{
lblContents.Text="System Error. Please Contact Administrator.";
}
if (!IsPostBack)
{
lblOrg.Text="Budget Manager: " + Session["OrgName"].ToString();
lblBudAmt.Text="Budget Amount Available: " + Session["BudAmt"].ToString()
+ " " + Session["CurrName"].ToString();
loadData();
lblBud.Text = "Budget Name: " + Session["BudName"].ToString();
}
}
private void loadData ()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_RetrieveBudOrgsD";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@BudgetsId",SqlDbType.Int);
cmd.Parameters["@BudgetsId"].Value=Session["BudgetsId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"BudOrgs");
if (ds.Tables["BudOrgs"].Rows.Count == 0)
{
DataGrid1.Visible=false;
lblContents.Text="The above budget has not yet been distributed. To distribute"
+ " click on 'Add'.";
}
Session["ds"] = ds;
DataGrid1.DataSource=ds;
DataGrid1.DataBind();
assignValues();
}
private void computeBudget()
{
float Change = 0;
float CurrBud = 0;
float CurrBudChange = 0;
float Req = 0;
float DiffBudD = 0;
int ChangeFlag = 0;
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbCurr = (TextBox)(i.Cells[5].FindControl("txtCurr"));
if (i.Cells[4].Text != " ")
{
CurrBud =
CurrBud
+ float.Parse(i.Cells[4].Text, NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign);
}
if (tbCurr.Text != "")
{
Change =
Change
+ float.Parse(tbCurr.Text.ToString(), NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign);
ChangeFlag = ChangeFlag + 1;
}
if (i.Cells[6].Text != "")
{
if (i.Cells[6].Text != " ")
{
Req = Req + float.Parse(i.Cells[6].Text, NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign);
}
}
}
if (ChangeFlag == 0)
{
Exit();
}
else
{
CurrBudChange = CurrBud + Change;
DiffBudD =
float.Parse(Session["BudAmt"].ToString(), NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign)
- CurrBudChange;
lblBudDist.Text="Distributed below " + CurrBudChange.ToString();
if (DiffBudD >= 0)
{
lblDiff.Text = "Undistributed Budget: " + DiffBudD.ToString();
}
else
{
lblDiff.Text = "Overdistributed Budget: " + DiffBudD.ToString();
lblDiff.ForeColor=Color.White;
}
lblReq.Text="Budget Required per Work Program : " + Req.ToString();
}
/* /Check 1
if (CurrBud + Change
>
float.Parse(Session["BudAmt"].ToString(), NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign)
)
{
lblContents.Text = "You may not distribute more than the funds available for this budget."
+ "currbud" + CurrBud.ToString() + "change" + Change.ToString();
Rules = 2;
}
else if (CurrBud + Change > 0)
{
lblContents.Text = "You may not distribute more than the funds available for this budget."
+ "currbud" + CurrBud.ToString() + "change" + Change.ToString();
Rules = 3;
}*/
}
private void assignValues()
{
if (Session["Status"].ToString() != "Open")
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbOrig = (TextBox)(i.Cells[2].FindControl("txtOrig"));
if (Session["Status"].ToString() == "Created")
{
if (i.Cells[3].Text == " ")
{
tbOrig.Text = "";
}
else
{
tbOrig.Text = i.Cells[3].Text;
}
}
}
}
else
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbCurr = (TextBox)(i.Cells[5].FindControl("txtCurr"));
{
if (i.Cells[5].Text == " ")
{
tbCurr.Text = "";
}
else
{
tbCurr.Text = i.Cells[5].Text;
}
}
}
}
}
private void processCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
if (e.CommandName == "Revs")
{
Session["BDOId"] = e.Item.Cells[0].Text;
Session["BDOrgName"] = e.Item.Cells[1].Text;
Session["CurrBAmt"] = e.Item.Cells[4].Text;
Session["ReqBAmt"] = e.Item.Cells[6].Text;
Session["CBORevs"]="frmBudOrgsD";
Response.Redirect (strURL + "frmBORevisions.aspx?");
}
else if (e.CommandName == "Tasks")
{
Session["BDOId"] = e.Item.Cells[0].Text;
Session["MgrId"]=e.Item.Cells[11].Text;
Session["MgrName"] = e.Item.Cells[1].Text;
Session["COrgLocServices"] = "frmBudOrgsD";
Response.Redirect (strURL + "frmOrgLocServices.aspx?");
}
else if (e.CommandName == "Outputs")
{
Session["CPSEPO"] = "frmBudOrgsD";
Session["BDOId"] = e.Item.Cells[0].Text;
Session["BDOrgName"] = e.Item.Cells[1].Text;
//Session["ProcessName"] = e.Item.Cells[1].Text; to be added
//Session["PSEPID"] = e.Item.Cells[0].Text; to be added
Response.Redirect(strURL + "frmPSEPO.aspx?");
}
else if (e.CommandName == "Clients")
{
Session["CPSEPC"] = "frmBudOrgsD";
Session["BOId"] = e.Item.Cells[0].Text;
Session["BDOrgName"] = e.Item.Cells[1].Text;
//Session["ProcessName"] = e.Item.Cells[1].Text;
//Session["PSEPID"] = e.Item.Cells[0].Text;
Response.Redirect(strURL + "frmPSEPClient.aspx?");
}
else if (e.CommandName == "Remove")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_DeleteBudOrgs";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add ("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value=Int32.Parse (e.Item.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
redirectNow();
}
private void redirectNow()
{
Session["CBOSel"]="frmBudOrgsD";
Response.Redirect (strURL + "frmBudOrgsSel.aspx?");
}
private void updateOrigAmt()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbOrigAmt = (TextBox)(i.Cells[2].FindControl("txtOrig"));
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_UpdateBudOrgsAmt";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@OrigAmt", SqlDbType.Decimal);
if (tbOrigAmt.Text != "")
{
cmd.Parameters ["@OrigAmt"].Value=decimal.Parse(tbOrigAmt.Text, NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands);
}
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters ["@Id"].Value=Int32.Parse(i.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
if (Session["BRS"].ToString() == "0")
{
updateOrigAmt();
Exit();
}
else
{
if (btnExit.Text == "OK")
{
{
if (Session["Status"].ToString() == "Open")
{
computeBudget();
if (Rules == 0)
btnExit.Text = "Confirm";
txtDesc.Visible=true;
lblContents.ForeColor=Color.White;
lblContents.Text="Please add reasons for this budget change below, and press 'OK' to confirm"
+ " or 'Cancel' to discard changes";
}
else
{
updateOrigAmt();
Exit();
}
}
}
else
{
updateJournal();
retrieveBOJournals();
Exit();
}
}
}
private void updateJournal()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_UpdateBOJournals";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@Desc", SqlDbType.NVarChar);
if (txtDesc.Text != "")
{
cmd.Parameters ["@Desc"].Value=txtDesc.Text;
}
cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
cmd.Parameters ["@BudgetsId"].Value=Session["BudgetsId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
private void retrieveBOJournals()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_retrieveBOJournalsId";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@BudgetsId", SqlDbType.Decimal);
cmd.Parameters ["@BudgetsId"].Value=Session["BudgetsId"].ToString();
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"BOJ");
if (ds.Tables["BOJ"].Rows.Count == 1)
{
I = Int32.Parse(ds.Tables["BOJ"].Rows[0][0].ToString());
updateBOAmts();
updateCurrAmt(); //This summarizes BOAmts and is done to simplify read queries for reporting
//as well as for loadData() for this form.
}
else
{
lblContents.Text="System Error. Journal entry not created. Please contact System Administrator.";
}
}
private void updateCurrAmt()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbCurrAmt = (TextBox)(i.Cells[5].FindControl("txtCurr"));
{
if (tbCurrAmt.Text !="")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_UpdateBudOrgsCAmt";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@BOId", SqlDbType.Int);
cmd.Parameters ["@BOId"].Value=Int32.Parse(i.Cells[0].Text);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
}
private void updateBOAmts()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tbCurrAmt = (TextBox)(i.Cells[5].FindControl("txtCurr"));
{
if (tbCurrAmt.Text !="")
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.CommandText="fms_UpdateBOAmts";
cmd.Connection=this.epsDbConn;
cmd.Parameters.Add("@BOJournalsId", SqlDbType.Int);
cmd.Parameters ["@BOJournalsId"].Value=I;
cmd.Parameters.Add("@BOId", SqlDbType.Int);
cmd.Parameters ["@BOId"].Value=Int32.Parse(i.Cells[0].Text);
cmd.Parameters.Add("@CurrAmt", SqlDbType.Decimal);
cmd.Parameters ["@CurrAmt"].Value=decimal.Parse(tbCurrAmt.Text, NumberStyles.AllowDecimalPoint|NumberStyles.AllowThousands|NumberStyles.AllowLeadingSign);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
}
private void Exit()
{
Session["MgrName"] = null;
Response.Redirect (strURL + Session["CBudOrgsD"].ToString() + ".aspx?");
}
protected void btnCancel_Click(object sender, System.EventArgs e)
{
Exit();
}
}
}
| |
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 TestAttrIoC.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.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,
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;
}
}
}
| |
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK;
using OpenTK.Graphics;
using osu.Framework.Extensions.Color4Extensions;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Colour;
using osu.Framework.Graphics.Sprites;
using osu.Game.Users;
using osu.Game.Graphics;
using osu.Game.Graphics.Backgrounds;
using osu.Game.Overlays.MedalSplash;
using osu.Framework.Allocation;
using osu.Framework.Audio.Sample;
using osu.Framework.Audio;
using osu.Framework.Graphics.Textures;
using osu.Framework.Input;
using OpenTK.Input;
using System.Linq;
using osu.Framework.Graphics.Shapes;
using System;
using osu.Framework.MathUtils;
namespace osu.Game.Overlays
{
public class MedalOverlay : FocusedOverlayContainer
{
public const float DISC_SIZE = 400;
private const float border_width = 5;
private readonly Medal medal;
private readonly Box background;
private readonly Container backgroundStrip, particleContainer;
private readonly BackgroundStrip leftStrip, rightStrip;
private readonly CircularContainer disc;
private readonly Sprite innerSpin, outerSpin;
private DrawableMedal drawableMedal;
private SampleChannel getSample;
public MedalOverlay(Medal medal)
{
this.medal = medal;
RelativeSizeAxes = Axes.Both;
Children = new Drawable[]
{
background = new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.Black.Opacity(60),
},
outerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(DISC_SIZE + 500),
Alpha = 0f,
},
backgroundStrip = new Container
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.X,
Height = border_width,
Alpha = 0f,
Children = new[]
{
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreRight,
Width = 0.5f,
Padding = new MarginPadding { Right = DISC_SIZE / 2 },
Children = new[]
{
leftStrip = new BackgroundStrip(0f, 1f)
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
},
},
},
new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.CentreLeft,
Width = 0.5f,
Padding = new MarginPadding { Left = DISC_SIZE / 2 },
Children = new[]
{
rightStrip = new BackgroundStrip(1f, 0f),
},
},
},
},
particleContainer = new Container
{
RelativeSizeAxes = Axes.Both,
Alpha = 0f,
},
disc = new CircularContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Alpha = 0f,
Masking = true,
AlwaysPresent = true,
BorderColour = Color4.White,
BorderThickness = border_width,
Size = new Vector2(DISC_SIZE),
Scale = new Vector2(0.8f),
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = OsuColour.FromHex(@"05262f"),
},
new Triangles
{
RelativeSizeAxes = Axes.Both,
TriangleScale = 2,
ColourDark = OsuColour.FromHex(@"04222b"),
ColourLight = OsuColour.FromHex(@"052933"),
},
innerSpin = new Sprite
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
RelativeSizeAxes = Axes.Both,
Size = new Vector2(1.05f),
Alpha = 0.25f,
},
},
},
};
}
[BackgroundDependencyLoader]
private void load(OsuColour colours, TextureStore textures, AudioManager audio)
{
getSample = audio.Sample.Get(@"MedalSplash/medal-get");
innerSpin.Texture = outerSpin.Texture = textures.Get(@"MedalSplash/disc-spin");
disc.EdgeEffect = leftStrip.EdgeEffect = rightStrip.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 50,
};
disc.Add(drawableMedal = new DrawableMedal(medal)
{
Anchor = Anchor.TopCentre,
Origin = Anchor.TopCentre,
RelativeSizeAxes = Axes.Both,
});
}
protected override void LoadComplete()
{
base.LoadComplete();
Show();
}
protected override void Update()
{
base.Update();
particleContainer.Add(new MedalParticle(RNG.Next(0, 359)));
}
protected override bool OnClick(InputState state)
{
dismiss();
return true;
}
protected override void OnFocusLost(InputState state)
{
if (state.Keyboard.Keys.Contains(Key.Escape)) dismiss();
}
private const double initial_duration = 400;
private const double step_duration = 900;
protected override void PopIn()
{
base.PopIn();
this.FadeIn(200);
background.FlashColour(Color4.White.Opacity(0.25f), 400);
getSample.Play();
innerSpin.Spin(20000, RotationDirection.Clockwise);
outerSpin.Spin(40000, RotationDirection.Clockwise);
using (BeginDelayedSequence(200, true))
{
disc.FadeIn(initial_duration)
.ScaleTo(1f, initial_duration * 2, Easing.OutElastic);
particleContainer.FadeIn(initial_duration);
outerSpin.FadeTo(0.1f, initial_duration * 2);
using (BeginDelayedSequence(initial_duration + 200, true))
{
backgroundStrip.FadeIn(step_duration);
leftStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
rightStrip.ResizeWidthTo(1f, step_duration, Easing.OutQuint);
this.Animate().Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Icon;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.MedalUnlocked;
})
.Delay(step_duration).Schedule(() =>
{
if (drawableMedal.State != DisplayState.Full)
drawableMedal.State = DisplayState.Full;
});
}
}
}
protected override void PopOut()
{
base.PopOut();
this.FadeOut(200);
}
private void dismiss()
{
if (drawableMedal.State != DisplayState.Full)
{
// if we haven't yet, play out the animation fully
drawableMedal.State = DisplayState.Full;
FinishTransforms(true);
return;
}
Hide();
Expire();
}
private class BackgroundStrip : Container
{
public BackgroundStrip(float start, float end)
{
RelativeSizeAxes = Axes.Both;
Width = 0f;
Colour = ColourInfo.GradientHorizontal(Color4.White.Opacity(start), Color4.White.Opacity(end));
Masking = true;
Children = new[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = Color4.White,
}
};
}
}
private class MedalParticle : CircularContainer
{
private readonly float direction;
private Vector2 positionForOffset(float offset) => new Vector2((float)(offset * Math.Sin(direction)), (float)(offset * Math.Cos(direction)));
public MedalParticle(float direction)
{
this.direction = direction;
Anchor = Anchor.Centre;
Origin = Anchor.Centre;
Position = positionForOffset(DISC_SIZE / 2);
Masking = true;
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Glow,
Colour = colours.Blue.Opacity(0.5f),
Radius = 5,
};
this.MoveTo(positionForOffset(DISC_SIZE / 2 + 200), 500);
this.FadeOut(500);
Expire();
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
/// Describes the snapshot created from the imported disk.
/// </summary>
public partial class SnapshotDetail
{
private string _description;
private string _deviceName;
private double? _diskImageSize;
private string _format;
private string _progress;
private string _snapshotId;
private string _status;
private string _statusMessage;
private string _url;
private UserBucketDetails _userBucket;
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description for the snapshot.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property DeviceName.
/// <para>
/// The block device mapping for the snapshot.
/// </para>
/// </summary>
public string DeviceName
{
get { return this._deviceName; }
set { this._deviceName = value; }
}
// Check to see if DeviceName property is set
internal bool IsSetDeviceName()
{
return this._deviceName != null;
}
/// <summary>
/// Gets and sets the property DiskImageSize.
/// <para>
/// The size of the disk in the snapshot, in GiB.
/// </para>
/// </summary>
public double DiskImageSize
{
get { return this._diskImageSize.GetValueOrDefault(); }
set { this._diskImageSize = value; }
}
// Check to see if DiskImageSize property is set
internal bool IsSetDiskImageSize()
{
return this._diskImageSize.HasValue;
}
/// <summary>
/// Gets and sets the property Format.
/// <para>
/// The format of the disk image from which the snapshot is created.
/// </para>
/// </summary>
public string Format
{
get { return this._format; }
set { this._format = value; }
}
// Check to see if Format property is set
internal bool IsSetFormat()
{
return this._format != null;
}
/// <summary>
/// Gets and sets the property Progress.
/// <para>
/// The percentage of progress for the task.
/// </para>
/// </summary>
public string Progress
{
get { return this._progress; }
set { this._progress = value; }
}
// Check to see if Progress property is set
internal bool IsSetProgress()
{
return this._progress != null;
}
/// <summary>
/// Gets and sets the property SnapshotId.
/// <para>
/// The snapshot ID of the disk being imported.
/// </para>
/// </summary>
public string SnapshotId
{
get { return this._snapshotId; }
set { this._snapshotId = value; }
}
// Check to see if SnapshotId property is set
internal bool IsSetSnapshotId()
{
return this._snapshotId != null;
}
/// <summary>
/// Gets and sets the property Status.
/// <para>
/// A brief status of the snapshot creation.
/// </para>
/// </summary>
public string Status
{
get { return this._status; }
set { this._status = value; }
}
// Check to see if Status property is set
internal bool IsSetStatus()
{
return this._status != null;
}
/// <summary>
/// Gets and sets the property StatusMessage.
/// <para>
/// A detailed status message for the snapshot creation.
/// </para>
/// </summary>
public string StatusMessage
{
get { return this._statusMessage; }
set { this._statusMessage = value; }
}
// Check to see if StatusMessage property is set
internal bool IsSetStatusMessage()
{
return this._statusMessage != null;
}
/// <summary>
/// Gets and sets the property Url.
/// <para>
/// The URL used to access the disk image.
/// </para>
/// </summary>
public string Url
{
get { return this._url; }
set { this._url = value; }
}
// Check to see if Url property is set
internal bool IsSetUrl()
{
return this._url != null;
}
/// <summary>
/// Gets and sets the property UserBucket.
/// </summary>
public UserBucketDetails UserBucket
{
get { return this._userBucket; }
set { this._userBucket = value; }
}
// Check to see if UserBucket property is set
internal bool IsSetUserBucket()
{
return this._userBucket != null;
}
}
}
| |
/*
Copyright 2012-2022 Marco De Salvo
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 RDFSharp.Model;
using RDFSharp.Semantics.OWL;
using System.Collections.Generic;
namespace RDFSharp.Semantics.SKOS
{
/// <summary>
/// RDFSKOSHelper contains utility methods supporting SKOS modeling and reasoning
/// </summary>
public static class RDFSKOSHelper
{
#region Modeling
#region Initialize
/// <summary>
/// Initializes the given ontology with support for SKOS T-BOX and A-BOX
/// </summary>
public static RDFOntology InitializeSKOS(this RDFOntology ontology)
{
if (ontology != null)
{
ontology.Merge(RDFSKOSOntology.Instance);
ontology.AddStandardAnnotation(RDFSemanticsEnums.RDFOntologyStandardAnnotation.Imports, RDFSKOSOntology.Instance);
}
return ontology;
}
#endregion
#region Relations
#region TopConcept
/// <summary>
/// Adds the given concept to the conceptScheme as top concept of the hierarchy
/// </summary>
public static RDFSKOSConceptScheme AddTopConceptRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
if (conceptScheme != null && concept != null && !conceptScheme.Equals(concept))
{
//Add skos:hasTopConcept relation to the scheme
conceptScheme.Relations.TopConcept.AddEntry(new RDFOntologyTaxonomyEntry(conceptScheme, RDFVocabulary.SKOS.HAS_TOP_CONCEPT.ToRDFOntologyObjectProperty(), concept));
}
return conceptScheme;
}
#endregion
#region Semantic
/// <summary>
/// Adds a 'skos:semanticRelation' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddSemanticRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
//Add skos:semanticRelation relation to the scheme
conceptScheme.Relations.SemanticRelation.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.SEMANTIC_RELATION.ToRDFOntologyObjectProperty(), bConcept));
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:related' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddRelatedRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckRelatedRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:related relations to the scheme
conceptScheme.Relations.Related.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.RELATED.ToRDFOntologyObjectProperty(), bConcept));
conceptScheme.Relations.Related.AddEntry(new RDFOntologyTaxonomyEntry(bConcept, RDFVocabulary.SKOS.RELATED.ToRDFOntologyObjectProperty(), aConcept)
.SetInference(RDFSemanticsEnums.RDFOntologyInferenceType.API));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:broader' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddBroaderRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckBroaderRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:broader relation to the scheme
conceptScheme.Relations.Broader.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.BROADER.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:broaderTransitive' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddBroaderTransitiveRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckBroaderRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:broaderTransitive relation to the scheme
conceptScheme.Relations.BroaderTransitive.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.BROADER_TRANSITIVE.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:narrower' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddNarrowerRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckNarrowerRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:narrower relation to the scheme
conceptScheme.Relations.Narrower.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.NARROWER.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:narrowerTransitive' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddNarrowerTransitiveRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckNarrowerRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:narrowerTransitive relation to the scheme
conceptScheme.Relations.NarrowerTransitive.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.NARROWER_TRANSITIVE.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
#endregion
#region Mapping
/// <summary>
/// Adds a 'skos:mappingRelation' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddMappingRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
//Add skos:mappingRelation relation to the scheme
conceptScheme.Relations.MappingRelation.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.MAPPING_RELATION.ToRDFOntologyObjectProperty(), bConcept));
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:closeMatch' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddCloseMatchRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckCloseOrExactMatchRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:closeMatch relation to the scheme
conceptScheme.Relations.CloseMatch.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.CLOSE_MATCH.ToRDFOntologyObjectProperty(), bConcept));
conceptScheme.Relations.CloseMatch.AddEntry(new RDFOntologyTaxonomyEntry(bConcept, RDFVocabulary.SKOS.CLOSE_MATCH.ToRDFOntologyObjectProperty(), aConcept)
.SetInference(RDFSemanticsEnums.RDFOntologyInferenceType.API));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:exactMatch' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddExactMatchRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckCloseOrExactMatchRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:exactMatch relation to the scheme
conceptScheme.Relations.ExactMatch.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.EXACT_MATCH.ToRDFOntologyObjectProperty(), bConcept));
conceptScheme.Relations.ExactMatch.AddEntry(new RDFOntologyTaxonomyEntry(bConcept, RDFVocabulary.SKOS.EXACT_MATCH.ToRDFOntologyObjectProperty(), aConcept)
.SetInference(RDFSemanticsEnums.RDFOntologyInferenceType.API));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:broadMatch' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddBroadMatchRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckBroaderRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:broadMatch relation to the scheme
conceptScheme.Relations.BroadMatch.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.BROAD_MATCH.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:narrowMatch' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddNarrowMatchRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckNarrowerRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:narrowMatch relation to the scheme
conceptScheme.Relations.NarrowMatch.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.NARROW_MATCH.ToRDFOntologyObjectProperty(), bConcept));
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skos:relatedMatch' relation between the given concepts within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddRelatedMatchAssertion(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
{
if (conceptScheme != null && aConcept != null && bConcept != null && !aConcept.Equals(bConcept))
{
if (RDFSKOSChecker.CheckRelatedRelation(conceptScheme, aConcept, bConcept))
{
//Add skos:relatedMatch relation to the scheme
conceptScheme.Relations.RelatedMatch.AddEntry(new RDFOntologyTaxonomyEntry(aConcept, RDFVocabulary.SKOS.RELATED_MATCH.ToRDFOntologyObjectProperty(), bConcept));
conceptScheme.Relations.RelatedMatch.AddEntry(new RDFOntologyTaxonomyEntry(bConcept, RDFVocabulary.SKOS.RELATED_MATCH.ToRDFOntologyObjectProperty(), aConcept)
.SetInference(RDFSemanticsEnums.RDFOntologyInferenceType.API));
}
}
return conceptScheme;
}
#endregion
#region Notation
/// <summary>
/// Adds the given notation to the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddNotationRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral notationLiteral)
{
if (conceptScheme != null && concept != null && notationLiteral != null)
{
//Add skos:Notation relation to the scheme
conceptScheme.Relations.Notation.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.NOTATION.ToRDFOntologyDatatypeProperty(), notationLiteral));
}
return conceptScheme;
}
#endregion
#region Label
/// <summary>
/// Adds the given label as preferred label of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddPrefLabelRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFSKOSLabel label,
RDFOntologyLiteral prefLabelLiteral)
{
if (conceptScheme != null && concept != null && label != null && prefLabelLiteral != null)
{
//Only plain literals are allowed as skosxl:prefLabel assertions
if (prefLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckPrefLabel(conceptScheme, concept, prefLabelLiteral))
{
//Add prefLabel relation
conceptScheme.Relations.PrefLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.SKOSXL.PREF_LABEL.ToRDFOntologyObjectProperty(), label));
//Add literalForm relation
conceptScheme.Relations.LiteralForm.AddEntry(new RDFOntologyTaxonomyEntry(label, RDFVocabulary.SKOS.SKOSXL.LITERAL_FORM.ToRDFOntologyDatatypeProperty(), prefLabelLiteral));
}
}
}
return conceptScheme;
}
/// <summary>
/// Adds the given label as alternative label of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddAltLabelRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFSKOSLabel label,
RDFOntologyLiteral altLabelLiteral)
{
if (conceptScheme != null && concept != null && label != null && altLabelLiteral != null)
{
//Only plain literals are allowed as skosxl:altLabel assertions
if (altLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckAltLabel(conceptScheme, concept, altLabelLiteral))
{
//Add altLabel relation
conceptScheme.Relations.AltLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.SKOSXL.ALT_LABEL.ToRDFOntologyObjectProperty(), label));
//Add literalForm relation
conceptScheme.Relations.LiteralForm.AddEntry(new RDFOntologyTaxonomyEntry(label, RDFVocabulary.SKOS.SKOSXL.LITERAL_FORM.ToRDFOntologyDatatypeProperty(), altLabelLiteral));
}
}
}
return conceptScheme;
}
/// <summary>
/// Adds the given label as hidden label of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddHiddenLabelRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFSKOSLabel label,
RDFOntologyLiteral hiddenLabelLiteral)
{
if (conceptScheme != null && concept != null && label != null && hiddenLabelLiteral != null)
{
//Only plain literals are allowed as skosxl:hiddenLabel assertions
if (hiddenLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckHiddenLabel(conceptScheme, concept, hiddenLabelLiteral))
{
//Add hiddenLabel relation
conceptScheme.Relations.HiddenLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.SKOSXL.HIDDEN_LABEL.ToRDFOntologyObjectProperty(), label));
//Add literalForm relation
conceptScheme.Relations.LiteralForm.AddEntry(new RDFOntologyTaxonomyEntry(label, RDFVocabulary.SKOS.SKOSXL.LITERAL_FORM.ToRDFOntologyDatatypeProperty(), hiddenLabelLiteral));
}
}
}
return conceptScheme;
}
/// <summary>
/// Adds a 'skosxl:labelRelation' relation between the given labels within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddLabelRelation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSLabel aLabel,
RDFSKOSLabel bLabel)
{
if (conceptScheme != null && aLabel != null && bLabel != null && !aLabel.Equals(bLabel))
{
//Add skosxl:labelRelation relation to the scheme
conceptScheme.Relations.LabelRelation.AddEntry(new RDFOntologyTaxonomyEntry(aLabel, RDFVocabulary.SKOS.SKOSXL.LABEL_RELATION.ToRDFOntologyObjectProperty(), bLabel));
conceptScheme.Relations.LabelRelation.AddEntry(new RDFOntologyTaxonomyEntry(bLabel, RDFVocabulary.SKOS.SKOSXL.LABEL_RELATION.ToRDFOntologyObjectProperty(), aLabel)
.SetInference(RDFSemanticsEnums.RDFOntologyInferenceType.API));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal form of the given label within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddLiteralFormAssertion(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSLabel label,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && label != null && literal != null)
{
//Add literalForm relation
conceptScheme.Relations.LiteralForm.AddEntry(new RDFOntologyTaxonomyEntry(label, RDFVocabulary.SKOS.SKOSXL.LITERAL_FORM.ToRDFOntologyDatatypeProperty(), literal));
}
return conceptScheme;
}
#endregion
#endregion
#region Annotations
#region Lexical Labeling
/// <summary>
/// Adds the given literal as preferred label annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddPrefLabelAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral prefLabelLiteral)
{
if (conceptScheme != null && concept != null && prefLabelLiteral != null)
{
//Only plain literals are allowed as skos:prefLabel annotations
if (prefLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckPrefLabel(conceptScheme, concept, prefLabelLiteral))
{
//Add prefLabel annotation
conceptScheme.Annotations.PrefLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.PREF_LABEL.ToRDFOntologyAnnotationProperty(), prefLabelLiteral));
}
}
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as alternative label annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddAltLabelAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral altLabelLiteral)
{
if (conceptScheme != null && concept != null && altLabelLiteral != null)
{
//Only plain literals are allowed as skos:altLabel annotations
if (altLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckAltLabel(conceptScheme, concept, altLabelLiteral))
{
//Add altLabel annotation
conceptScheme.Annotations.AltLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.ALT_LABEL.ToRDFOntologyAnnotationProperty(), altLabelLiteral));
}
}
}
return conceptScheme;
}
/// <summary>
/// Adds the "concept -> skos:hiddenLabel -> hiddenLabelLiteral" annotation to the concept scheme
/// </summary>
public static RDFSKOSConceptScheme AddHiddenLabelAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral hiddenLabelLiteral)
{
if (conceptScheme != null && concept != null && hiddenLabelLiteral != null)
{
//Only plain literals are allowed as skos:hiddenLabel annotations
if (hiddenLabelLiteral.Value is RDFPlainLiteral)
{
if (RDFSKOSChecker.CheckHiddenLabel(conceptScheme, concept, hiddenLabelLiteral))
{
//Add hiddenLabel annotation
conceptScheme.Annotations.HiddenLabel.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.HIDDEN_LABEL.ToRDFOntologyAnnotationProperty(), hiddenLabelLiteral));
}
}
}
return conceptScheme;
}
#endregion
#region Documentation
/// <summary>
/// Adds the given literal as 'skos:note' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddNoteAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add note annotation to the scheme
conceptScheme.Annotations.Note.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.NOTE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as 'skos:changeNote' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddChangeNoteAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add changeNote annotation to the scheme
conceptScheme.Annotations.ChangeNote.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.CHANGE_NOTE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as 'skos:editorialNote' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddEditorialNoteAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add editorialNote annotation to the scheme
conceptScheme.Annotations.EditorialNote.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.EDITORIAL_NOTE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
///Adds the given literal as 'skos:historyNote' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddHistoryNoteAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add historyNote annotation to the scheme
conceptScheme.Annotations.HistoryNote.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.HISTORY_NOTE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as 'skos:scopeNote' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddScopeNoteAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add scopeNote annotation to the scheme
conceptScheme.Annotations.ScopeNote.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.SCOPE_NOTE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as 'skos:definition' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddDefinitionAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add definition annotation to the scheme
conceptScheme.Annotations.Definition.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.DEFINITION.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
/// <summary>
/// Adds the given literal as 'skos:example' annotation of the given concept within the conceptScheme
/// </summary>
public static RDFSKOSConceptScheme AddExampleAnnotation(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
RDFOntologyLiteral literal)
{
if (conceptScheme != null && concept != null && literal != null)
{
//Add example annotation to the scheme
conceptScheme.Annotations.Example.AddEntry(new RDFOntologyTaxonomyEntry(concept, RDFVocabulary.SKOS.EXAMPLE.ToRDFOntologyAnnotationProperty(), literal));
}
return conceptScheme;
}
#endregion
#endregion
#endregion
#region Reasoning
#region Semantic
#region Broader/BroaderTransitive
/// <summary>
/// Checks if the given aConcept has broader/broaderTransitive concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasBroaderConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetBroaderConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the broader/broaderTransitive concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetBroaderConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
//Get skos:broader concepts
foreach (RDFOntologyTaxonomyEntry broaderConcept in conceptScheme.Relations.Broader.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)broaderConcept.TaxonomyObject);
//Get skos:broaderTransitive concepts
result = result.UnionWith(conceptScheme.GetBroaderConceptsOfInternal(concept, null))
.RemoveConcept(concept); //Safety deletion
}
return result;
}
/// <summary>
/// Subsumes the "skos:broaderTransitive" taxonomy to discover direct and indirect broader concepts of the given scheme
/// </summary>
internal static RDFSKOSConceptScheme GetBroaderConceptsOfInternal(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
Dictionary<long, RDFSKOSConcept> visitContext)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
#region visitContext
if (visitContext == null)
visitContext = new Dictionary<long, RDFSKOSConcept>() { { concept.PatternMemberID, concept } };
else
{
if (!visitContext.ContainsKey(concept.PatternMemberID))
visitContext.Add(concept.PatternMemberID, concept);
else
return result;
}
#endregion
//Transitivity of "skos:broaderTransitive" taxonomy:
//((A SKOS:BROADERTRANSITIVE B) && (B SKOS:BROADERTRANSITIVE C)) => (A SKOS:BROADERTRANSITIVE C)
foreach (RDFOntologyTaxonomyEntry bt in conceptScheme.Relations.BroaderTransitive.SelectEntriesBySubject(concept))
{
result.AddConcept((RDFSKOSConcept)bt.TaxonomyObject);
//Exploit skos:broaderTransitive taxonomy
result = result.UnionWith(conceptScheme.GetBroaderConceptsOfInternal((RDFSKOSConcept)bt.TaxonomyObject, visitContext));
}
return result;
}
#endregion
#region Narrower/NarrowerTransitive
/// <summary>
/// Checks if the given aConcept has narrower/narrowerTransitive concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasNarrowerConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetNarrowerConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the narrower/narrowerTransitive concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetNarrowerConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
//Get skos:narrower concepts
foreach (RDFOntologyTaxonomyEntry narrowerConcept in conceptScheme.Relations.Narrower.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)narrowerConcept.TaxonomyObject);
//Get skos:narrowerTransitive concepts
result = result.UnionWith(conceptScheme.GetNarrowerConceptsOfInternal(concept, null))
.RemoveConcept(concept); //Safety deletion
}
return result;
}
/// <summary>
/// Subsumes the "skos:narrowerTransitive" taxonomy to discover direct and indirect narrower concepts of the given scheme
/// </summary>
internal static RDFSKOSConceptScheme GetNarrowerConceptsOfInternal(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
Dictionary<long, RDFSKOSConcept> visitContext)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
#region visitContext
if (visitContext == null)
visitContext = new Dictionary<long, RDFSKOSConcept>() { { concept.PatternMemberID, concept } };
else
{
if (!visitContext.ContainsKey(concept.PatternMemberID))
visitContext.Add(concept.PatternMemberID, concept);
else
return result;
}
#endregion
//Transitivity of "skos:narrowerTransitive" taxonomy:
//((A SKOS:NARROWERTRANSITIVE B) && (B SKOS:NARROWERTRANSITIVE C)) => (A SKOS:NARROWERTRANSITIVE C)
foreach (RDFOntologyTaxonomyEntry nt in conceptScheme.Relations.NarrowerTransitive.SelectEntriesBySubject(concept))
{
result.AddConcept((RDFSKOSConcept)nt.TaxonomyObject);
//Exploit skos:narrowerTransitive taxonomy
result = result.UnionWith(conceptScheme.GetNarrowerConceptsOfInternal((RDFSKOSConcept)nt.TaxonomyObject, visitContext));
}
return result;
}
#endregion
#region Related
/// <summary>
/// Checks if the given aConcept has related concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasRelatedConcept(this RDFSKOSConceptScheme data,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && data != null ? data.GetRelatedConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the related concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetRelatedConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
foreach (RDFOntologyTaxonomyEntry relatedConcept in conceptScheme.Relations.Related.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)relatedConcept.TaxonomyObject);
}
return result;
}
#endregion
#endregion
#region Mapping
#region BroadMatch
/// <summary>
/// Checks if the given aConcept has broadMatch concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasBroadMatchConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetBroadMatchConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the broadMatch concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetBroadMatchConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
foreach (RDFOntologyTaxonomyEntry broadMatchConcept in conceptScheme.Relations.BroadMatch.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)broadMatchConcept.TaxonomyObject);
}
return result;
}
#endregion
#region NarrowMatch
/// <summary>
/// Checks if the given aConcept has narrowMatch concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasNarrowMatchConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetNarrowMatchConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the narrowMatch concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetNarrowMatchConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
foreach (RDFOntologyTaxonomyEntry narrowMatchConcept in conceptScheme.Relations.NarrowMatch.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)narrowMatchConcept.TaxonomyObject);
}
return result;
}
#endregion
#region RelatedMatch
/// <summary>
/// Checks if the given aConcept has relatedMatch concept the given bConcept within the given scheme
/// </summary>
public static bool CheckHasRelatedMatchConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetRelatedMatchConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the relatedMatch concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetRelatedMatchConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
foreach (RDFOntologyTaxonomyEntry relatedMatchConcept in conceptScheme.Relations.RelatedMatch.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)relatedMatchConcept.TaxonomyObject);
}
return result;
}
#endregion
#region CloseMatch
/// <summary>
/// Checks if the given aConcept skos:closeMatch the given bConcept within the given scheme
/// </summary>
public static bool CheckHasCloseMatchConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetCloseMatchConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the skos:closeMatch concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetCloseMatchConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
foreach (RDFOntologyTaxonomyEntry closeMatchConcept in conceptScheme.Relations.CloseMatch.SelectEntriesBySubject(concept))
result.AddConcept((RDFSKOSConcept)closeMatchConcept.TaxonomyObject);
}
return result;
}
#endregion
#region ExactMatch
/// <summary>
/// Checks if the given aConcept skos:exactMatch the given bConcept within the given scheme
/// </summary>
public static bool CheckHasExactMatchConcept(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept aConcept,
RDFSKOSConcept bConcept)
=> aConcept != null && bConcept != null && conceptScheme != null ? conceptScheme.GetExactMatchConceptsOf(aConcept).Concepts.ContainsKey(bConcept.PatternMemberID) : false;
/// <summary>
/// Enlists the skos:exactMatch concepts of the given concept within the given scheme
/// </summary>
public static RDFSKOSConceptScheme GetExactMatchConceptsOf(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
if (concept != null && conceptScheme != null)
{
result = conceptScheme.GetExactMatchConceptsOfInternal(concept, null)
.RemoveConcept(concept); //Safety deletion
}
return result;
}
/// <summary>
/// Subsumes the "skos:exactMatch" taxonomy to discover direct and indirect exactmatches of the given concept
/// </summary>
internal static RDFSKOSConceptScheme GetExactMatchConceptsOfInternal(this RDFSKOSConceptScheme conceptScheme,
RDFSKOSConcept concept,
Dictionary<long, RDFSKOSConcept> visitContext)
{
RDFSKOSConceptScheme result = new RDFSKOSConceptScheme((RDFResource)conceptScheme.Value);
#region visitContext
if (visitContext == null)
visitContext = new Dictionary<long, RDFSKOSConcept>() { { concept.PatternMemberID, concept } };
else
{
if (!visitContext.ContainsKey(concept.PatternMemberID))
visitContext.Add(concept.PatternMemberID, concept);
else
return result;
}
#endregion
// Transitivity of "skos:exactMatch" taxonomy:
//((A SKOS:EXACTMATCH B) && (B SKOS:EXACTMATCH C)) => (A SKOS:EXACTMATCH C)
foreach (RDFOntologyTaxonomyEntry em in conceptScheme.Relations.ExactMatch.SelectEntriesBySubject(concept))
{
result.AddConcept((RDFSKOSConcept)em.TaxonomyObject);
result = result.UnionWith(conceptScheme.GetExactMatchConceptsOfInternal((RDFSKOSConcept)em.TaxonomyObject, visitContext));
}
return result;
}
#endregion
#endregion
#endregion
#region Extensions
/// <summary>
/// Adds the "skosCollection -> skos:member -> skosMember" relation to the data (and links the given axiom annotation if provided)
/// </summary>
internal static RDFOntologyData AddMemberRelation(this RDFOntologyData ontologyData,
RDFOntologyFact skosCollection,
RDFOntologyFact skosMember,
RDFOntologyAxiomAnnotation axiomAnnotation=null)
{
if (ontologyData != null && skosCollection != null && skosMember != null)
{
RDFOntologyTaxonomyEntry taxonomyEntry = new RDFOntologyTaxonomyEntry(skosCollection, RDFVocabulary.SKOS.MEMBER.ToRDFOntologyObjectProperty(), skosMember);
ontologyData.Relations.Member.AddEntry(taxonomyEntry);
//Link owl:Axiom annotation
ontologyData.AddAxiomAnnotation(taxonomyEntry, axiomAnnotation, nameof(RDFOntologyDataMetadata.Member));
}
return ontologyData;
}
/// <summary>
/// Adds the "skosOrderedCollection -> skos:memberList -> skosMember" relation to the data (and links the given axiom annotation if provided)
/// </summary>
internal static RDFOntologyData AddMemberListRelation(this RDFOntologyData ontologyData,
RDFOntologyFact skosOrderedCollection,
RDFOntologyFact skosMember,
RDFOntologyAxiomAnnotation axiomAnnotation = null)
{
if (ontologyData != null && skosOrderedCollection != null && skosMember != null)
{
RDFOntologyTaxonomyEntry taxonomyEntry = new RDFOntologyTaxonomyEntry(skosOrderedCollection, RDFVocabulary.SKOS.MEMBER_LIST.ToRDFOntologyObjectProperty(), skosMember);
ontologyData.Relations.MemberList.AddEntry(taxonomyEntry);
//Link owl:Axiom annotation
ontologyData.AddAxiomAnnotation(taxonomyEntry, axiomAnnotation, nameof(RDFOntologyDataMetadata.MemberList));
}
return ontologyData;
}
/// <summary>
/// Removes the "skosCollection -> skos:member -> skosMember" relation to the data.
/// </summary>
internal static RDFOntologyData RemoveMemberRelation(this RDFOntologyData ontologyData,
RDFOntologyFact skosCollection,
RDFOntologyFact skosMember)
{
if (ontologyData != null && skosCollection != null && skosMember != null)
{
RDFOntologyTaxonomyEntry taxonomyEntry = new RDFOntologyTaxonomyEntry(skosCollection, RDFVocabulary.SKOS.MEMBER.ToRDFOntologyObjectProperty(), skosMember);
ontologyData.Relations.Member.RemoveEntry(taxonomyEntry);
//Unlink owl:Axiom annotation
ontologyData.RemoveAxiomAnnotation(taxonomyEntry);
}
return ontologyData;
}
/// <summary>
/// Removes the "skosOrderedCollection -> skos:memberList -> skosMember" relation to the data.
/// </summary>
internal static RDFOntologyData RemoveMemberListRelation(this RDFOntologyData ontologyData,
RDFOntologyFact skosOrderedCollection,
RDFOntologyFact skosMember)
{
if (ontologyData != null && skosOrderedCollection != null && skosMember != null)
{
RDFOntologyTaxonomyEntry taxonomyEntry = new RDFOntologyTaxonomyEntry(skosOrderedCollection, RDFVocabulary.SKOS.MEMBER_LIST.ToRDFOntologyObjectProperty(), skosMember);
ontologyData.Relations.MemberList.RemoveEntry(taxonomyEntry);
//Unlink owl:Axiom annotation
ontologyData.RemoveAxiomAnnotation(taxonomyEntry);
}
return ontologyData;
}
#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.
/******************************************************************************
* 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 ExtractVector128UInt321()
{
var test = new ExtractVector128Test__ExtractVector128UInt321();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
// Validates passing an instance member of a class works
test.RunClassFldScenario();
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
}
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 ExtractVector128Test__ExtractVector128UInt321
{
private struct TestStruct
{
public Vector256<UInt32> _fld;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref testStruct._fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
return testStruct;
}
public void RunStructFldScenario(ExtractVector128Test__ExtractVector128UInt321 testClass)
{
var result = Avx2.ExtractVector128(_fld, 1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr);
}
}
private static readonly int LargestVectorSize = 32;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector256<UInt32> _clsVar;
private Vector256<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static ExtractVector128Test__ExtractVector128UInt321()
{
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
}
public ExtractVector128Test__ExtractVector128UInt321()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetUInt32(); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Avx2.ExtractVector128(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Avx2.ExtractVector128(
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Avx2.ExtractVector128(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Avx2).GetMethod(nameof(Avx2.ExtractVector128), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)1
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Avx2.ExtractVector128(
_clsVar,
1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ExtractVector128(firstOp, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new ExtractVector128Test__ExtractVector128UInt321();
var result = Avx2.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Avx2.ExtractVector128(_fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Avx2.ExtractVector128(test._fld, 1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<UInt32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != firstOp[4])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((result[i] != firstOp[i + 4]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ExtractVector128)}<UInt32>(Vector256<UInt32><9>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.Xna.Framework.Content;
[assembly: InternalsVisibleTo("CocosSharp.Content.Pipeline.Importers")]
[assembly: InternalsVisibleTo("Microsoft.Xna.Framework.Content")]
namespace CocosSharp
{
#if IOS
[Foundation.Preserve (AllMembers = true)]
#endif
internal sealed class CCBMFontConfiguration
{
// Due to a bug in MonoGame's Custom Content loading not being able to recognize properties that are not
// marked public we have to leave the Serialized information as variables and not properties.
// This is an inconsistency with how XNA works. Until this bug is fixed this needs to remain as it is.
[ContentSerializer]
internal int CommonHeight;// { get; set; }
[ContentSerializer]
internal Dictionary<int, CCBMGlyphDef> Glyphs; // { get; set; }
[ContentSerializer]
internal Dictionary<int, CCKerningHashElement> GlyphKernings; // { get; set; }
[ContentSerializer]
internal string AtlasName; // { get; set; }
[ContentSerializer]
internal CCBMGlyphPadding Padding;
public List<int> CharacterSet { get; set; }
#region Constructors
internal static CCBMFontConfiguration FontConfigurationWithFile(string fntFile)
{
try
{
return CCContentManager.SharedContentManager.Load<CCBMFontConfiguration>(fntFile);
}
catch (ContentLoadException)
{
return new CCBMFontConfiguration(fntFile);
}
}
internal CCBMFontConfiguration()
{
Glyphs = new Dictionary<int, CCBMGlyphDef>();
CharacterSet = new List<int>();
GlyphKernings = new Dictionary<int, CCKerningHashElement>();
}
internal CCBMFontConfiguration(string fntFile)
: this(CCContentManager.SharedContentManager.Load<string>(fntFile), fntFile)
{ }
// Content pipeline makes use of this constructor
internal CCBMFontConfiguration(string data, string fntFile)
: base()
{
Glyphs = new Dictionary<int, CCBMGlyphDef>();
CharacterSet = new List<int>();
GlyphKernings = new Dictionary<int, CCKerningHashElement>();
GlyphKernings.Clear();
Glyphs.Clear();
CharacterSet = ParseConfigFile(data, fntFile);
}
#endregion Constructors
private List<int> ParseConfigFile(string pBuffer, string fntFile)
{
long nBufSize = pBuffer.Length;
Debug.Assert(pBuffer != null, "CCBMFontConfiguration::parseConfigFile | Open file error.");
if (string.IsNullOrEmpty(pBuffer))
{
return null;
}
var validCharsString = new List<int>();
// parse spacing / padding
string line;
string strLeft = pBuffer;
while (strLeft.Length > 0)
{
int pos = strLeft.IndexOf('\n');
if (pos != -1)
{
// the data is more than a line.get one line
line = strLeft.Substring(0, pos);
strLeft = strLeft.Substring(pos + 1);
}
else
{
// get the left data
line = strLeft;
strLeft = null;
}
if (line.StartsWith("info face"))
{
// XXX: info parsing is incomplete
// Not needed for the Hiero editors, but needed for the AngelCode editor
// [self parseInfoArguments:line];
parseInfoArguments(line);
}
// Check to see if the start of the line is something we are interested in
else if (line.StartsWith("common lineHeight"))
{
parseCommonArguments(line);
}
else if (line.StartsWith("page id"))
{
parseImageFileName(line, fntFile);
}
else if (line.StartsWith("chars c"))
{
// Ignore this line
}
else if (line.StartsWith("char"))
{
// Parse the current line and create a new CharDef
var characterDefinition = new CCBMGlyphDef();
parseCharacterDefinition(line, characterDefinition);
Glyphs.Add(characterDefinition.Character, characterDefinition);
validCharsString.Add(characterDefinition.Character);
}
//else if (line.StartsWith("kernings count"))
//{
// this.parseKerningCapacity(line);
//}
else if (line.StartsWith("kerning first"))
{
parseKerningEntry(line);
}
}
return validCharsString;
}
private void parseCharacterDefinition(string line, CCBMGlyphDef characterDefinition)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// char id=32 x=0 y=0 width=0 height=0 xoffset=0 yoffset=44 xadvance=14 page=0 chnl=0
//////////////////////////////////////////////////////////////////////////
// Character ID
int index = line.IndexOf("id=");
int index2 = line.IndexOf(' ', index);
string value = line.Substring(index, index2 - index);
characterDefinition.Character = CocosSharp.CCUtils.CCParseInt(value.Replace("id=", ""));
//CCAssert(characterDefinition->charID < kCCBMFontMaxChars, "BitmpaFontAtlas: CharID bigger than supported");
// Character x
index = line.IndexOf("x=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.Subrect.Origin.X = CocosSharp.CCUtils.CCParseFloat(value.Replace("x=", ""));
// Character y
index = line.IndexOf("y=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.Subrect.Origin.Y = CocosSharp.CCUtils.CCParseFloat(value.Replace("y=", ""));
// Character width
index = line.IndexOf("width=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.Subrect.Size.Width = CocosSharp.CCUtils.CCParseFloat(value.Replace("width=", ""));
// Character height
index = line.IndexOf("height=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.Subrect.Size.Height = CocosSharp.CCUtils.CCParseFloat(value.Replace("height=", ""));
// Character xoffset
index = line.IndexOf("xoffset=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.XOffset = CocosSharp.CCUtils.CCParseInt(value.Replace("xoffset=", ""));
// Character yoffset
index = line.IndexOf("yoffset=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.YOffset = CocosSharp.CCUtils.CCParseInt(value.Replace("yoffset=", ""));
// Character xadvance
index = line.IndexOf("xadvance=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
characterDefinition.XAdvance = CocosSharp.CCUtils.CCParseInt(value.Replace("xadvance=", ""));
}
// info face
private void parseInfoArguments(string line)
{
//////////////////////////////////////////////////////////////////////////
// possible lines to parse:
// info face="Script" size=32 bold=0 italic=0 charset="" unicode=1 stretchH=100 smooth=1 aa=1 padding=1,4,3,2 spacing=0,0 outline=0
// info face="Cracked" size=36 bold=0 italic=0 charset="" unicode=0 stretchH=100 smooth=1 aa=1 padding=0,0,0,0 spacing=1,1
//////////////////////////////////////////////////////////////////////////
// padding
int index = line.IndexOf("padding=");
int index2 = line.IndexOf(' ', index);
string value = line.Substring(index, index2 - index);
value = value.Replace("padding=", "");
string[] temp = value.Split(',');
Padding.Top = CocosSharp.CCUtils.CCParseInt(temp[0]);
Padding.Right = CocosSharp.CCUtils.CCParseInt(temp[1]);
Padding.Bottom = CocosSharp.CCUtils.CCParseInt(temp[2]);
Padding.Left = CocosSharp.CCUtils.CCParseInt(temp[3]);
//CCLOG("cocos2d: padding: %d,%d,%d,%d", m_tPadding.left, m_tPadding.top, m_tPadding.right, m_tPadding.bottom);
}
// common
private void parseCommonArguments(string line)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// common lineHeight=104 base=26 scaleW=1024 scaleH=512 pages=1 packed=0
//////////////////////////////////////////////////////////////////////////
// Height
int index = line.IndexOf("lineHeight=");
int index2 = line.IndexOf(' ', index);
string value = line.Substring(index, index2 - index);
CommonHeight = CocosSharp.CCUtils.CCParseInt(value.Replace("lineHeight=", ""));
// scaleW. sanity check
index = line.IndexOf("scaleW=") + "scaleW=".Length;
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
//CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
// scaleH. sanity check
index = line.IndexOf("scaleH=") + "scaleH=".Length;
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
//CCAssert(atoi(value.c_str()) <= CCConfiguration::sharedConfiguration()->getMaxTextureSize(), "CCLabelBMFont: page can't be larger than supported");
// pages. sanity check
index = line.IndexOf("pages=") + "pages=".Length;
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
//CCAssert(atoi(value.c_str()) == 1, "CCBitfontAtlas: only supports 1 page");
// packed (ignore) What does this mean ??
}
//page file
private void parseImageFileName(string line, string fntFile)
{
// //////////////////////////////////////////////////////////////////////////
//// line to parse:
//// page id=0 file="bitmapFontTest.png"
////////////////////////////////////////////////////////////////////////////
// page ID. Sanity check
int index = line.IndexOf('=') + 1;
int index2 = line.IndexOf(' ', index);
string value = line.Substring(index, index2 - index);
int ivalue;
if (!int.TryParse(value, out ivalue))
{
throw (new ContentLoadException("Invalid page ID for FNT descriptor. Line=" + line + ", value=" + value + ", indices=" + index + "," + index2));
}
// Debug.Assert(Convert.ToInt32(value) == 0, "LabelBMFont file could not be found");
// file
index = line.IndexOf('"') + 1;
index2 = line.IndexOf('"', index);
value = line.Substring(index, index2 - index);
AtlasName = value;
var directory = string.Empty;
if (!CCFileUtils.GetDirectoryName(value, out directory))
{
try
{
AtlasName = CCFileUtils.FullPathFromRelativeFile(value, fntFile);
}
catch { }
}
}
private void parseKerningEntry(string line)
{
//////////////////////////////////////////////////////////////////////////
// line to parse:
// kerning first=121 second=44 amount=-7
//////////////////////////////////////////////////////////////////////////
// first
int first;
int index = line.IndexOf("first=");
int index2 = line.IndexOf(' ', index);
string value = line.Substring(index, index2 - index);
first = CocosSharp.CCUtils.CCParseInt(value.Replace("first=", ""));
// second
int second;
index = line.IndexOf("second=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index, index2 - index);
second = CocosSharp.CCUtils.CCParseInt(value.Replace("second=", ""));
// amount
int amount;
index = line.IndexOf("amount=");
index2 = line.IndexOf(' ', index);
value = line.Substring(index);
amount = CocosSharp.CCUtils.CCParseInt(value.Replace("amount=", ""));
try
{
var element = new CCKerningHashElement();
element.Amount = amount;
element.Key = (first << 16) | (second & 0xffff);
GlyphKernings.Add(element.Key, element);
}
catch (Exception)
{
CocosSharp.CCLog.Log("Failed to parse font line: {0}", line);
}
}
private void purgeKerningDictionary()
{
GlyphKernings.Clear();
}
#region Nested type: CCBMGlyphDef
/// <summary>
/// CCBMFont definition
/// </summary>
internal class CCBMGlyphDef
{
/// <summary>
/// ID of the character
/// </summary>
public int Character { get; set; }
/// <summary>
/// origin and size of the font
/// </summary>
public CCRect Subrect;
/// <summary>
/// The amount to move the current position after drawing the character (in pixels)
/// </summary>
public int XAdvance { get; set; }
/// <summary>
/// The X amount the image should be offset when drawing the image (in pixels)
/// </summary>
public int XOffset { get; set; }
/// <summary>
/// The Y amount the image should be offset when drawing the image (in pixels)
/// </summary>
public int YOffset { get; set; }
}
#endregion
#region Nested type: CCBMGlyphPadding
public struct CCBMGlyphPadding
{
// padding left
public int Bottom { get; set; }
public int Left { get; set; }
// padding top
// padding right
public int Right { get; set; }
public int Top { get; set; }
// padding bottom
}
#endregion
#region Nested type: CCKerningHashElement
public struct CCKerningHashElement
{
public int Amount { get; set; }
public int Key { get; set; } //key for the hash. 16-bit for 1st element, 16-bit for 2nd element
}
#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.
/******************************************************************************
* 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 AndNotInt32()
{
var test = new SimpleBinaryOpTest__AndNotInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (Sse2.IsSupported)
{
// Validates passing a static member works, using pinning and Load
test.RunClsVarScenario_Load();
}
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Sse2.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local class works, using pinning and Load
test.RunClassLclFldScenario_Load();
}
// Validates passing an instance member of a class works
test.RunClassFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a class works, using pinning and Load
test.RunClassFldScenario_Load();
}
// Validates passing the field of a local struct works
test.RunStructLclFldScenario();
if (Sse2.IsSupported)
{
// Validates passing the field of a local struct works, using pinning and Load
test.RunStructLclFldScenario_Load();
}
// Validates passing an instance member of a struct works
test.RunStructFldScenario();
if (Sse2.IsSupported)
{
// Validates passing an instance member of a struct works, using pinning and Load
test.RunStructFldScenario_Load();
}
}
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__AndNotInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] inArray2;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle inHandle2;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, Int32[] inArray2, Int32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Int32>();
if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.inArray2 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int32, byte>(ref inArray2[0]), (uint)sizeOfinArray2);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.Free();
inHandle2.Free();
outHandle.Free();
}
private static unsafe void* Align(byte* buffer, ulong expectedAlignment)
{
return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1));
}
}
private struct TestStruct
{
public Vector128<Int32> _fld1;
public Vector128<Int32> _fld2;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleBinaryOpTest__AndNotInt32 testClass)
{
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleBinaryOpTest__AndNotInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Int32[] _data2 = new Int32[Op2ElementCount];
private static Vector128<Int32> _clsVar1;
private static Vector128<Int32> _clsVar2;
private Vector128<Int32> _fld1;
private Vector128<Int32> _fld2;
private DataTable _dataTable;
static SimpleBinaryOpTest__AndNotInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleBinaryOpTest__AndNotInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt32(); }
for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, _data2, new Int32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = Sse2.AndNot(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned));
var result = Sse2.AndNot(
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned));
var result = typeof(Sse2).GetMethod(nameof(Sse2.AndNot), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = Sse2.AndNot(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
fixed (Vector128<Int32>* pClsVar2 = &_clsVar2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(pClsVar1)),
Sse2.LoadVector128((Int32*)(pClsVar2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var op2 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr);
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned));
var op1 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr));
var op2 = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr));
var result = Sse2.AndNot(op1, op2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, op2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleBinaryOpTest__AndNotInt32();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleBinaryOpTest__AndNotInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
fixed (Vector128<Int32>* pFld2 = &test._fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = Sse2.AndNot(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
fixed (Vector128<Int32>* pFld2 = &_fld2)
{
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(pFld1)),
Sse2.LoadVector128((Int32*)(pFld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = Sse2.AndNot(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = Sse2.AndNot(
Sse2.LoadVector128((Int32*)(&test._fld1)),
Sse2.LoadVector128((Int32*)(&test._fld2))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunStructFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario));
var test = TestStruct.Create();
test.RunStructFldScenario(this);
}
public void RunStructFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load));
var test = TestStruct.Create();
test.RunStructFldScenario_Load(this);
}
public void RunUnsupportedScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario));
bool succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
succeeded = true;
}
if (!succeeded)
{
Succeeded = false;
}
}
private void ValidateResult(Vector128<Int32> op1, Vector128<Int32> op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), op2);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
Int32[] inArray2 = new Int32[Op2ElementCount];
Int32[] outArray = new Int32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>());
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if ((int)(~left[0] & right[0]) != result[0])
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if ((int)(~left[i] & right[i]) != result[i])
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.AndNot)}<Int32>(Vector128<Int32>, Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})");
TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.DirectoryServices.ActiveDirectory
{
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Specialized;
using System.Diagnostics;
using System.Security.Permissions;
public class ForestTrustRelationshipInformation : TrustRelationshipInformation
{
private TopLevelNameCollection _topLevelNames = new TopLevelNameCollection();
private StringCollection _excludedNames = new StringCollection();
private ForestTrustDomainInfoCollection _domainInfo = new ForestTrustDomainInfoCollection();
private ArrayList _binaryData = new ArrayList();
private Hashtable _excludedNameTime = new Hashtable();
private ArrayList _binaryDataTime = new ArrayList();
internal bool retrieved = false;
internal ForestTrustRelationshipInformation(DirectoryContext context, string source, DS_DOMAIN_TRUSTS unmanagedTrust, TrustType type)
{
string tmpDNSName = null;
string tmpNetBIOSName = null;
// security context
this.context = context;
// source
this.source = source;
// target
if (unmanagedTrust.DnsDomainName != (IntPtr)0)
tmpDNSName = Marshal.PtrToStringUni(unmanagedTrust.DnsDomainName);
if (unmanagedTrust.NetbiosDomainName != (IntPtr)0)
tmpNetBIOSName = Marshal.PtrToStringUni(unmanagedTrust.NetbiosDomainName);
this.target = (tmpDNSName == null ? tmpNetBIOSName : tmpDNSName);
// direction
if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0 &&
(unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0)
direction = TrustDirection.Bidirectional;
else if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_OUTBOUND) != 0)
direction = TrustDirection.Outbound;
else if ((unmanagedTrust.Flags & (int)DS_DOMAINTRUST_FLAG.DS_DOMAIN_DIRECT_INBOUND) != 0)
direction = TrustDirection.Inbound;
// type
this.type = type;
}
public TopLevelNameCollection TopLevelNames
{
get
{
if (!retrieved)
GetForestTrustInfoHelper();
return _topLevelNames;
}
}
public StringCollection ExcludedTopLevelNames
{
get
{
if (!retrieved)
GetForestTrustInfoHelper();
return _excludedNames;
}
}
public ForestTrustDomainInfoCollection TrustedDomainInformation
{
get
{
if (!retrieved)
GetForestTrustInfoHelper();
return _domainInfo;
}
}
public void Save()
{
int count = 0;
IntPtr records = (IntPtr)0;
int currentCount = 0;
IntPtr tmpPtr = (IntPtr)0;
IntPtr forestInfo = (IntPtr)0;
PolicySafeHandle handle = null;
LSA_UNICODE_STRING trustedDomainName;
IntPtr collisionInfo = (IntPtr)0;
ArrayList ptrList = new ArrayList();
ArrayList sidList = new ArrayList();
bool impersonated = false;
IntPtr target = (IntPtr)0;
string serverName = null;
IntPtr fileTime = (IntPtr)0;
// first get the count of all the records
int toplevelNamesCount = TopLevelNames.Count;
int excludedNamesCount = ExcludedTopLevelNames.Count;
int trustedDomainCount = TrustedDomainInformation.Count;
int binaryDataCount = 0;
checked
{
count += toplevelNamesCount;
count += excludedNamesCount;
count += trustedDomainCount;
if (_binaryData.Count != 0)
{
binaryDataCount = _binaryData.Count;
// for the ForestTrustRecordTypeLast record
count++;
count += binaryDataCount;
}
// allocate the memory for all the records
records = Marshal.AllocHGlobal(count * IntPtr.Size);
}
try
{
try
{
IntPtr ptr = (IntPtr)0;
fileTime = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(FileTime)));
UnsafeNativeMethods.GetSystemTimeAsFileTime(fileTime);
// set the time
FileTime currentTime = new FileTime();
Marshal.PtrToStructure(fileTime, currentTime);
for (int i = 0; i < toplevelNamesCount; i++)
{
// now begin to construct top leve name record
LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
record.Flags = (int)_topLevelNames[i].Status;
record.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName;
TopLevelName TLN = _topLevelNames[i];
record.Time = TLN.time;
record.TopLevelName = new LSA_UNICODE_STRING();
ptr = Marshal.StringToHGlobalUni(TLN.Name);
ptrList.Add(ptr);
UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr);
tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
ptrList.Add(tmpPtr);
Marshal.StructureToPtr(record, tmpPtr, false);
Marshal.WriteIntPtr(records, IntPtr.Size * currentCount, tmpPtr);
currentCount++;
}
for (int i = 0; i < excludedNamesCount; i++)
{
// now begin to construct excluded top leve name record
LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
record.Flags = 0;
record.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx;
if (_excludedNameTime.Contains(_excludedNames[i]))
{
record.Time = (LARGE_INTEGER)_excludedNameTime[i];
}
else
{
record.Time = new LARGE_INTEGER();
record.Time.lowPart = currentTime.lower;
record.Time.highPart = currentTime.higher;
}
record.TopLevelName = new LSA_UNICODE_STRING();
ptr = Marshal.StringToHGlobalUni(_excludedNames[i]);
ptrList.Add(ptr);
UnsafeNativeMethods.RtlInitUnicodeString(record.TopLevelName, ptr);
tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
ptrList.Add(tmpPtr);
Marshal.StructureToPtr(record, tmpPtr, false);
Marshal.WriteIntPtr(records, IntPtr.Size * currentCount, tmpPtr);
currentCount++;
}
for (int i = 0; i < trustedDomainCount; i++)
{
// now begin to construct domain info record
LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
record.Flags = (int)_domainInfo[i].Status;
record.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo;
ForestTrustDomainInformation tmp = _domainInfo[i];
record.Time = tmp.time;
IntPtr pSid = (IntPtr)0;
IntPtr stringSid = (IntPtr)0;
stringSid = Marshal.StringToHGlobalUni(tmp.DomainSid);
ptrList.Add(stringSid);
int result = UnsafeNativeMethods.ConvertStringSidToSidW(stringSid, ref pSid);
if (result == 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error());
}
record.DomainInfo = new LSA_FOREST_TRUST_DOMAIN_INFO();
record.DomainInfo.sid = pSid;
sidList.Add(pSid);
record.DomainInfo.DNSNameBuffer = Marshal.StringToHGlobalUni(tmp.DnsName);
ptrList.Add(record.DomainInfo.DNSNameBuffer);
record.DomainInfo.DNSNameLength = (short)(tmp.DnsName == null ? 0 : tmp.DnsName.Length * 2); // sizeof(WCHAR)
record.DomainInfo.DNSNameMaximumLength = (short)(tmp.DnsName == null ? 0 : tmp.DnsName.Length * 2);
record.DomainInfo.NetBIOSNameBuffer = Marshal.StringToHGlobalUni(tmp.NetBiosName);
ptrList.Add(record.DomainInfo.NetBIOSNameBuffer);
record.DomainInfo.NetBIOSNameLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2);
record.DomainInfo.NetBIOSNameMaximumLength = (short)(tmp.NetBiosName == null ? 0 : tmp.NetBiosName.Length * 2);
tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
ptrList.Add(tmpPtr);
Marshal.StructureToPtr(record, tmpPtr, false);
Marshal.WriteIntPtr(records, IntPtr.Size * currentCount, tmpPtr);
currentCount++;
}
if (binaryDataCount > 0)
{
// now begin to construct ForestTrustRecordTypeLast
LSA_FOREST_TRUST_RECORD lastRecord = new LSA_FOREST_TRUST_RECORD();
lastRecord.Flags = 0;
lastRecord.ForestTrustType = LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast;
tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
ptrList.Add(tmpPtr);
Marshal.StructureToPtr(lastRecord, tmpPtr, false);
Marshal.WriteIntPtr(records, IntPtr.Size * currentCount, tmpPtr);
currentCount++;
for (int i = 0; i < binaryDataCount; i++)
{
// now begin to construct excluded top leve name record
LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
record.Flags = 0;
record.Time = (LARGE_INTEGER)_binaryDataTime[i];
record.Data.Length = ((byte[])_binaryData[i]).Length;
if (record.Data.Length == 0)
{
record.Data.Buffer = (IntPtr)0;
}
else
{
record.Data.Buffer = Marshal.AllocHGlobal(record.Data.Length);
ptrList.Add(record.Data.Buffer);
Marshal.Copy((byte[])_binaryData[i], 0, record.Data.Buffer, record.Data.Length);
}
tmpPtr = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_RECORD)));
ptrList.Add(tmpPtr);
Marshal.StructureToPtr(record, tmpPtr, false);
Marshal.WriteIntPtr(records, IntPtr.Size * currentCount, tmpPtr);
currentCount++;
}
}
// finally construct the LSA_FOREST_TRUST_INFORMATION
LSA_FOREST_TRUST_INFORMATION trustInformation = new LSA_FOREST_TRUST_INFORMATION();
trustInformation.RecordCount = count;
trustInformation.Entries = records;
forestInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(LSA_FOREST_TRUST_INFORMATION)));
Marshal.StructureToPtr(trustInformation, forestInfo, false);
// get policy server name
serverName = Utils.GetPolicyServerName(context, true, true, SourceName);
// do impersonation first
impersonated = Utils.Impersonate(context);
// get the policy handle
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
// get the target name
trustedDomainName = new LSA_UNICODE_STRING();
target = Marshal.StringToHGlobalUni(TargetName);
UnsafeNativeMethods.RtlInitUnicodeString(trustedDomainName, target);
// call the unmanaged function
int error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 1, out collisionInfo);
if (error != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(UnsafeNativeMethods.LsaNtStatusToWinError(error), serverName);
}
// there is collision, throw proper exception so user can deal with it
if (collisionInfo != (IntPtr)0)
{
throw ExceptionHelper.CreateForestTrustCollisionException(collisionInfo);
}
// commit the changes
error = UnsafeNativeMethods.LsaSetForestTrustInformation(handle, trustedDomainName, forestInfo, 0, out collisionInfo);
if (error != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(error, serverName);
}
// now next time property is invoked, we need to go to the server
retrieved = false;
}
finally
{
if (impersonated)
Utils.Revert();
// release the memory
for (int i = 0; i < ptrList.Count; i++)
{
Marshal.FreeHGlobal((IntPtr)ptrList[i]);
}
for (int i = 0; i < sidList.Count; i++)
{
UnsafeNativeMethods.LocalFree((IntPtr)sidList[i]);
}
if (records != (IntPtr)0)
{
Marshal.FreeHGlobal(records);
}
if (forestInfo != (IntPtr)0)
{
Marshal.FreeHGlobal(forestInfo);
}
if (collisionInfo != (IntPtr)0)
UnsafeNativeMethods.LsaFreeMemory(collisionInfo);
if (target != (IntPtr)0)
Marshal.FreeHGlobal(target);
if (fileTime != (IntPtr)0)
Marshal.FreeHGlobal(fileTime);
}
}
catch { throw; }
}
private void GetForestTrustInfoHelper()
{
IntPtr forestTrustInfo = (IntPtr)0;
PolicySafeHandle handle = null;
LSA_UNICODE_STRING tmpName = null;
bool impersonated = false;
IntPtr targetPtr = (IntPtr)0;
string serverName = null;
TopLevelNameCollection tmpTLNs = new TopLevelNameCollection();
StringCollection tmpExcludedTLNs = new StringCollection();
ForestTrustDomainInfoCollection tmpDomainInformation = new ForestTrustDomainInfoCollection();
// internal members
ArrayList tmpBinaryData = new ArrayList();
Hashtable tmpExcludedNameTime = new Hashtable();
ArrayList tmpBinaryDataTime = new ArrayList();
try
{
try
{
// get the target name
tmpName = new LSA_UNICODE_STRING();
targetPtr = Marshal.StringToHGlobalUni(TargetName);
UnsafeNativeMethods.RtlInitUnicodeString(tmpName, targetPtr);
serverName = Utils.GetPolicyServerName(context, true, false, source);
// do impersonation
impersonated = Utils.Impersonate(context);
// get the policy handle
handle = new PolicySafeHandle(Utils.GetPolicyHandle(serverName));
int result = UnsafeNativeMethods.LsaQueryForestTrustInformation(handle, tmpName, ref forestTrustInfo);
// check the result
if (result != 0)
{
int win32Error = UnsafeNativeMethods.LsaNtStatusToWinError(result);
if (win32Error != 0)
{
throw ExceptionHelper.GetExceptionFromErrorCode(win32Error, serverName);
}
}
try
{
if (forestTrustInfo != (IntPtr)0)
{
LSA_FOREST_TRUST_INFORMATION trustInfo = new LSA_FOREST_TRUST_INFORMATION();
Marshal.PtrToStructure(forestTrustInfo, trustInfo);
int count = trustInfo.RecordCount;
IntPtr addr = (IntPtr)0;
for (int i = 0; i < count; i++)
{
addr = Marshal.ReadIntPtr(trustInfo.Entries, i * IntPtr.Size);
LSA_FOREST_TRUST_RECORD record = new LSA_FOREST_TRUST_RECORD();
Marshal.PtrToStructure(addr, record);
if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelName)
{
IntPtr myPtr = IntPtr.Add(addr, 16);
Marshal.PtrToStructure(myPtr, record.TopLevelName);
TopLevelName TLN = new TopLevelName(record.Flags, record.TopLevelName, record.Time);
tmpTLNs.Add(TLN);
}
else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustTopLevelNameEx)
{
// get the excluded TLN and put it in our collection
IntPtr myPtr = IntPtr.Add(addr, 16);
Marshal.PtrToStructure(myPtr, record.TopLevelName);
string excludedName = Marshal.PtrToStringUni(record.TopLevelName.Buffer, record.TopLevelName.Length / 2);
tmpExcludedTLNs.Add(excludedName);
tmpExcludedNameTime.Add(excludedName, record.Time);
}
else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustDomainInfo)
{
ForestTrustDomainInformation dom = new ForestTrustDomainInformation(record.Flags, record.DomainInfo, record.Time);
tmpDomainInformation.Add(dom);
}
else if (record.ForestTrustType == LSA_FOREST_TRUST_RECORD_TYPE.ForestTrustRecordTypeLast)
{
// enumeration is done, but we might still have some unrecognized entries after that
continue;
}
else
{
int length = record.Data.Length;
byte[] byteArray = new byte[length];
if ((record.Data.Buffer != (IntPtr)0) && (length != 0))
{
Marshal.Copy(record.Data.Buffer, byteArray, 0, length);
}
tmpBinaryData.Add(byteArray);
tmpBinaryDataTime.Add(record.Time);
}
}
}
}
finally
{
UnsafeNativeMethods.LsaFreeMemory(forestTrustInfo);
}
_topLevelNames = tmpTLNs;
_excludedNames = tmpExcludedTLNs;
_domainInfo = tmpDomainInformation;
_binaryData = tmpBinaryData;
_excludedNameTime = tmpExcludedNameTime;
_binaryDataTime = tmpBinaryDataTime;
// mark it as retrieved
retrieved = true;
}
finally
{
if (impersonated)
Utils.Revert();
if (targetPtr != (IntPtr)0)
{
Marshal.FreeHGlobal(targetPtr);
}
}
}
catch { throw; }
}
}
}
| |
#region BSD License
/*
Copyright (c) 2010, NETFx
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 Clarius Consulting 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.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using Microsoft.CSharp.RuntimeBinder;
using System.Runtime.CompilerServices;
namespace System.Dynamic
{
/// <summary>
/// Provides reflection-based dynamic syntax for objects and types.
/// This class provides the extension methods <see cref="AsDynamicReflection(object)"/>
/// and <see cref="AsDynamicReflection(Type)"/> as entry points.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
static partial class DynamicReflection
{
/// <summary>
/// Provides dynamic syntax for accessing the given object members.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="obj" this="true">The object to access dinamically</param>
public static dynamic AsDynamicReflection(this object obj)
{
if (obj == null)
return null;
return new DynamicReflectionObject(obj);
}
/// <summary>
/// Provides dynamic syntax for accessing the given type members.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="type" this="true">The type to access dinamically</param>
public static dynamic AsDynamicReflection(this Type type)
{
if (type == null)
return null;
return new DynamicReflectionObject(type);
}
/// <summary>
/// Converts the type to a <see cref="TypeParameter"/> that
/// the reflection dynamic must use to make a generic
/// method invocation.
/// </summary>
/// <nuget id="netfx-System.Dynamic.Reflection" />
/// <param name="type" this="true">The type to convert</param>
public static TypeParameter AsGenericTypeParameter(this Type type)
{
return new TypeParameter(type);
}
private class DynamicReflectionObject : DynamicObject
{
private static readonly BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public;
private static readonly MethodInfo castMethod = typeof(DynamicReflectionObject).GetMethod("Cast", BindingFlags.Static | BindingFlags.NonPublic);
private object target;
private Type targetType;
public DynamicReflectionObject(object target)
{
this.target = target;
this.targetType = target.GetType();
}
public DynamicReflectionObject(Type type)
{
this.target = null;
this.targetType = type;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
if (!base.TryInvokeMember(binder, args, out result))
{
var memberName = (binder.Name == "ctor" || binder.Name == "cctor") ? "." + binder.Name : binder.Name;
var method = FindBestMatch(binder, memberName, args);
if (method != null)
{
if (binder.Name == "ctor")
{
var instance = this.target;
if (instance == null)
instance = FormatterServices.GetSafeUninitializedObject(this.targetType);
result = Invoke(method, instance, args);
result = instance.AsDynamicReflection();
}
else
{
result = AsDynamicIfNecessary(Invoke(method, this.target, args));
}
return true;
}
}
result = default(object);
return false;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!base.TryGetMember(binder, out result))
{
var field = targetType.GetField(binder.Name, flags);
var baseType = targetType.BaseType;
while (field == null && baseType != null)
{
field = baseType.GetField(binder.Name, flags);
baseType = baseType.BaseType;
}
if (field != null)
{
result = AsDynamicIfNecessary(field.GetValue(target));
return true;
}
var getter = FindBestMatch(binder, "get_" + binder.Name, new object[0]);
if (getter != null)
{
result = AsDynamicIfNecessary(getter.Invoke(this.target, null));
return true;
}
}
// \o/ If nothing else works, and the member is "target", return our target.
if (binder.Name == "target")
{
result = this.target;
return true;
}
result = default(object);
return false;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
if (!base.TrySetMember(binder, value))
{
var field = targetType.GetField(binder.Name, flags);
var baseType = targetType.BaseType;
while (field == null && baseType != null)
{
field = baseType.GetField(binder.Name, flags);
baseType = baseType.BaseType;
}
if (field != null)
{
field.SetValue(target, value);
return true;
}
var setter = FindBestMatch(binder, "set_" + binder.Name, new[] { value });
if (setter != null)
{
setter.Invoke(this.target, new[] { value });
return true;
}
}
return false;
}
public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (!base.TryGetIndex(binder, indexes, out result))
{
var indexer = FindBestMatch(binder, "get_Item", indexes);
if (indexer != null)
{
result = AsDynamicIfNecessary(indexer.Invoke(this.target, indexes));
return true;
}
}
result = default(object);
return false;
}
public override bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
if (!base.TrySetIndex(binder, indexes, value))
{
var args = indexes.Concat(new[] { value }).ToArray();
var indexer = FindBestMatch(binder, "set_Item", args);
if (indexer != null)
{
indexer.Invoke(this.target, args);
return true;
}
}
return false;
}
public override bool TryConvert(ConvertBinder binder, out object result)
{
try
{
result = castMethod.MakeGenericMethod(binder.Type).Invoke(null, new[] { this.target });
return true;
}
catch (Exception) { }
var convertible = this.target as IConvertible;
if (convertible != null)
{
try
{
result = Convert.ChangeType(convertible, binder.Type);
return true;
}
catch (Exception) { }
}
result = default(object);
return false;
}
private static object Invoke(IInvocable method, object instance, object[] args)
{
var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray();
var refArgs = new Dictionary<int, RefValue>();
var outArgs = new Dictionary<int, OutValue>();
for (int i = 0; i < method.Parameters.Count; i++)
{
if (method.Parameters[i].ParameterType.IsByRef)
{
var refArg = finalArgs[i] as RefValue;
var outArg = finalArgs[i] as OutValue;
if (refArg != null)
refArgs[i] = refArg;
else if (outArg != null)
outArgs[i] = outArg;
}
}
foreach (var refArg in refArgs)
{
finalArgs[refArg.Key] = refArg.Value.Value;
}
foreach (var outArg in outArgs)
{
finalArgs[outArg.Key] = null;
}
var result = method.Invoke(instance, finalArgs);
foreach (var refArg in refArgs)
{
refArg.Value.Value = finalArgs[refArg.Key];
}
foreach (var outArg in outArgs)
{
outArg.Value.Value = finalArgs[outArg.Key];
}
return result;
}
/// <summary>
/// Converts dynamic objects to object, which may cause unboxing
/// of the wrapped dynamic such as in our own DynamicReflectionObject type.
/// </summary>
private static object UnboxDynamic(object maybeDynamic)
{
var dyn = maybeDynamic as DynamicObject;
if (dyn == null)
return maybeDynamic;
var binder = (ConvertBinder)Microsoft.CSharp.RuntimeBinder.Binder.Convert(CSharpBinderFlags.ConvertExplicit, typeof(object), typeof(DynamicReflectionObject));
//var site = CallSite<Func<CallSite, object, object>>.Create(binder);
object result;
dyn.TryConvert(binder, out result);
return result;
}
private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, string memberName, object[] args)
{
var finalArgs = args.Where(x => !(x is TypeParameter)).Select(UnboxDynamic).ToArray();
var genericTypeArgs = new List<Type>();
if (binder is InvokeBinder || binder is InvokeMemberBinder)
{
IEnumerable typeArgs = binder.AsDynamicReflection().TypeArguments;
genericTypeArgs.AddRange(typeArgs.Cast<Type>());
genericTypeArgs.AddRange(args.OfType<TypeParameter>().Select(x => x.Type));
}
var method = FindBestMatch(binder, finalArgs, genericTypeArgs, this.targetType
.GetMethods(flags)
.Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length)
.Select(x => new MethodInvocable(x)));
if (method == null)
{
// Fallback to explicitly implemented members.
method = FindBestMatch(binder, finalArgs, genericTypeArgs, this.targetType
.GetInterfaces()
.SelectMany(
iface => this.targetType
.GetInterfaceMap(iface)
.TargetMethods.Select(x => new { Interface = iface, Method = x }))
.Where(x =>
x.Method.GetParameters().Length == finalArgs.Length &&
x.Method.Name.Replace(x.Interface.FullName.Replace('+', '.') + ".", "") == memberName)
.Select(x => (IInvocable)new MethodInvocable(x.Method))
.Concat(this.targetType.GetConstructors(flags)
.Where(x => x.Name == memberName && x.GetParameters().Length == finalArgs.Length)
.Select(x => new ConstructorInvocable(x)))
.Distinct());
}
var methodInvocable = method as MethodInvocable;
if (method != null && methodInvocable != null && methodInvocable.Method.IsGenericMethodDefinition)
{
method = new MethodInvocable(methodInvocable.Method.MakeGenericMethod(genericTypeArgs.ToArray()));
}
return method;
}
private IInvocable FindBestMatch(DynamicMetaObjectBinder binder, object[] args, List<Type> genericArgs, IEnumerable<IInvocable> candidates)
{
var result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.ExactType);
if (result == null)
result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.AssignableFrom);
if (result == null)
result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.ExactTypeGenericHint);
if (result == null)
result = FindBestMatchImpl(binder, args, genericArgs, candidates, MatchingStyle.AssignableFromGenericHint);
return result;
}
/// <summary>
/// Finds the best match among the candidates.
/// </summary>
/// <param name="binder">The binder that is requesting the match.</param>
/// <param name="args">The args passed in to the invocation.</param>
/// <param name="genericArgs">The generic args if any.</param>
/// <param name="candidates">The candidate methods to use for the match..</param>
/// <param name="matching">if set to <c>MatchingStyle.AssignableFrom</c>, uses a more lax matching approach for arguments, with IsAssignableFrom instead of == for arg type,
/// and <c>MatchingStyle.GenericTypeHint</c> tries to use the generic arguments as type hints if they match the # of args.</param>
private IInvocable FindBestMatchImpl(DynamicMetaObjectBinder binder, object[] args, List<Type> genericArgs, IEnumerable<IInvocable> candidates, MatchingStyle matching)
{
dynamic dynamicBinder = binder.AsDynamicReflection();
for (int i = 0; i < args.Length; i++)
{
var index = i;
if (args[index] != null)
{
switch (matching)
{
case MatchingStyle.ExactType:
candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsAssignableFrom(GetArgumentType(args[index])));
break;
case MatchingStyle.AssignableFrom:
candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsEquivalentTo(GetArgumentType(args[index])));
break;
case MatchingStyle.ExactTypeGenericHint:
candidates = candidates.Where(x => x.Parameters.Count == genericArgs.Count &&
x.Parameters[index].ParameterType.IsEquivalentTo(genericArgs[index]));
break;
case MatchingStyle.AssignableFromGenericHint:
candidates = candidates.Where(x => x.Parameters.Count == genericArgs.Count &&
x.Parameters[index].ParameterType.IsAssignableFrom(genericArgs[index]));
break;
default:
break;
}
}
IEnumerable enumerable = dynamicBinder.ArgumentInfo;
// The binder has the extra argument info for the "this" parameter at the beginning.
if (enumerable.Cast<object>().ToList()[index + 1].AsDynamicReflection().IsByRef)
candidates = candidates.Where(x => x.Parameters[index].ParameterType.IsByRef);
// Only filter by matching generic argument count if the generics isn't being used as parameter type hints.
if (genericArgs.Count > 0 && matching != MatchingStyle.AssignableFromGenericHint && matching != MatchingStyle.ExactTypeGenericHint)
candidates = candidates.Where(x => x.IsGeneric && x.GenericParameters == genericArgs.Count);
}
return candidates.FirstOrDefault();
}
private static Type GetArgumentType(object arg)
{
if (arg is RefValue || arg is OutValue)
return arg.GetType().GetGenericArguments()[0].MakeByRefType();
if (arg is DynamicReflectionObject)
return ((DynamicReflectionObject)arg).target.GetType();
return arg.GetType();
}
private object AsDynamicIfNecessary(object value)
{
if (value == null)
return value;
var type = value.GetType();
if (type.IsClass && type != typeof(string))
return value.AsDynamicReflection();
return value;
}
private static T Cast<T>(object target)
{
return (T)target;
}
private enum MatchingStyle
{
ExactType,
AssignableFrom,
ExactTypeGenericHint,
AssignableFromGenericHint,
}
private interface IInvocable
{
bool IsGeneric { get; }
int GenericParameters { get; }
IList<ParameterInfo> Parameters { get; }
object Invoke(object obj, object[] parameters);
}
private class MethodInvocable : IInvocable
{
private MethodInfo method;
private Lazy<IList<ParameterInfo>> parameters;
public MethodInvocable(MethodInfo method)
{
this.method = method;
this.parameters = new Lazy<IList<ParameterInfo>>(() => this.method.GetParameters());
}
public object Invoke(object obj, object[] parameters)
{
return this.method.Invoke(obj, parameters);
}
public IList<ParameterInfo> Parameters
{
get { return this.parameters.Value; }
}
public MethodInfo Method { get { return this.method; } }
public bool IsGeneric { get { return this.method.IsGenericMethodDefinition; } }
public int GenericParameters { get { return this.method.GetGenericArguments().Length; } }
}
private class ConstructorInvocable : IInvocable
{
private ConstructorInfo ctor;
private Lazy<IList<ParameterInfo>> parameters;
public ConstructorInvocable(ConstructorInfo ctor)
{
this.ctor = ctor;
this.parameters = new Lazy<IList<ParameterInfo>>(() => this.ctor.GetParameters());
}
public object Invoke(object obj, object[] parameters)
{
return this.ctor.Invoke(obj, parameters);
}
public IList<ParameterInfo> Parameters
{
get { return this.parameters.Value; }
}
public bool IsGeneric { get { return false; } }
public int GenericParameters { get { return 0; } }
}
}
}
}
| |
/* Genuine Channels product.
*
* Copyright (c) 2002-2007 Dmitry Belikov. All rights reserved.
*
* This source code comes under and must be used and distributed according to the Genuine Channels license agreement.
*/
using System;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using Belikov.GenuineChannels.BufferPooling;
using Belikov.GenuineChannels.Logbook;
using Belikov.GenuineChannels.Messaging;
namespace Belikov.GenuineChannels.GenuineTcp
{
/// <summary>
/// Implements a stream reading data from a socket synchronously.
/// Automatically initiates receiving after the current message is read up entirely.
/// </summary>
internal class SyncSocketReadingStream : Stream, IDisposable
{
/// <summary>
/// Constructs an instance of the SyncSocketReadingStream class.
/// </summary>
/// <param name="tcpConnectionManager">TCP Connection Manager.</param>
/// <param name="tcpSocketInfo">The connection.</param>
/// <param name="receiveTimeout">The moment at which the message must be received entirely.</param>
/// <param name="automaticallyContinueReading">Indicates whether this instance will automatically initiate reading of the next message from the specified connection.</param>
public SyncSocketReadingStream(TcpConnectionManager tcpConnectionManager, TcpSocketInfo tcpSocketInfo, int receiveTimeout, bool automaticallyContinueReading)
{
this._readBuffer = BufferPool.ObtainBuffer();
this._tcpConnectionManager = tcpConnectionManager;
this._tcpSocketInfo = tcpSocketInfo;
this._receiveTimeout = receiveTimeout;
this._automaticallyContinueReading = automaticallyContinueReading;
// first, complete receiving of the first header
// it may read up the entire message and release the underlying connection
ReadNextPortion(true);
}
private TcpConnectionManager _tcpConnectionManager;
private TcpSocketInfo _tcpSocketInfo;
private int _receiveTimeout;
private byte[] _readBuffer;
private bool _automaticallyContinueReading;
private int _validLength;
private int _currentPosition;
private int _currentPacketSize;
private int _currentPacketBytesRead;
private bool _messageRead;
/// <summary>
/// The unique identifier of the current stream.
/// </summary>
public int DbgStreamId
{
get
{
return this._dbgStreamId;
}
}
private int _dbgStreamId = Interlocked.Increment(ref _totalDbgStreamId);
private static int _totalDbgStreamId = 0;
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer.</returns>
public override int Read(byte[] buffer, int offset, int count)
{
int size = 0;
int resultSize = 0;
for ( ; ; )
{
// check whether we have the next portion
if (this._currentPosition < this._validLength)
{
size = Math.Min(this._validLength - this._currentPosition, count);
Buffer.BlockCopy(this._readBuffer, this._currentPosition, buffer, offset, size);
this._currentPosition += size;
count -= size;
resultSize += size;
offset += size;
}
// recycle the buffer if possible
if (this._readBuffer != null && this._messageRead && this._currentPacketBytesRead >= this._currentPacketSize && this._currentPosition >= this._validLength)
{
BufferPool.RecycleBuffer(this._readBuffer);
this._readBuffer = null;
}
if (count <= 0 || (this._messageRead && this._currentPacketBytesRead >= this._currentPacketSize))
return resultSize;
ReadNextPortion(false);
}
}
/// <summary>
/// Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.
/// </summary>
/// <returns>The unsigned byte cast to an Int32, or -1 if at the end of the stream.</returns>
public override int ReadByte()
{
try
{
// get a byte
if (this._currentPosition < this._validLength)
return this._readBuffer[ this._currentPosition++ ];
ReadNextPortion(false);
if (this._currentPosition < this._validLength)
return this._readBuffer[ this._currentPosition++ ];
return -1;
}
finally
{
// recycle the buffer if possible
if (this._readBuffer != null && this._messageRead && this._currentPacketBytesRead >= this._currentPacketSize && this._currentPosition >= this._validLength)
{
BufferPool.RecycleBuffer(this._readBuffer);
this._readBuffer = null;
}
}
}
/// <summary>
/// Synchronously reads the next network packet if it is available.
/// </summary>
/// <param name="deriveHeader">Indicates whether it is necessary to take header from the provided connection.</param>
private void ReadNextPortion(bool deriveHeader)
{
int bytesRead = 0;
int lengthToRead = 0;
if (! deriveHeader)
{
// try to read the remaining part of the packet
if (this._currentPacketBytesRead < this._currentPacketSize)
{
// read the next part of the packet
lengthToRead = Math.Min(this._currentPacketSize - this._currentPacketBytesRead, this._readBuffer.Length);
this._validLength = this.ReadFromSocket(this._readBuffer, 0, lengthToRead);
if (this._validLength == 0)
throw GenuineExceptions.Get_Receive_Portion();
// Fixed in 2.5.9.7
//this._tcpSocketInfo.ITransportContext.ConnectionManager.IncreaseBytesReceived(this._validLength);
this._currentPacketBytesRead += this._validLength;
this._currentPosition = 0;
if (this._currentPacketBytesRead == this._currentPacketSize && this._messageRead)
{
this.ReadingCompleted();
}
return ;
}
// the underlying stream ends
if (this._messageRead)
return ;
// prepare for reading a header
this._currentPosition = 0;
}
lengthToRead = TcpConnectionManager.HEADER_SIZE;
if (deriveHeader)
{
if (this._tcpSocketInfo.ReceivingBufferCurrentPosition > 0)
Buffer.BlockCopy(this._tcpSocketInfo.ReceivingHeaderBuffer, 0, this._readBuffer, 0, this._tcpSocketInfo.ReceivingBufferCurrentPosition);
this._currentPosition = this._tcpSocketInfo.ReceivingBufferCurrentPosition;
}
// read the header
while (this._currentPosition < lengthToRead)
{
bytesRead = this.ReadFromSocket(this._readBuffer, this._currentPosition, lengthToRead - this._currentPosition);
if (bytesRead == 0)
throw GenuineExceptions.Get_Receive_Portion();
// Fixed in 2.5.9.7
//this._tcpSocketInfo.ITransportContext.ConnectionManager.IncreaseBytesReceived(bytesRead);
this._currentPosition += bytesRead;
}
// parse the header
if (this._readBuffer[0] != MessageCoder.COMMAND_MAGIC_CODE)
throw GenuineExceptions.Get_Receive_IncorrectData();
this._currentPacketSize = MessageCoder.ReadInt32(this._readBuffer, 1);
this._messageRead = this._readBuffer[5] != 0;
this._currentPacketBytesRead = 0;
// and read the part of the packet
if (this._currentPacketBytesRead < this._currentPacketSize)
{
// read the next part of the packet
lengthToRead = Math.Min(this._currentPacketSize - this._currentPacketBytesRead, this._readBuffer.Length);
this._validLength = this.ReadFromSocket(this._readBuffer, 0, lengthToRead);
if (this._validLength == 0)
throw GenuineExceptions.Get_Receive_Portion();
// Fixed in 2.5.9.7
//this._tcpSocketInfo.ITransportContext.ConnectionManager.IncreaseBytesReceived(this._validLength);
this._currentPacketBytesRead += this._validLength;
this._currentPosition = 0;
}
if (this._currentPacketBytesRead == this._currentPacketSize && this._messageRead)
{
this.ReadingCompleted();
}
}
/// <summary>
/// Completes reading from the connection.
/// </summary>
private void ReadingCompleted()
{
if (this._automaticallyContinueReading)
this._tcpConnectionManager.LowLevel_HalfSync_StartReceiving(this._tcpSocketInfo);
}
/// <summary>
/// Reads data from the socket.
/// </summary>
/// <param name="buffer">An array of type Byte that is the storage location for received data.</param>
/// <param name="offset">The location in buffer to store the received data.</param>
/// <param name="count">The number of bytes to receive.</param>
/// <returns>The number of bytes read.</returns>
public int ReadFromSocket(byte[] buffer, int offset, int count)
{
BinaryLogWriter binaryLogWriter = this._tcpConnectionManager.ITransportContext.BinaryLogWriter;
try
{
int millisecondsRemained = GenuineUtility.GetMillisecondsLeft(this._receiveTimeout);
if (millisecondsRemained <= 0)
throw GenuineExceptions.Get_Send_ServerDidNotReply();
this._tcpSocketInfo.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, millisecondsRemained);
int bytesReceived = this._tcpSocketInfo.Socket.Receive(buffer, offset, count, SocketFlags.None);
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
binaryLogWriter.WriteTransportContentEvent(LogCategory.LowLevelTransport, "SyncSocketReadingStream.ReadFromSocket",
LogMessageType.LowLevelTransport_SyncReceivingCompleted, null, null, this._tcpSocketInfo.Remote,
binaryLogWriter[LogCategory.LowLevelTransport] > 1 ? new MemoryStream(buffer, offset, bytesReceived) : null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
this._tcpSocketInfo.DbgConnectionId, bytesReceived,
this._tcpSocketInfo.Socket.RemoteEndPoint.ToString(), null, null,
"Socket.Receive(). Bytes received: {0}.", bytesReceived);
this._tcpConnectionManager.IncreaseBytesReceived(bytesReceived);
return bytesReceived;
}
catch (Exception ex)
{
// LOG:
if ( binaryLogWriter != null && binaryLogWriter[LogCategory.LowLevelTransport] > 0 )
binaryLogWriter.WriteEvent(LogCategory.LowLevelTransport, "SyncSocketReadingStream.ReadFromSocket",
LogMessageType.LowLevelTransport_SyncReceivingCompleted, ex, null, this._tcpSocketInfo.Remote, null,
GenuineUtility.CurrentThreadId, Thread.CurrentThread.Name,
null, null, this._tcpSocketInfo.DbgConnectionId, 0, 0, 0, null, null, null, null,
"Socket.Receive() failed.");
throw;
}
}
/// <summary>
/// Skips the remaining part of the message.
/// </summary>
public new void Dispose()
{
this.Close();
}
/// <summary>
/// Closes the current stream and releases all resources associated with the current stream.
/// </summary>
public override void Close()
{
this.SkipMessage();
}
/// <summary>
/// Skips the current message in the transport stream.
/// </summary>
public void SkipMessage()
{
while (! this.IsReadingFinished)
ReadNextPortion(false);
}
/// <summary>
/// Gets an indication whether the message reading from the underlying provider was completed.
/// </summary>
public bool IsReadingFinished
{
get
{
return this._currentPacketBytesRead >= this._currentPacketSize && this._messageRead;
}
}
/// <summary>
/// Gets an indication whether the message has been read from this stream.
/// </summary>
public bool IsMessageProcessed
{
get
{
return this._currentPacketBytesRead >= this._currentPacketSize && this._messageRead && this._currentPosition >= this._validLength;
}
}
#region -- Insignificant stream members ----------------------------------------------------
/// <summary>
/// Writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
public override bool CanRead
{
get
{
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
public override bool CanSeek
{
get
{
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
public override bool CanWrite
{
get
{
return true;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
public override long Length
{
get
{
throw new NotSupportedException();
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// Always fires NotSupportedException exception.
/// </summary>
public override long Position
{
get
{
throw new NotSupportedException();
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Begins an asynchronous read operation.
/// </summary>
/// <param name="buffer">The buffer to read the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous read request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous read, which could still be pending.</returns>
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Begins an asynchronous write operation.
/// </summary>
/// <param name="buffer">The buffer to write data from.</param>
/// <param name="offset">The byte offset in buffer from which to begin writing.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request from other requests.</param>
/// <returns>An IAsyncResult that represents the asynchronous write, which could still be pending.</returns>
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
/// <summary>
/// Waits for the pending asynchronous read to complete.
/// </summary>
/// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
/// <returns>The number of bytes read from the stream, between zero (0) and the number of bytes you requested. Streams only return zero (0) at the end of the stream, otherwise, they should block until at least one byte is available.</returns>
public override int EndRead(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Ends an asynchronous write operation.
/// </summary>
/// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
public override void EndWrite(IAsyncResult asyncResult)
{
throw new NotSupportedException();
}
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
public override void Flush()
{
}
/// <summary>
/// Sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// Sets the length of the current stream.
/// </summary>
/// <param name="val">The desired length of the current stream in bytes.</param>
public override void SetLength(long val)
{
throw new NotSupportedException();
}
#endregion
}
}
| |
//
// Copyright 2012-2013, Xamarin 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.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
#if __UNIFIED__
using UIKit;
using Foundation;
using CoreAnimation;
using CoreGraphics;
using CGRect = global::System.Drawing.RectangleF;
#else
using MonoTouch.UIKit;
using MonoTouch.Foundation;
using MonoTouch.CoreAnimation;
using MonoTouch.CoreGraphics;
using System.Drawing;
using CGRect = global::System.Drawing.RectangleF;
using CGPoint = global::System.Drawing.PointF;
using CGSize = global::System.Drawing.SizeF;
using nfloat = global::System.Single;
using nint = global::System.Int32;
using nuint = global::System.UInt32;
#endif
using Xamarin.Auth;
using Xamarin.Utilities.iOS;
namespace Xamarin.Social
{
public class ShareViewController : UIViewController
{
Service service;
Item item;
List<Account> accounts = new List<Account>();
Action<ShareResult> completionHandler;
Task<IEnumerable<Account>> futureAccounts;
UITextView textEditor;
ProgressLabel progress;
TextLengthLabel textLengthLabel;
UILabel linksLabel;
ChoiceField accountField = null;
bool sharing = false;
bool canceledFromOutside = false;
UIAlertView accountsAlert;
static UIFont TextEditorFont = UIFont.SystemFontOfSize (18);
static readonly UIColor FieldColor = UIColor.FromRGB (56, 84, 135);
internal ShareViewController (Service service, Item item, Action<ShareResult> completionHandler)
{
this.service = service;
this.item = item;
this.completionHandler = completionHandler;
Title = NSBundle.MainBundle.LocalizedString (service.ShareTitle, "Title of Share dialog");
View.BackgroundColor = UIColor.White;
if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0))
EdgesForExtendedLayout = UIRectEdge.None;
futureAccounts = service.GetAccountsAsync ();
}
public override void ViewDidLoad()
{
BuildUI();
base.ViewDidLoad();
}
public override void ViewDidAppear (bool animated)
{
base.ViewDidAppear (animated);
var fa = Interlocked.Exchange (ref futureAccounts, null);
if (fa != null) {
fa.ContinueWith (t => {
accounts.AddRange (t.Result);
foreach (string username in accounts.Select (a => a.Username))
accountField.Items.Add (username);
CheckForAccounts();
}, TaskScheduler.FromCurrentSynchronizationContext());
} else if (canceledFromOutside)
canceledFromOutside = false;
else
CheckForAccounts();
}
void CheckForAccounts ()
{
if (accounts.Count == 0) {
var title = "No " + service.Title + " Accounts";
var msg = "There are no configured " + service.Title + " accounts. " +
"Would you like to add one?";
accountsAlert = new UIAlertView (
title,
msg,
null,
"Cancel",
"Add Account");
accountsAlert.Clicked += (sender, e) => {
if (e.ButtonIndex == 1) {
Authenticate ();
} else {
completionHandler (ShareResult.Cancelled);
}
};
accountsAlert.Show ();
} else {
textEditor.BecomeFirstResponder ();
}
}
void Authenticate ()
{
var vc = service.GetAuthenticateUI (account => {
if (account != null)
accounts.Add (account);
else
canceledFromOutside = true;
DismissViewController (true, () => {
if (account != null) {
accountField.Items.Add (account.Username);
textEditor.BecomeFirstResponder ();
} else {
completionHandler (ShareResult.Cancelled);
}
});
});
vc.ModalTransitionStyle = UIModalTransitionStyle.FlipHorizontal;
PresentViewController (vc, true, null);
}
void BuildUI ()
{
var b = View.Bounds;
var statusHeight = 22.0f;
//
// Account Field
//
var fieldHeight = 33;
accountField = new ChoiceField (
#if ! __UNIFIED__
new RectangleF (0, b.Y, b.Width, 33),
#else
new RectangleF (0, (float)b.Y, (float)b.Width, 33),
#endif
this,
NSBundle.MainBundle.LocalizedString ("From", "From title when sharing"));
View.AddSubview (accountField);
b.Y += fieldHeight;
b.Height -= fieldHeight;
//
// Text Editor
//
var editorHeight = b.Height;
if (service.HasMaxTextLength || item.Links.Count > 0) {
editorHeight -= statusHeight;
}
textEditor = new UITextView (
#if ! __UNIFIED__
new RectangleF (0, b.Y, b.Width, editorHeight))
#else
new RectangleF (0, (float) b.Y, (float) b.Width, (float)editorHeight))
#endif
{
Font = TextEditorFont,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight,
Text = item.Text,
};
textEditor.Delegate = new TextEditorDelegate (this);
View.AddSubview (textEditor);
//
// Icons
//
if (item.Images.Count > 0) {
var rem = 4.0f;
RectangleF f;
var x = b.Right - AttachmentIcon.Size - 8 - rem*(item.Images.Count - 1);
var y = textEditor.Frame.Y + 8;
#if ! __UNIFIED__
f = textEditor.Frame;
f.Width = x - 8 - f.X;
#else
f = (RectangleF)textEditor.Frame;
f.Width = (float)x - 8 - f.X;
#endif
textEditor.Frame = f;
foreach (var i in item.Images) {
var icon = new ImageIcon (i.Image);
#if ! __UNIFIED__
f = icon.Frame;
f.X = x;
f.Y = y;
#else
f = (RectangleF) icon.Frame;
f.X = (float)x;
f.Y = (float)y;
#endif
icon.Frame = f;
View.AddSubview (icon);
x += rem;
y += rem;
}
}
//
// Remaining Text Length
//
if (service.HasMaxTextLength) {
textLengthLabel = new TextLengthLabel (
#if ! __UNIFIED__
new RectangleF (4, b.Bottom - statusHeight, textEditor.Frame.Width - 8, statusHeight),
#else
new RectangleF (4, (float)(b.Bottom - statusHeight), (float)(textEditor.Frame.Width - 8), statusHeight),
#endif
service.MaxTextLength) {
TextLength = service.GetTextLength (item),
};
View.AddSubview (textLengthLabel);
}
//
// Links Label
//
if (item.Links.Count > 0) {
linksLabel = new UILabel (
#if ! __UNIFIED__
new RectangleF (4, b.Bottom - statusHeight, textEditor.Frame.Width - 66, statusHeight)) {
#else
new RectangleF (4, (float)(b.Bottom - statusHeight), (float)(textEditor.Frame.Width - 66), statusHeight)) {
#endif
TextColor = UIColor.FromRGB (124, 124, 124),
AutoresizingMask =
UIViewAutoresizing.FlexibleTopMargin |
UIViewAutoresizing.FlexibleBottomMargin |
UIViewAutoresizing.FlexibleWidth,
UserInteractionEnabled = false,
BackgroundColor = UIColor.Clear,
Font = UIFont.SystemFontOfSize (16),
LineBreakMode = UILineBreakMode.HeadTruncation,
};
if (item.Links.Count == 1) {
linksLabel.Text = item.Links[0].AbsoluteUri;
}
else {
linksLabel.Text = string.Format (
NSBundle.MainBundle.LocalizedString ("{0} links", "# of links label"),
item.Links.Count);
}
View.AddSubview (linksLabel);
}
//
// Navigation Items
//
NavigationItem.LeftBarButtonItem = new UIBarButtonItem (
UIBarButtonSystemItem.Cancel,
delegate {
completionHandler (ShareResult.Cancelled);
});
NavigationItem.RightBarButtonItem = new UIBarButtonItem (
NSBundle.MainBundle.LocalizedString ("Send", "Send button text when sharing"),
UIBarButtonItemStyle.Done,
HandleSend);
//
// Watch for the keyboard
//
NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.DidShowNotification, HandleKeyboardDidShow);
NSNotificationCenter.DefaultCenter.AddObserver (UIKeyboard.WillHideNotification, HandleKeyboardDidHide);
}
void HandleSend (object sender, EventArgs e)
{
if (sharing) return;
item.Text = textEditor.Text;
StartSharing ();
var account = accounts.FirstOrDefault ();
if (accounts.Count > 1 && accountField != null) {
account = accounts.FirstOrDefault (x => x.Username == accountField.SelectedItem);
}
try {
service.ShareItemAsync (item, account).ContinueWith (shareTask => {
StopSharing ();
if (shareTask.IsFaulted) {
this.ShowError ("Share Error", shareTask.Exception);
}
else {
completionHandler (ShareResult.Done);
}
}, TaskScheduler.FromCurrentSynchronizationContext ());
}
catch (Exception ex) {
StopSharing ();
this.ShowError ("Share Error", ex);
}
}
void StartSharing ()
{
sharing = true;
NavigationItem.RightBarButtonItem.Enabled = false;
if (progress == null) {
progress = new ProgressLabel (NSBundle.MainBundle.LocalizedString ("Sending...", "Sending... status message when sharing"));
NavigationItem.TitleView = progress;
progress.StartAnimating ();
}
}
void StopSharing ()
{
sharing = false;
NavigationItem.RightBarButtonItem.Enabled = true;
if (progress != null) {
progress.StopAnimating ();
NavigationItem.TitleView = null;
progress = null;
}
}
public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation)
{
return true;
}
void ResignFirstResponders ()
{
textEditor.ResignFirstResponder ();
}
void HandleKeyboardDidShow (NSNotification n)
{
var size = UIKeyboard.BoundsFromNotification (n).Size;
var f = textEditor.Frame;
f.Height -= size.Height;
textEditor.Frame = f;
if (textLengthLabel != null) {
f = textLengthLabel.Frame;
f.Y -= size.Height;
textLengthLabel.Frame = f;
}
if (linksLabel != null) {
f = linksLabel.Frame;
f.Y -= size.Height;
linksLabel.Frame = f;
}
}
void HandleKeyboardDidHide (NSNotification n)
{
var size = UIKeyboard.BoundsFromNotification (n).Size;
UIView.BeginAnimations ("kbd");
var f = textEditor.Frame;
f.Height += size.Height;
textEditor.Frame = f;
if (textLengthLabel != null) {
f = textLengthLabel.Frame;
f.Y += size.Height;
textLengthLabel.Frame = f;
}
if (linksLabel != null) {
f = linksLabel.Frame;
f.Y += size.Height;
linksLabel.Frame = f;
}
UIView.CommitAnimations ();
}
class TextEditorDelegate : UITextViewDelegate
{
ShareViewController controller;
public TextEditorDelegate (ShareViewController controller)
{
this.controller = controller;
}
public override void Changed (UITextView textView)
{
controller.item.Text = textView.Text;
if (controller.textLengthLabel != null) {
controller.textLengthLabel.TextLength =
controller.service.GetTextLength (controller.item);
}
}
}
class TextLengthLabel : UILabel
{
int maxLength;
int textLength;
static readonly UIColor okColor = UIColor.FromRGB (124, 124, 124);
static readonly UIColor errorColor = UIColor.FromRGB (166, 80, 80);
public int TextLength {
get {
return textLength;
}
set {
textLength = value;
Update ();
}
}
public TextLengthLabel (RectangleF frame, int maxLength)
: base (frame)
{
this.maxLength = maxLength;
this.textLength = 0;
UserInteractionEnabled = false;
BackgroundColor = UIColor.Clear;
AutoresizingMask =
UIViewAutoresizing.FlexibleWidth |
UIViewAutoresizing.FlexibleBottomMargin |
UIViewAutoresizing.FlexibleTopMargin;
TextAlignment = UITextAlignment.Right;
Font = UIFont.BoldSystemFontOfSize (16);
TextColor = okColor;
}
void Update ()
{
var rem = maxLength - textLength;
Text = rem.ToString ();
if (rem < 0) {
TextColor = errorColor;
}
else {
TextColor = okColor;
}
}
}
abstract class AttachmentIcon : UIImageView
{
public static float Size { get { return 72; } }
static readonly CGColor borderColor = new CGColor (0.75f, 0.75f, 0.75f);
static readonly CGColor shadowColor = new CGColor (0.25f, 0.25f, 0.25f);
public AttachmentIcon ()
: base (new RectangleF (0, 0, Size, Size))
{
ContentMode = UIViewContentMode.ScaleAspectFill;
ClipsToBounds = true;
AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin;
Layer.CornerRadius = 4;
Layer.ShadowOffset = new SizeF (0, 0);
Layer.ShadowColor = shadowColor;
Layer.ShadowRadius = 4;
Layer.ShadowOpacity = 1.0f;
Layer.BorderColor = borderColor;
Layer.BorderWidth = 1;
}
}
class ImageIcon : AttachmentIcon
{
public ImageIcon (UIImage image)
{
Image = image;
}
}
abstract class Field : UIView
{
public ShareViewController Controller { get; private set; }
public UILabel TitleLabel { get; private set; }
public Field (RectangleF frame, ShareViewController controller, string title)
: base (frame)
{
Controller = controller;
BackgroundColor = UIColor.White;
Opaque = true;
AutoresizingMask = UIViewAutoresizing.FlexibleWidth;
TitleLabel = new UILabel () {
BackgroundColor = UIColor.White,
Font = TextEditorFont,
Text = title + ":",
TextColor = UIColor.Gray,
};
#if ! __UNIFIED__
TitleLabel.Frame = new RectangleF (8, 0, frame.Width, frame.Height - 1);
#else
TitleLabel.Frame = new RectangleF (8, 0, (float)frame.Width, frame.Height - 1);
#endif
AddSubview (TitleLabel);
}
#if ! __UNIFIED__
public override void Draw (RectangleF rect)
#else
public void Draw (RectangleF rect)
#endif
{
var b = Bounds;
using (var c = UIGraphics.GetCurrentContext ()) {
UIColor.LightGray.SetStroke ();
c.SetLineWidth (1.0f);
c.MoveTo (0, b.Bottom);
c.AddLineToPoint (b.Right, b.Bottom);
c.StrokePath ();
}
}
}
class ChoiceField : Field
{
public string SelectedItem {
get { return Picker.SelectedItem; }
}
public LabelButton ValueLabel { get; private set; }
public CheckedPickerView Picker { get; private set; }
public IList<string> Items {
get { return Picker.Items; }
set { Picker.Items = value; }
}
public ChoiceField (RectangleF frame, ShareViewController controller, string title)
: base (frame, controller, title)
{
ValueLabel = new LabelButton () {
BackgroundColor = UIColor.White,
Font = TextEditorFont,
TextColor = UIColor.DarkTextColor,
AutoresizingMask = UIViewAutoresizing.FlexibleWidth,
};
var tf = TitleLabel.Frame;
#if ! __UNIFIED__
ValueLabel.Frame = new RectangleF (tf.Right, 0, frame.Width - tf.Right, frame.Height - 1);
#else
ValueLabel.Frame = new RectangleF ((float)tf.Right, 0, (float)((nfloat)frame.Width - tf.Right), (float)(frame.Height - 1));
#endif
ValueLabel.TouchUpInside += HandleTouchUpInside;
AddSubview (ValueLabel);
Picker = new CheckedPickerView (new RectangleF (0, 0, 320, 216));
Picker.Hidden = true;
Picker.SelectedItemChanged += delegate {
ValueLabel.Text = Picker.SelectedItem;
};
controller.View.AddSubview (Picker);
ValueLabel.Text = Picker.SelectedItem;
}
void HandleTouchUpInside (object sender, EventArgs e)
{
if (Items.Count > 1) {
Controller.ResignFirstResponders ();
var v = Controller.View;
Picker.Hidden = false;
#if ! __UNIFIED__
Picker.Frame = new RectangleF (0, v.Bounds.Bottom - 216, 320, 216);
#else
Picker.Frame = new RectangleF (0, (float)(v.Bounds.Bottom - 216), 320, 216);
#endif
v.BringSubviewToFront (Picker);
}
}
}
class LabelButton : UILabel
{
public event EventHandler TouchUpInside;
public LabelButton ()
{
UserInteractionEnabled = true;
}
public override void TouchesBegan (NSSet touches, UIEvent evt)
{
TextColor = FieldColor;
}
public override void TouchesEnded (NSSet touches, UIEvent evt)
{
TextColor = UIColor.DarkTextColor;
var t = touches.ToArray<UITouch> ().First ();
if (Bounds.Contains (t.LocationInView (this))) {
var ev = TouchUpInside;
if (ev != null) {
ev (this, EventArgs.Empty);
}
}
}
public override void TouchesCancelled (NSSet touches, UIEvent evt)
{
TextColor = UIColor.DarkTextColor;
}
}
}
}
| |
using System;
using Mindscape.LightSpeed;
using Mindscape.LightSpeed.Validation;
using Mindscape.LightSpeed.Linq;
namespace TwitterRuRu
{
[Serializable]
[System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
[System.ComponentModel.DataObject]
[Table(IdentityMethod=IdentityMethod.IdentityColumn)]
public partial class Accounts : Entity<int>
{
#region Fields
[Column("AspNetUser_Id")]
private string _aspNetUserId;
#endregion
#region Field attribute and view names
/// <summary>Identifies the AspNetUserId entity attribute.</summary>
public const string AspNetUserIdField = "AspNetUserId";
#endregion
#region Relationships
[ReverseAssociation("Accounts")]
private readonly EntityHolder<AspNetUser> _aspNetUser = new EntityHolder<AspNetUser>();
#endregion
#region Properties
[System.Diagnostics.DebuggerNonUserCode]
public AspNetUser AspNetUser
{
get { return Get(_aspNetUser); }
set { Set(_aspNetUser, value); }
}
/// <summary>Gets or sets the ID for the <see cref="AspNetUser" /> property.</summary>
[System.Diagnostics.DebuggerNonUserCode]
public string AspNetUserId
{
get { return Get(ref _aspNetUserId, "AspNetUserId"); }
set { Set(ref _aspNetUserId, value, "AspNetUserId"); }
}
#endregion
}
[Serializable]
[System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
[System.ComponentModel.DataObject]
[Table("AspNetUsers")]
public partial class AspNetUser : Entity<string>
{
#region Fields
private string _userName;
private string _passwordHash;
private string _securityStamp;
[ValidatePresence]
[ValidateLength(0, 128)]
private string _discriminator;
#endregion
#region Field attribute and view names
/// <summary>Identifies the UserName entity attribute.</summary>
public const string UserNameField = "UserName";
/// <summary>Identifies the PasswordHash entity attribute.</summary>
public const string PasswordHashField = "PasswordHash";
/// <summary>Identifies the SecurityStamp entity attribute.</summary>
public const string SecurityStampField = "SecurityStamp";
/// <summary>Identifies the Discriminator entity attribute.</summary>
public const string DiscriminatorField = "Discriminator";
#endregion
#region Relationships
[ReverseAssociation("AspNetUser")]
private readonly EntityCollection<Accounts> _accounts = new EntityCollection<Accounts>();
[ReverseAssociation("AspNetUserTweet")]
private readonly EntityCollection<Tweets> _tweets = new EntityCollection<Tweets>();
#endregion
#region Properties
[System.Diagnostics.DebuggerNonUserCode]
public EntityCollection<Accounts> Accounts
{
get { return Get(_accounts); }
}
[System.Diagnostics.DebuggerNonUserCode]
public EntityCollection<Tweets> Tweets
{
get { return Get(_tweets); }
}
[System.Diagnostics.DebuggerNonUserCode]
public string UserName
{
get { return Get(ref _userName, "UserName"); }
set { Set(ref _userName, value, "UserName"); }
}
[System.Diagnostics.DebuggerNonUserCode]
public string PasswordHash
{
get { return Get(ref _passwordHash, "PasswordHash"); }
set { Set(ref _passwordHash, value, "PasswordHash"); }
}
[System.Diagnostics.DebuggerNonUserCode]
public string SecurityStamp
{
get { return Get(ref _securityStamp, "SecurityStamp"); }
set { Set(ref _securityStamp, value, "SecurityStamp"); }
}
[System.Diagnostics.DebuggerNonUserCode]
public string Discriminator
{
get { return Get(ref _discriminator, "Discriminator"); }
set { Set(ref _discriminator, value, "Discriminator"); }
}
#endregion
}
[Serializable]
[System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
[System.ComponentModel.DataObject]
[Table(IdentityMethod=IdentityMethod.IdentityColumn)]
public partial class Tweets : Entity<int>
{
#region Fields
private string _message;
private System.DateTime _created_date;
[Column("AspNetUser_TweetID")]
private string _aspNetUserTweetId;
#endregion
#region Field attribute and view names
/// <summary>Identifies the message entity attribute.</summary>
public const string messageField = "message";
/// <summary>Identifies the created_date entity attribute.</summary>
public const string created_dateField = "created_date";
/// <summary>Identifies the AspNetUserTweetId entity attribute.</summary>
public const string AspNetUserTweetIdField = "AspNetUserTweetId";
#endregion
#region Relationships
[ReverseAssociation("Tweets")]
private readonly EntityHolder<AspNetUser> _aspNetUserTweet = new EntityHolder<AspNetUser>();
#endregion
#region Properties
[System.Diagnostics.DebuggerNonUserCode]
public AspNetUser AspNetUserTweet
{
get { return Get(_aspNetUserTweet); }
set { Set(_aspNetUserTweet, value); }
}
[System.Diagnostics.DebuggerNonUserCode]
public string message
{
get { return Get(ref _message, "message"); }
set { Set(ref _message, value, "message"); }
}
[System.Diagnostics.DebuggerNonUserCode]
public System.DateTime created_date
{
get { return Get(ref _created_date, "created_date"); }
set { Set(ref _created_date, value, "created_date"); }
}
/// <summary>Gets or sets the ID for the <see cref="AspNetUserTweet" /> property.</summary>
[System.Diagnostics.DebuggerNonUserCode]
public string AspNetUserTweetId
{
get { return Get(ref _aspNetUserTweetId, "AspNetUserTweetId"); }
set { Set(ref _aspNetUserTweetId, value, "AspNetUserTweetId"); }
}
#endregion
}
/// <summary>
/// Provides a strong-typed unit of work for working with the LightSpeedModel1 model.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")]
public partial class LightSpeedModel1UnitOfWork : Mindscape.LightSpeed.UnitOfWork
{
public System.Linq.IQueryable<Accounts> Accounts
{
get { return this.Query<Accounts>(); }
}
public System.Linq.IQueryable<AspNetUser> AspNetUsers
{
get { return this.Query<AspNetUser>(); }
}
public System.Linq.IQueryable<Tweets> Tweets
{
get { return this.Query<Tweets>(); }
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using Microsoft.Azure.Management.Compute.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace Microsoft.Azure.Commands.Compute.Automation
{
[Cmdlet("New", "AzureRmDiskUpdateConfig", SupportsShouldProcess = true)]
[OutputType(typeof(DiskUpdate))]
public class NewAzureRmDiskUpdateConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet
{
[Parameter(
Mandatory = false,
Position = 0,
ValueFromPipelineByPropertyName = true)]
public StorageAccountTypes? AccountType { get; set; }
[Parameter(
Mandatory = false,
Position = 1,
ValueFromPipelineByPropertyName = true)]
public OperatingSystemTypes? OsType { get; set; }
[Parameter(
Mandatory = false,
Position = 2,
ValueFromPipelineByPropertyName = true)]
public int? DiskSizeGB { get; set; }
[Parameter(
Mandatory = false,
Position = 3,
ValueFromPipelineByPropertyName = true)]
public Hashtable Tag { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public DiskCreateOption? CreateOption { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string StorageAccountId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public ImageDiskReference ImageReference { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string SourceUri { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public string SourceResourceId { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public bool? EncryptionSettingsEnabled { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public KeyVaultAndSecretReference DiskEncryptionKey { get; set; }
[Parameter(
Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public KeyVaultAndKeyReference KeyEncryptionKey { get; set; }
protected override void ProcessRecord()
{
if (ShouldProcess("DiskUpdate", "New"))
{
Run();
}
}
private void Run()
{
// CreationData
Microsoft.Azure.Management.Compute.Models.CreationData vCreationData = null;
// EncryptionSettings
Microsoft.Azure.Management.Compute.Models.EncryptionSettings vEncryptionSettings = null;
if (this.CreateOption.HasValue)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.CreateOption = this.CreateOption.Value;
}
if (this.StorageAccountId != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.StorageAccountId = this.StorageAccountId;
}
if (this.ImageReference != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.ImageReference = this.ImageReference;
}
if (this.SourceUri != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.SourceUri = this.SourceUri;
}
if (this.SourceResourceId != null)
{
if (vCreationData == null)
{
vCreationData = new Microsoft.Azure.Management.Compute.Models.CreationData();
}
vCreationData.SourceResourceId = this.SourceResourceId;
}
if (this.EncryptionSettingsEnabled != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.Enabled = this.EncryptionSettingsEnabled;
}
if (this.DiskEncryptionKey != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.DiskEncryptionKey = this.DiskEncryptionKey;
}
if (this.KeyEncryptionKey != null)
{
if (vEncryptionSettings == null)
{
vEncryptionSettings = new Microsoft.Azure.Management.Compute.Models.EncryptionSettings();
}
vEncryptionSettings.KeyEncryptionKey = this.KeyEncryptionKey;
}
var vDiskUpdate = new DiskUpdate
{
AccountType = this.AccountType,
OsType = this.OsType,
DiskSizeGB = this.DiskSizeGB,
Tags = (this.Tag == null) ? null : this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value),
CreationData = vCreationData,
EncryptionSettings = vEncryptionSettings,
};
WriteObject(vDiskUpdate);
}
}
}
| |
//
// System.Data.UniqueConstraint.cs
//
// Author:
// Franklin Wise <gracenote@earthlink.net>
// Daniel Morgan <danmorg@sc.rr.com>
// Tim Coleman (tim@timcoleman.com)
//
// (C) 2002 Franklin Wise
// (C) 2002 Daniel Morgan
// Copyright (C) Tim Coleman, 2002
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Data.Common;
namespace System.Data {
[Editor]
[DefaultProperty ("ConstraintName")]
[Serializable]
public class UniqueConstraint : Constraint
{
private bool _isPrimaryKey = false;
private bool _belongsToCollection = false;
private DataTable _dataTable; //set by ctor except when unique case
//FIXME: create a class which will wrap this collection
private DataColumn [] _dataColumns;
//TODO:provide helpers for this case
private string [] _dataColumnNames; //unique case
private bool _dataColsNotValidated;
#region Constructors
public UniqueConstraint (DataColumn column)
{
_uniqueConstraint ("", column, false);
}
public UniqueConstraint (DataColumn[] columns)
{
_uniqueConstraint ("", columns, false);
}
public UniqueConstraint (DataColumn column, bool isPrimaryKey)
{
_uniqueConstraint ("", column, isPrimaryKey);
}
public UniqueConstraint (DataColumn[] columns, bool isPrimaryKey)
{
_uniqueConstraint ("", columns, isPrimaryKey);
}
public UniqueConstraint (string name, DataColumn column)
{
_uniqueConstraint (name, column, false);
}
public UniqueConstraint (string name, DataColumn[] columns)
{
_uniqueConstraint (name, columns, false);
}
public UniqueConstraint (string name, DataColumn column, bool isPrimaryKey)
{
_uniqueConstraint (name, column, isPrimaryKey);
}
public UniqueConstraint (string name, DataColumn[] columns, bool isPrimaryKey)
{
_uniqueConstraint (name, columns, isPrimaryKey);
}
//Special case. Can only be added to the Collection with AddRange
[Browsable (false)]
public UniqueConstraint (string name, string[] columnNames, bool isPrimaryKey)
{
_dataColsNotValidated = true;
//keep list of names to resolve later
_dataColumnNames = columnNames;
base.ConstraintName = name;
_isPrimaryKey = isPrimaryKey;
}
//helper ctor
private void _uniqueConstraint(string name, DataColumn column, bool isPrimaryKey)
{
_dataColsNotValidated = false;
//validate
_validateColumn (column);
//Set Constraint Name
base.ConstraintName = name;
_isPrimaryKey = isPrimaryKey;
//keep reference
_dataColumns = new DataColumn [] {column};
//Get table reference
_dataTable = column.Table;
}
//helpter ctor
private void _uniqueConstraint(string name, DataColumn[] columns, bool isPrimaryKey)
{
_dataColsNotValidated = false;
//validate
_validateColumns (columns, out _dataTable);
//Set Constraint Name
base.ConstraintName = name;
//keep reference
_dataColumns = columns;
//PK?
_isPrimaryKey = isPrimaryKey;
}
#endregion // Constructors
#region Helpers
private void _validateColumns(DataColumn [] columns)
{
DataTable table;
_validateColumns(columns, out table);
}
//Validates a collection of columns with the ctor rules
private void _validateColumns(DataColumn [] columns, out DataTable table) {
table = null;
//not null
if (null == columns) throw new ArgumentNullException();
//check that there is at least one column
//LAMESPEC: not in spec
if (columns.Length < 1)
throw new InvalidConstraintException("Must be at least one column.");
DataTable compareTable = columns[0].Table;
//foreach
foreach (DataColumn col in columns){
//check individual column rules
_validateColumn (col);
//check that columns are all from the same table??
//LAMESPEC: not in spec
if (compareTable != col.Table)
throw new InvalidConstraintException("Columns must be from the same table.");
}
table = compareTable;
}
//validates a column with the ctor rules
private void _validateColumn(DataColumn column) {
//not null
if (null == column) // FIXME: This is little weird, but here it goes...
throw new NullReferenceException("Object reference not set to an instance of an object.");
//column must belong to a table
//LAMESPEC: not in spec
if (null == column.Table)
throw new ArgumentException ("Column must belong to a table.");
}
internal static void SetAsPrimaryKey(ConstraintCollection collection, UniqueConstraint newPrimaryKey)
{
//not null
if (null == collection) throw new ArgumentNullException("ConstraintCollection can't be null.");
//make sure newPrimaryKey belongs to the collection parm unless it is null
if ( collection.IndexOf(newPrimaryKey) < 0 && (null != newPrimaryKey) )
throw new ArgumentException("newPrimaryKey must belong to collection.");
//Get existing pk
UniqueConstraint uc = GetPrimaryKeyConstraint(collection);
//clear existing
if (null != uc) uc._isPrimaryKey = false;
//set new key
if (null != newPrimaryKey) newPrimaryKey._isPrimaryKey = true;
}
internal static UniqueConstraint GetPrimaryKeyConstraint(ConstraintCollection collection)
{
if (null == collection) throw new ArgumentNullException("Collection can't be null.");
UniqueConstraint uc;
IEnumerator enumer = collection.GetEnumerator();
while (enumer.MoveNext())
{
uc = enumer.Current as UniqueConstraint;
if (null == uc) continue;
if (uc.IsPrimaryKey) return uc;
}
//if we got here there was no pk
return null;
}
internal static UniqueConstraint GetUniqueConstraintForColumnSet(ConstraintCollection collection,
DataColumn[] columns)
{
if (null == collection) throw new ArgumentNullException("Collection can't be null.");
if (null == columns ) return null;
foreach(Constraint constraint in collection) {
if (constraint is UniqueConstraint) {
UniqueConstraint uc = constraint as UniqueConstraint;
if ( DataColumn.AreColumnSetsTheSame(uc.Columns, columns) ) {
return uc;
}
}
}
return null;
}
internal bool DataColsNotValidated
{
get {
return (_dataColsNotValidated);
}
}
// Helper Special Ctor
// Set the _dataTable property to the table to which this instance is bound when AddRange()
// is called with the special constructor.
// Validate whether the named columns exist in the _dataTable
internal void PostAddRange( DataTable _setTable )
{
_dataTable = _setTable;
DataColumn []cols = new DataColumn [_dataColumnNames.Length];
int i = 0;
foreach ( string _columnName in _dataColumnNames ) {
if ( _setTable.Columns.Contains (_columnName) ) {
cols [i] = _setTable.Columns [_columnName];
i++;
continue;
}
throw( new InvalidConstraintException ( "The named columns must exist in the table" ));
}
_dataColumns = cols;
}
#endregion //Helpers
#region Properties
[DataCategory ("Data")]
[DataSysDescription ("Indicates the columns of this constraint.")]
[ReadOnly (true)]
public virtual DataColumn[] Columns {
get { return _dataColumns; }
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates if this constraint is a primary key.")]
public bool IsPrimaryKey {
get {
if (Table == null || (!_belongsToCollection)) {
return false;
}
return _isPrimaryKey;
}
}
[DataCategory ("Data")]
[DataSysDescription ("Indicates the table of this constraint.")]
[ReadOnly (true)]
public override DataTable Table {
get { return _dataTable; }
}
#endregion // Properties
#region Methods
public override bool Equals(object key2) {
UniqueConstraint cst = key2 as UniqueConstraint;
if (null == cst) return false;
//according to spec if the cols are equal
//then two UniqueConstraints are equal
return DataColumn.AreColumnSetsTheSame(cst.Columns, this.Columns);
}
public override int GetHashCode()
{
//initialize hash with default value
int hash = 42;
int i;
//derive the hash code from the columns that way
//Equals and GetHashCode return Equal objects to be the
//same
//Get the first column hash
if (this.Columns.Length > 0)
hash ^= this.Columns[0].GetHashCode();
//get the rest of the column hashes if there any
for (i = 1; i < this.Columns.Length; i++)
{
hash ^= this.Columns[1].GetHashCode();
}
return hash ;
}
internal override void AddToConstraintCollectionSetup(
ConstraintCollection collection)
{
for (int i = 0; i < Columns.Length; i++)
if (Columns[i].Table != collection.Table)
throw new ArgumentException("These columns don't point to this table.");
//run Ctor rules again
_validateColumns(_dataColumns);
//make sure a unique constraint doesn't already exists for these columns
UniqueConstraint uc = UniqueConstraint.GetUniqueConstraintForColumnSet(collection, this.Columns);
if (null != uc) throw new ArgumentException("Unique constraint already exists for these" +
" columns. Existing ConstraintName is " + uc.ConstraintName);
//Allow only one primary key
if (this.IsPrimaryKey) {
uc = GetPrimaryKeyConstraint(collection);
if (null != uc) uc._isPrimaryKey = false;
}
// if constraint is based on one column only
// this column becomes unique
if (_dataColumns.Length == 1) {
_dataColumns[0].SetUnique();
}
//FIXME: ConstraintCollection calls AssertContraint() again rigth after calling
//this method, so that it is executed twice. Need to investigate which
// call to remove as that migth affect other parts of the classes.
//AssertConstraint();
if (IsConstraintViolated())
throw new ArgumentException("These columns don't currently have unique values.");
_belongsToCollection = true;
}
internal override void RemoveFromConstraintCollectionCleanup(
ConstraintCollection collection)
{
_belongsToCollection = false;
Index index = Index;
Index = null;
}
protected override bool IsConstraintViolated()
{
if (Index == null) {
Index = Table.GetIndex(Columns,null,DataViewRowState.None,null,false);
}
if (Index.HasDuplicates) {
int[] dups = Index.Duplicates;
for (int i = 0; i < dups.Length; i++){
DataRow row = Table.RecordCache[dups[i]];
ArrayList columns = new ArrayList();
ArrayList values = new ArrayList();
foreach (DataColumn col in Columns){
columns.Add(col.ColumnName);
values.Add(row[col].ToString());
}
string columnNames = String.Join(",", (string[])columns.ToArray(typeof(string)));
string columnValues = String.Join(",", (string[])values.ToArray(typeof(string)));
row.RowError = String.Format("Column(s) '{0}' are constrained to be unique. Value(s) '{1}' are already present", columnNames, columnValues);
}
// FIXME : check the exception to be thrown here
// throw new ConstraintException("These columns don't currently have unique values");
//throw new ConstraintException ("Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.");
return true;
}
return false;
}
internal override void AssertConstraint(DataRow row)
{
if (IsPrimaryKey && row.HasVersion(DataRowVersion.Default)) {
for (int i = 0; i < Columns.Length; i++) {
if (row.IsNull(Columns[i])) {
throw new NoNullAllowedException("Column '" + Columns[i].ColumnName + "' does not allow nulls.");
}
}
}
if (Index == null) {
Index = Table.GetIndex(Columns,null,DataViewRowState.None,null,false);
}
if (Index.HasDuplicates) {
throw new ConstraintException(GetErrorMessage(row));
}
}
internal override bool IsColumnContained(DataColumn column)
{
for (int i = 0; i < _dataColumns.Length; i++)
if (column == _dataColumns[i])
return true;
return false;
}
internal override bool CanRemoveFromCollection(ConstraintCollection col, bool shouldThrow){
if (Equals(col.Table.PrimaryKey)){
if (shouldThrow)
throw new ArgumentException("Cannot remove unique constraint since it's the primary key of a table.");
return false;
}
if (Table.DataSet != null){
foreach (DataTable table in Table.DataSet.Tables){
foreach (Constraint constraint in table.Constraints){
if (constraint is ForeignKeyConstraint)
if (((ForeignKeyConstraint)constraint).RelatedTable == Table){
if (shouldThrow)
throw new ArgumentException(
String.Format("Cannot remove unique constraint '{0}'. Remove foreign key constraint '{1}' first.",
ConstraintName, constraint.ConstraintName)
);
return false;
}
}
}
}
return true;
}
private string GetErrorMessage(DataRow row)
{
int i;
System.Text.StringBuilder sb = new System.Text.StringBuilder(row[_dataColumns[0]].ToString());
for (i = 1; i < _dataColumns.Length; i++) {
sb = sb.Append(", ").Append(row[_dataColumns[i].ColumnName]);
}
string valStr = sb.ToString();
sb = new System.Text.StringBuilder(_dataColumns[0].ColumnName);
for (i = 1; i < _dataColumns.Length; i++) {
sb = sb.Append(", ").Append(_dataColumns[i].ColumnName);
}
string colStr = sb.ToString();
return "Column '" + colStr + "' is constrained to be unique. Value '" + valStr + "' is already present.";
}
#endregion // Methods
}
}
| |
using System;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
namespace Umbraco.Core.Services
{
/// <summary>
/// The Umbraco ServiceContext, which provides access to the following services:
/// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>,
/// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>.
/// </summary>
public class ServiceContext
{
private Lazy<ITagService> _tagService;
private Lazy<IContentService> _contentService;
private Lazy<IUserService> _userService;
private Lazy<IMemberService> _memberService;
private Lazy<IMediaService> _mediaService;
private Lazy<IContentTypeService> _contentTypeService;
private Lazy<IDataTypeService> _dataTypeService;
private Lazy<IFileService> _fileService;
private Lazy<ILocalizationService> _localizationService;
private Lazy<IPackagingService> _packagingService;
private Lazy<ServerRegistrationService> _serverRegistrationService;
private Lazy<IEntityService> _entityService;
private Lazy<IRelationService> _relationService;
private Lazy<IApplicationTreeService> _treeService;
private Lazy<ISectionService> _sectionService;
private Lazy<IMacroService> _macroService;
private Lazy<IMemberTypeService> _memberTypeService;
private Lazy<IMemberGroupService> _memberGroupService;
private Lazy<INotificationService> _notificationService;
/// <summary>
/// public ctor - will generally just be used for unit testing
/// </summary>
/// <param name="contentService"></param>
/// <param name="mediaService"></param>
/// <param name="contentTypeService"></param>
/// <param name="dataTypeService"></param>
/// <param name="fileService"></param>
/// <param name="localizationService"></param>
/// <param name="packagingService"></param>
/// <param name="entityService"></param>
/// <param name="relationService"></param>
/// <param name="sectionService"></param>
/// <param name="treeService"></param>
/// <param name="tagService"></param>
/// <param name="memberGroupService"></param>
public ServiceContext(
IContentService contentService,
IMediaService mediaService,
IContentTypeService contentTypeService,
IDataTypeService dataTypeService,
IFileService fileService,
ILocalizationService localizationService,
IPackagingService packagingService,
IEntityService entityService,
IRelationService relationService,
IMemberGroupService memberGroupService,
ISectionService sectionService,
IApplicationTreeService treeService,
ITagService tagService)
{
_tagService = new Lazy<ITagService>(() => tagService);
_contentService = new Lazy<IContentService>(() => contentService);
_mediaService = new Lazy<IMediaService>(() => mediaService);
_contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService);
_dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService);
_fileService = new Lazy<IFileService>(() => fileService);
_localizationService = new Lazy<ILocalizationService>(() => localizationService);
_packagingService = new Lazy<IPackagingService>(() => packagingService);
_entityService = new Lazy<IEntityService>(() => entityService);
_relationService = new Lazy<IRelationService>(() => relationService);
_sectionService = new Lazy<ISectionService>(() => sectionService);
_memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService);
_treeService = new Lazy<IApplicationTreeService>(() => treeService);
}
/// <summary>
/// Constructor used to instantiate the core services
/// </summary>
/// <param name="dbUnitOfWorkProvider"></param>
/// <param name="fileUnitOfWorkProvider"></param>
/// <param name="publishingStrategy"></param>
/// <param name="cache"></param>
internal ServiceContext(IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider, IUnitOfWorkProvider fileUnitOfWorkProvider, BasePublishingStrategy publishingStrategy, CacheHelper cache)
{
BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache,
//this needs to be lazy because when we create the service context it's generally before the
//resolvers have been initialized!
new Lazy<RepositoryFactory>(() => RepositoryResolver.Current.Factory));
}
/// <summary>
/// Builds the various services
/// </summary>
private void BuildServiceCache(
IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider,
IUnitOfWorkProvider fileUnitOfWorkProvider,
BasePublishingStrategy publishingStrategy,
CacheHelper cache,
Lazy<RepositoryFactory> repositoryFactory)
{
var provider = dbUnitOfWorkProvider;
var fileProvider = fileUnitOfWorkProvider;
if (_notificationService == null)
_notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value));
if (_serverRegistrationService == null)
_serverRegistrationService = new Lazy<ServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory.Value));
if (_userService == null)
_userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory.Value));
if (_memberService == null)
_memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory.Value, _memberGroupService.Value));
if (_contentService == null)
_contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory.Value, publishingStrategy));
if (_mediaService == null)
_mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory.Value));
if (_contentTypeService == null)
_contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory.Value, _contentService.Value, _mediaService.Value));
if (_dataTypeService == null)
_dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory.Value));
if (_fileService == null)
_fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory.Value));
if (_localizationService == null)
_localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory.Value));
if (_packagingService == null)
_packagingService = new Lazy<IPackagingService>(() => new PackagingService(_contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, repositoryFactory.Value, provider));
if (_entityService == null)
_entityService = new Lazy<IEntityService>(() => new EntityService(provider, repositoryFactory.Value, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value));
if (_relationService == null)
_relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory.Value, _entityService.Value));
if (_treeService == null)
_treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(cache));
if (_sectionService == null)
_sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, cache));
if (_macroService == null)
_macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory.Value));
if (_memberTypeService == null)
_memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory.Value, _memberService.Value));
if (_tagService == null)
_tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory.Value));
if (_memberGroupService == null)
_memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory.Value));
}
/// <summary>
/// Gets the <see cref="INotificationService"/>
/// </summary>
internal INotificationService NotificationService
{
get { return _notificationService.Value; }
}
/// <summary>
/// Gets the <see cref="ServerRegistrationService"/>
/// </summary>
internal ServerRegistrationService ServerRegistrationService
{
get { return _serverRegistrationService.Value; }
}
/// <summary>
/// Gets the <see cref="ITagService"/>
/// </summary>
public ITagService TagService
{
get { return _tagService.Value; }
}
/// <summary>
/// Gets the <see cref="IMacroService"/>
/// </summary>
public IMacroService MacroService
{
get { return _macroService.Value; }
}
/// <summary>
/// Gets the <see cref="IEntityService"/>
/// </summary>
public IEntityService EntityService
{
get { return _entityService.Value; }
}
/// <summary>
/// Gets the <see cref="IRelationService"/>
/// </summary>
public IRelationService RelationService
{
get { return _relationService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentService"/>
/// </summary>
public IContentService ContentService
{
get { return _contentService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentTypeService"/>
/// </summary>
public IContentTypeService ContentTypeService
{
get { return _contentTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IDataTypeService"/>
/// </summary>
public IDataTypeService DataTypeService
{
get { return _dataTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IFileService"/>
/// </summary>
public IFileService FileService
{
get { return _fileService.Value; }
}
/// <summary>
/// Gets the <see cref="ILocalizationService"/>
/// </summary>
public ILocalizationService LocalizationService
{
get { return _localizationService.Value; }
}
/// <summary>
/// Gets the <see cref="IMediaService"/>
/// </summary>
public IMediaService MediaService
{
get { return _mediaService.Value; }
}
/// <summary>
/// Gets the <see cref="PackagingService"/>
/// </summary>
public IPackagingService PackagingService
{
get { return _packagingService.Value; }
}
/// <summary>
/// Gets the <see cref="UserService"/>
/// </summary>
public IUserService UserService
{
get { return _userService.Value; }
}
/// <summary>
/// Gets the <see cref="MemberService"/>
/// </summary>
public IMemberService MemberService
{
get { return _memberService.Value; }
}
/// <summary>
/// Gets the <see cref="SectionService"/>
/// </summary>
public ISectionService SectionService
{
get { return _sectionService.Value; }
}
/// <summary>
/// Gets the <see cref="ApplicationTreeService"/>
/// </summary>
public IApplicationTreeService ApplicationTreeService
{
get { return _treeService.Value; }
}
/// <summary>
/// Gets the MemberTypeService
/// </summary>
public IMemberTypeService MemberTypeService
{
get { return _memberTypeService.Value; }
}
/// <summary>
/// Gets the MemberGroupService
/// </summary>
public IMemberGroupService MemberGroupService
{
get { return _memberGroupService.Value; }
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class SetStrStrTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] Set() - new simple strings
//
for (int i = 0; i < values.Length; i++)
{
cnt = nvc.Count;
nvc.Set(keys[i], values[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, keys[i]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[keys[i]], values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[keys[i]], values[i]));
}
}
//
// Intl strings
// [] Set() - new Intl strings
//
int len = values.Length;
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
nvc.Set(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
}
//
// [] Case sensitivity
// Casing doesn't change ( keys are not converted to lower!)
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
cnt = nvc.Count;
// add uppercase items
nvc.Set(intlValues[i + len], intlValues[i]);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {1} instead of {2}", i, nvc.Count, cnt + 1));
}
// verify that collection contains newly added uppercase item
//
if (Array.IndexOf(nvc.AllKeys, intlValues[i + len]) < 0)
{
Assert.False(true, string.Format("Error, collection doesn't contain key of new item", i));
}
// access the item
//
if (String.Compare(nvc[intlValues[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" instead of \"{2}\"", i, nvc[intlValues[i + len]], intlValues[i]));
}
// verify that collection doesn't contains lowercase item
//
if (!caseInsensitive && String.Compare(nvc[intlValuesLower[i + len]], intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned item \"{1}\" is lowercase after adding uppercase", i, nvc[intlValuesLower[i + len]]));
}
// key is not converted to lower
if (!caseInsensitive && Array.IndexOf(nvc.AllKeys, intlValuesLower[i + len]) >= 0)
{
Assert.False(true, string.Format("Error, key was converted to lower", i));
}
// but search among keys is case-insensitive
if (String.Compare(nvc[intlValuesLower[i + len]], intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, could not find item using differently cased key", i));
}
}
//
// [] Set multiple values with the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
for (int i = 0; i < len; i++)
{
nvc.Set(k, "Value" + i);
// should replace previous value
if (nvc.Count != 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of 1", nvc.Count, i));
}
if (String.Compare(nvc[k], "Value" + i) != 0)
{
Assert.False(true, string.Format("Error, didn't replace value", i));
}
}
if (nvc.AllKeys.Length != 1)
{
Assert.False(true, "Error, should contain only 1 key");
}
// verify that collection contains newly added item
//
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// access the item
//
string[] vals = nvc.GetValues(k);
if (vals.Length != 1)
{
Assert.False(true, string.Format("Error, number of values at given key is {0} instead of {1}", vals.Length, 1));
}
if (Array.IndexOf(vals, "Value" + (len - 1).ToString()) < 0)
{
Assert.False(true, string.Format("Error, value is not {0}", "Value" + (len - 1)));
}
//
// [] Set(string, null)
//
k = "kk";
nvc.Remove(k); // make sure there is no such item already
cnt = nvc.Count;
nvc.Set(k, null);
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// verify that collection contains null
//
if (nvc[k] != null)
{
Assert.False(true, "Error, returned non-null on place of null");
}
nvc.Remove(k); // make sure there is no such item already
nvc.Add(k, "kItem");
cnt = nvc.Count;
nvc.Set(k, null);
if (nvc.Count != cnt)
{
Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc.Count, cnt));
}
if (Array.IndexOf(nvc.AllKeys, k) < 0)
{
Assert.False(true, "Error, collection doesn't contain key of new item");
}
// verify that item at k-key was replaced with null
//
if (nvc[k] != null)
{
Assert.False(true, "Error, non-null was not replaced with null");
}
//
// Set item with null key - no NullReferenceException expected
// [] Set(null, string)
//
nvc.Remove(null);
cnt = nvc.Count;
nvc.Set(null, "item");
if (nvc.Count != cnt + 1)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, cnt + 1));
}
if (Array.IndexOf(nvc.AllKeys, null) < 0)
{
Assert.False(true, "Error, collection doesn't contain null key ");
}
// verify that collection contains null
//
if (nvc[null] != "item")
{
Assert.False(true, "Error, returned wrong value at null key");
}
// replace item with null key
cnt = nvc.Count;
nvc.Set(null, "newItem");
if (nvc.Count != cnt)
{
Assert.False(true, string.Format("Error, count has changed: {0} instead of {1}", nvc.Count, cnt));
}
if (Array.IndexOf(nvc.AllKeys, null) < 0)
{
Assert.False(true, "Error, collection doesn't contain null key ");
}
// verify that item with null key was replaced
//
if (nvc[null] != "newItem")
{
Assert.False(true, "Error, didn't replace value at null key");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
public class ArrayLastIndexOf4
{
private const int c_MIN_SIZE = 64;
private const int c_MAX_SIZE = 1024;
private const int c_MIN_STRLEN = 1;
private const int c_MAX_STRLEN = 1024;
public static int Main()
{
ArrayLastIndexOf4 ac = new ArrayLastIndexOf4();
TestLibrary.TestFramework.BeginTestCase("Array.LastInexOf(T[] array, T value)");
if (ac.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
retVal = PosTest5() && retVal;
retVal = PosTest6() && retVal;
retVal = PosTest7() && retVal;
retVal = PosTest8() && retVal;
retVal = PosTest9() && retVal;
retVal = PosTest10() && retVal;
retVal = PosTest11() && retVal;
TestLibrary.TestFramework.LogInformation("");
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
retVal = NegTest9() && retVal;
retVal = NegTest10() && retVal;
return retVal;
}
public bool PosTest1() { return PosIndexOf<Int64>(1, TestLibrary.Generator.GetInt64(-55), TestLibrary.Generator.GetInt64(-55)); }
public bool PosTest2() { return PosIndexOf<Int32>(2, TestLibrary.Generator.GetInt32(-55), TestLibrary.Generator.GetInt32(-55)); }
public bool PosTest3() { return PosIndexOf<Int16>(3, TestLibrary.Generator.GetInt16(-55), TestLibrary.Generator.GetInt16(-55)); }
public bool PosTest4() { return PosIndexOf<Byte>(4, TestLibrary.Generator.GetByte(-55), TestLibrary.Generator.GetByte(-55)); }
public bool PosTest5() { return PosIndexOf<double>(5, TestLibrary.Generator.GetDouble(-55), TestLibrary.Generator.GetDouble(-55)); }
public bool PosTest6() { return PosIndexOf<float>(6, TestLibrary.Generator.GetSingle(-55), TestLibrary.Generator.GetSingle(-55)); }
public bool PosTest7() { return PosIndexOf<char>(7, TestLibrary.Generator.GetCharLetter(-55), TestLibrary.Generator.GetCharLetter(-55)); }
public bool PosTest8() { return PosIndexOf<char>(8, TestLibrary.Generator.GetCharNumber(-55), TestLibrary.Generator.GetCharNumber(-55)); }
public bool PosTest9() { return PosIndexOf<char>(9, TestLibrary.Generator.GetChar(-55), TestLibrary.Generator.GetChar(-55)); }
public bool PosTest10() { return PosIndexOf<string>(10, TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN), TestLibrary.Generator.GetString(-55, false, c_MIN_STRLEN, c_MAX_STRLEN)); }
public bool PosTest11() { return PosIndexOf2<Int32>(11, 1, 0, 0, 0); }
public bool NegTest1() { return NegIndexOf<Int32>(1, 1); }
// id, defaultValue, length, startIndex, count
public bool NegTest2() { return NegIndexOf2<Int32>( 2, 1, 0, 1, 0); }
public bool NegTest3() { return NegIndexOf2<Int32>( 3, 1, 0, -2, 0); }
public bool NegTest4() { return NegIndexOf2<Int32>( 4, 1, 0, -1, 1); }
public bool NegTest5() { return NegIndexOf2<Int32>( 5, 1, 0, 0, 1); }
public bool NegTest6() { return NegIndexOf2<Int32>( 6, 1, 1, -1, 1); }
public bool NegTest7() { return NegIndexOf2<Int32>( 7, 1, 1, 2, 1); }
public bool NegTest8() { return NegIndexOf2<Int32>( 8, 1, 1, 0, -1); }
public bool NegTest9() { return NegIndexOf2<Int32>( 9, 1, 1, 0, -1); }
public bool NegTest10() { return NegIndexOf2<Int32>(10, 1, 1, 1, 2); }
public bool PosIndexOf<T>(int id, T element, T otherElem)
{
bool retVal = true;
T[] array;
int length;
int index;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex, int count) (T=="+typeof(T)+") where value is found");
try
{
// creat the array
length = (TestLibrary.Generator.GetInt32(-55) % (c_MAX_SIZE-c_MIN_SIZE)) + c_MIN_SIZE;
array = new T[length];
// fill the array
for (int i=0; i<array.Length; i++)
{
array[i] = otherElem;
}
// set the lucky index
index = TestLibrary.Generator.GetInt32(-55) % length;
// set the value
array.SetValue( element, index);
newIndex = Array.LastIndexOf<T>(array, element, array.Length-1, array.Length);
if (index > newIndex)
{
TestLibrary.TestFramework.LogError("000", "Unexpected index: Expected(" + index + ") Actual(" + newIndex + ")");
retVal = false;
}
if (!element.Equals(array[newIndex]))
{
TestLibrary.TestFramework.LogError("001", "Unexpected value: Expected(" + element + ") Actual(" + array[newIndex] + ")");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool PosIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
int newIndex;
TestLibrary.TestFramework.BeginScenario("PosTest"+id+": Array.LastInexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
newIndex = Array.LastIndexOf<T>(array, defaultValue, startIndex, count);
if (-1 != newIndex)
{
TestLibrary.TestFramework.LogError("003", "Unexpected value: Expected(-1) Actual("+newIndex+")");
retVal = false;
}
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf<T>(int id, T defaultValue)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.LastInexOf(T[] array, T value, int startIndex, int count) (T == "+typeof(T)+" where array is null");
try
{
Array.LastIndexOf<T>(array, defaultValue, 0, 0);
TestLibrary.TestFramework.LogError("005", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentNullException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
public bool NegIndexOf2<T>(int id, T defaultValue, int length, int startIndex, int count)
{
bool retVal = true;
T[] array = null;
TestLibrary.TestFramework.BeginScenario("NegTest"+id+": Array.LastInexOf(T["+length+"] array, T value, "+startIndex+", "+count+") (T == "+typeof(T)+" where array is null");
try
{
array = new T[ length ];
Array.LastIndexOf<T>(array, defaultValue, startIndex, count);
TestLibrary.TestFramework.LogError("007", "Exepction should have been thrown");
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
// expected
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpected exception: " + e);
retVal = false;
}
return retVal;
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core.Events;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.SqlSyntax;
namespace Umbraco.Core.Persistence.Migrations.Initial
{
/// <summary>
/// Represents the initial database schema creation by running CreateTable for all DTOs against the db.
/// </summary>
internal class DatabaseSchemaCreation
{
/// <summary>
/// Constructor
/// </summary>
/// <param name="database"></param>
/// <param name="logger"></param>
/// <param name="sqlSyntaxProvider"></param>
public DatabaseSchemaCreation(Database database, ILogger logger, ISqlSyntaxProvider sqlSyntaxProvider)
{
_database = database;
_logger = logger;
_sqlSyntaxProvider = sqlSyntaxProvider;
_schemaHelper = new DatabaseSchemaHelper(database, logger, sqlSyntaxProvider);
}
#region Private Members
private readonly DatabaseSchemaHelper _schemaHelper;
private readonly Database _database;
private readonly ILogger _logger;
private readonly ISqlSyntaxProvider _sqlSyntaxProvider;
private static readonly Dictionary<int, Type> OrderedTables = new Dictionary<int, Type>
{
{0, typeof (NodeDto)},
{1, typeof (ContentTypeDto)},
{2, typeof (TemplateDto)},
{3, typeof (ContentDto)},
{4, typeof (ContentVersionDto)},
{5, typeof (DocumentDto)},
{6, typeof (ContentTypeTemplateDto)},
{7, typeof (DataTypeDto)},
{8, typeof (DataTypePreValueDto)},
{9, typeof (DictionaryDto)},
{10, typeof (LanguageDto)},
{11, typeof (LanguageTextDto)},
{12, typeof (DomainDto)},
{13, typeof (LogDto)},
{14, typeof (MacroDto)},
{15, typeof (MacroPropertyDto)},
{16, typeof (MemberTypeDto)},
{17, typeof (MemberDto)},
{18, typeof (Member2MemberGroupDto)},
{19, typeof (ContentXmlDto)},
{20, typeof (PreviewXmlDto)},
{21, typeof (PropertyTypeGroupDto)},
{22, typeof (PropertyTypeDto)},
{23, typeof (PropertyDataDto)},
{24, typeof (RelationTypeDto)},
{25, typeof (RelationDto)},
{28, typeof (TagDto)},
{29, typeof (TagRelationshipDto)},
{31, typeof (UserTypeDto)},
{32, typeof (UserDto)},
{33, typeof (TaskTypeDto)},
{34, typeof (TaskDto)},
{35, typeof (ContentType2ContentTypeDto)},
{36, typeof (ContentTypeAllowedContentTypeDto)},
{37, typeof (User2AppDto)},
{38, typeof (User2NodeNotifyDto)},
{39, typeof (User2NodePermissionDto)},
{40, typeof (ServerRegistrationDto)},
{41, typeof (AccessDto)},
{42, typeof (AccessRuleDto)},
{43, typeof (CacheInstructionDto)},
{44, typeof (ExternalLoginDto)},
{45, typeof (MigrationDto)},
{46, typeof (UmbracoDeployChecksumDto)},
{47, typeof (UmbracoDeployDependencyDto)},
{48, typeof (RedirectUrlDto) }
};
#endregion
/// <summary>
/// Drops all Umbraco tables in the db
/// </summary>
internal void UninstallDatabaseSchema()
{
_logger.Info<DatabaseSchemaCreation>("Start UninstallDatabaseSchema");
foreach (var item in OrderedTables.OrderByDescending(x => x.Key))
{
var tableNameAttribute = item.Value.FirstAttribute<TableNameAttribute>();
string tableName = tableNameAttribute == null ? item.Value.Name : tableNameAttribute.Value;
_logger.Info<DatabaseSchemaCreation>("Uninstall" + tableName);
try
{
if (_schemaHelper.TableExist(tableName))
{
_schemaHelper.DropTable(tableName);
}
}
catch (Exception ex)
{
//swallow this for now, not sure how best to handle this with diff databases... though this is internal
// and only used for unit tests. If this fails its because the table doesn't exist... generally!
_logger.Error<DatabaseSchemaCreation>("Could not drop table " + tableName, ex);
}
}
}
/// <summary>
/// Initialize the database by creating the umbraco db schema
/// </summary>
public void InitializeDatabaseSchema()
{
var e = new DatabaseCreationEventArgs();
FireBeforeCreation(e);
if (!e.Cancel)
{
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
_schemaHelper.CreateTable(false, item.Value);
}
}
FireAfterCreation(e);
}
/// <summary>
/// Validates the schema of the current database
/// </summary>
public DatabaseSchemaResult ValidateSchema()
{
var result = new DatabaseSchemaResult();
//get the db index defs
result.DbIndexDefinitions = _sqlSyntaxProvider.GetDefinedIndexes(_database)
.Select(x => new DbIndexDefinition()
{
TableName = x.Item1,
IndexName = x.Item2,
ColumnName = x.Item3,
IsUnique = x.Item4
}).ToArray();
foreach (var item in OrderedTables.OrderBy(x => x.Key))
{
var tableDefinition = DefinitionFactory.GetTableDefinition(item.Value);
result.TableDefinitions.Add(tableDefinition);
}
ValidateDbTables(result);
ValidateDbColumns(result);
ValidateDbIndexes(result);
ValidateDbConstraints(result);
return result;
}
private void ValidateDbConstraints(DatabaseSchemaResult result)
{
//MySql doesn't conform to the "normal" naming of constraints, so there is currently no point in doing these checks.
//TODO: At a later point we do other checks for MySql, but ideally it should be necessary to do special checks for different providers.
// ALso note that to get the constraints for MySql we have to open a connection which we currently have not.
if (_sqlSyntaxProvider is MySqlSyntaxProvider)
return;
//Check constraints in configured database against constraints in schema
var constraintsInDatabase = _sqlSyntaxProvider.GetConstraintsPerColumn(_database).DistinctBy(x => x.Item3).ToList();
var foreignKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("FK_")).Select(x => x.Item3).ToList();
var primaryKeysInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("PK_")).Select(x => x.Item3).ToList();
var indexesInDatabase = constraintsInDatabase.Where(x => x.Item3.InvariantStartsWith("IX_")).Select(x => x.Item3).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
var unknownConstraintsInDatabase =
constraintsInDatabase.Where(
x =>
x.Item3.InvariantStartsWith("FK_") == false && x.Item3.InvariantStartsWith("PK_") == false &&
x.Item3.InvariantStartsWith("IX_") == false).Select(x => x.Item3).ToList();
var foreignKeysInSchema = result.TableDefinitions.SelectMany(x => x.ForeignKeys.Select(y => y.Name)).ToList();
var primaryKeysInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => y.PrimaryKeyName))
.Where(x => x.IsNullOrWhiteSpace() == false).ToList();
//Add valid and invalid foreign key differences to the result object
// We'll need to do invariant contains with case insensitivity because foreign key, primary key, and even index naming w/ MySQL is not standardized
// In theory you could have: FK_ or fk_ ...or really any standard that your development department (or developer) chooses to use.
foreach (var unknown in unknownConstraintsInDatabase)
{
if (foreignKeysInSchema.InvariantContains(unknown) || primaryKeysInSchema.InvariantContains(unknown) || indexesInSchema.InvariantContains(unknown))
{
result.ValidConstraints.Add(unknown);
}
else
{
result.Errors.Add(new Tuple<string, string>("Unknown", unknown));
}
}
//Foreign keys:
var validForeignKeyDifferences = foreignKeysInDatabase.Intersect(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var foreignKey in validForeignKeyDifferences)
{
result.ValidConstraints.Add(foreignKey);
}
var invalidForeignKeyDifferences =
foreignKeysInDatabase.Except(foreignKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(foreignKeysInSchema.Except(foreignKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var foreignKey in invalidForeignKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", foreignKey));
}
//Primary keys:
//Add valid and invalid primary key differences to the result object
var validPrimaryKeyDifferences = primaryKeysInDatabase.Intersect(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var primaryKey in validPrimaryKeyDifferences)
{
result.ValidConstraints.Add(primaryKey);
}
var invalidPrimaryKeyDifferences =
primaryKeysInDatabase.Except(primaryKeysInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(primaryKeysInSchema.Except(primaryKeysInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var primaryKey in invalidPrimaryKeyDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", primaryKey));
}
//Constaints:
//NOTE: SD: The colIndex checks above should really take care of this but I need to keep this here because it was here before
// and some schema validation checks might rely on this data remaining here!
//Add valid and invalid index differences to the result object
var validIndexDifferences = indexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validIndexDifferences)
{
result.ValidConstraints.Add(index);
}
var invalidIndexDifferences =
indexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(indexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Constraint", index));
}
}
private void ValidateDbColumns(DatabaseSchemaResult result)
{
//Check columns in configured database against columns in schema
var columnsInDatabase = _sqlSyntaxProvider.GetColumnsInSchema(_database);
var columnsPerTableInDatabase = columnsInDatabase.Select(x => string.Concat(x.TableName, ",", x.ColumnName)).ToList();
var columnsPerTableInSchema = result.TableDefinitions.SelectMany(x => x.Columns.Select(y => string.Concat(y.TableName, ",", y.Name))).ToList();
//Add valid and invalid column differences to the result object
var validColumnDifferences = columnsPerTableInDatabase.Intersect(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var column in validColumnDifferences)
{
result.ValidColumns.Add(column);
}
var invalidColumnDifferences =
columnsPerTableInDatabase.Except(columnsPerTableInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(columnsPerTableInSchema.Except(columnsPerTableInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var column in invalidColumnDifferences)
{
result.Errors.Add(new Tuple<string, string>("Column", column));
}
}
private void ValidateDbTables(DatabaseSchemaResult result)
{
//Check tables in configured database against tables in schema
var tablesInDatabase = _sqlSyntaxProvider.GetTablesInSchema(_database).ToList();
var tablesInSchema = result.TableDefinitions.Select(x => x.Name).ToList();
//Add valid and invalid table differences to the result object
var validTableDifferences = tablesInDatabase.Intersect(tablesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var tableName in validTableDifferences)
{
result.ValidTables.Add(tableName);
}
var invalidTableDifferences =
tablesInDatabase.Except(tablesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(tablesInSchema.Except(tablesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var tableName in invalidTableDifferences)
{
result.Errors.Add(new Tuple<string, string>("Table", tableName));
}
}
private void ValidateDbIndexes(DatabaseSchemaResult result)
{
//These are just column indexes NOT constraints or Keys
//var colIndexesInDatabase = result.DbIndexDefinitions.Where(x => x.IndexName.InvariantStartsWith("IX_")).Select(x => x.IndexName).ToList();
var colIndexesInDatabase = result.DbIndexDefinitions.Select(x => x.IndexName).ToList();
var indexesInSchema = result.TableDefinitions.SelectMany(x => x.Indexes.Select(y => y.Name)).ToList();
//Add valid and invalid index differences to the result object
var validColIndexDifferences = colIndexesInDatabase.Intersect(indexesInSchema, StringComparer.InvariantCultureIgnoreCase);
foreach (var index in validColIndexDifferences)
{
result.ValidIndexes.Add(index);
}
var invalidColIndexDifferences =
colIndexesInDatabase.Except(indexesInSchema, StringComparer.InvariantCultureIgnoreCase)
.Union(indexesInSchema.Except(colIndexesInDatabase, StringComparer.InvariantCultureIgnoreCase));
foreach (var index in invalidColIndexDifferences)
{
result.Errors.Add(new Tuple<string, string>("Index", index));
}
}
#region Events
/// <summary>
/// The save event handler
/// </summary>
internal delegate void DatabaseEventHandler(DatabaseCreationEventArgs e);
/// <summary>
/// Occurs when [before save].
/// </summary>
internal static event DatabaseEventHandler BeforeCreation;
/// <summary>
/// Raises the <see cref="BeforeCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected internal virtual void FireBeforeCreation(DatabaseCreationEventArgs e)
{
if (BeforeCreation != null)
{
BeforeCreation(e);
}
}
/// <summary>
/// Occurs when [after save].
/// </summary>
internal static event DatabaseEventHandler AfterCreation;
/// <summary>
/// Raises the <see cref="AfterCreation"/> event.
/// </summary>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected virtual void FireAfterCreation(DatabaseCreationEventArgs e)
{
if (AfterCreation != null)
{
AfterCreation(e);
}
}
#endregion
}
}
| |
namespace FacebookSharp.Extensions
{
using System;
using System.Text;
using System.Collections.Generic;
using FacebookSharp.Schemas.Graph;
public static partial class FacebookExtensions
{
#if !(SILVERLIGHT || WINDOWS_PHONE)
/// <summary>
/// Gets the page with specified id.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <param name="parameters">
/// The parameters.
/// </param>
/// <returns>
/// </returns>
public static Page GetPage(this Facebook facebook, string pageId, IDictionary<string, string> parameters)
{
var result = facebook.GetObject(pageId, parameters);
return FacebookUtils.DeserializeObject<Page>(result);
}
/// <summary>
/// Gets the page with specified id.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <returns>
/// </returns>
public static Page GetPage(this Facebook facebook, string pageId)
{
return facebook.GetPage(pageId, null);
}
/// <summary>
/// Get list of pages for the current Facebook User
/// </summary>
/// <param name="facebook"></param>
/// <param name="parameters"></param>
/// <returns></returns>
public static string GetMyPagesAsJsonString(this Facebook facebook, IDictionary<string, string> parameters)
{
AssertRequireAccessToken(facebook);
return GetConnections(facebook, "me", "accounts", parameters);
}
public static string GetMyPagesAsJsonString(this Facebook facebook)
{
return GetMyPagesAsJsonString(facebook);
}
public static AccountCollection GetMyPages(this Facebook facebook, IDictionary<string, string> parameters)
{
AssertRequireAccessToken(facebook);
return GetConnections<AccountCollection>(facebook, "me", "accounts", parameters);
}
public static AccountCollection GetMyPages(this Facebook facebook)
{
return GetMyPages(facebook, null);
}
/// <summary>
/// Checks whether the current user is an admin of the sepcified page.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <returns>
/// </returns>
[Obsolete(Facebook.OldRestApiWarningMessage)]
public static bool AmIAdminOfPage(this Facebook facebook, string pageId)
{
return facebook.IsAdminOfPage(string.Empty, pageId);
}
/// <summary>
/// Checkes whether the sepcified user is the admin of the page.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="userId">
/// The user id.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <returns>
/// </returns>
[Obsolete(Facebook.OldRestApiWarningMessage)]
public static bool IsAdminOfPage(this Facebook facebook, string userId, string pageId)
{
return facebook.IsAdminOfPage(userId, pageId, false);
}
/// <summary>
/// Checks if the specified user is the admin of the page or not.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="userId">
/// The user id.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <param name="ignoreAccessTokenException">
/// The ignore access token exception.
/// </param>
/// <returns>
/// </returns>
/// <remarks>
/// ignoreAccessTokenException is true, it will not throw OAuthException if the user doesn't have enough permission,
/// rather it will return false.
/// </remarks>
[Obsolete(Facebook.OldRestApiWarningMessage)]
public static bool IsAdminOfPage(this Facebook facebook, string userId, string pageId, bool ignoreAccessTokenException)
{
AssertRequireAccessToken(facebook);
var parameters = new Dictionary<string, string>
{
{"page_id", pageId}
};
// http://developers.facebook.com/docs/reference/rest/pages.isAdmin
if (!string.IsNullOrEmpty(userId))
parameters.Add("uid", userId);
if (ignoreAccessTokenException)
{
try
{
var result = facebook.GetUsingRestApi("pages.isAdmin", parameters);
return result.Equals("true", StringComparison.OrdinalIgnoreCase);
}
catch (OAuthException)
{
return false;
}
}
else
{
var result = facebook.GetUsingRestApi("pages.isAdmin", parameters);
return result.Equals("true", StringComparison.OrdinalIgnoreCase);
}
}
/// <summary>
/// Gets the the list of all facebook user who are members of the specified page.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <returns>
/// Returns list of users who are members for the page.
/// </returns>
public static BasicUserInfoCollection GetPageMembers(this Facebook facebook, string pageId)
{
return facebook.GetPageMembers(pageId, null);
}
/// <summary>
/// Gets the the list of all facebook user who are members of the specified page.
/// </summary>
/// <param name="facebook">
/// The facebook.
/// </param>
/// <param name="pageId">
/// The page id.
/// </param>
/// <param name="parameters">
/// The parameters.
/// </param>
/// <returns>
/// Returns list of users who are members for the page.
/// </returns>
public static BasicUserInfoCollection GetPageMembers(this Facebook facebook, string pageId, IDictionary<string, string> parameters)
{
var likes = facebook.Get<BasicUserInfoCollection>("/" + pageId + "/members", parameters) ?? new BasicUserInfoCollection();
if (likes.Data == null)
likes.Data = new List<BasicUserInfo>();
return likes;
}
public static BasicUserInfoCollection GetPageMembers(this Facebook facebook, string pageId, int? limit, int? offset, string until, IDictionary<string, string> parameters)
{
parameters = AppendPagingParameters(parameters, limit, offset, until);
return facebook.GetPageMembers(pageId, parameters);
}
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Monitor
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
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>
/// MetricDefinitionsOperations operations.
/// </summary>
internal partial class MetricDefinitionsOperations : IServiceOperations<MonitorClient>, IMetricDefinitionsOperations
{
/// <summary>
/// Initializes a new instance of the MetricDefinitionsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal MetricDefinitionsOperations(MonitorClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the MonitorClient
/// </summary>
public MonitorClient Client { get; private set; }
/// <summary>
/// Lists the metric definitions for the resource.<br>The **$filter**
/// parameter is optional, and can be used to only retrieve certain metric
/// definitions.<br>For example, get just the definition for the CPU
/// percentage counter: $filter=name.value eq '\Processor(_Total)\% Processor
/// Time'.<br>This **$filter** is very restricted and allows only clauses
/// of the form **'name eq <value>'** separated by **or** logical
/// operators.<br>**NOTE**: No other syntax is allowed.
/// </summary>
/// <param name='resourceUri'>
/// The identifier of the resource.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </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<IEnumerable<MetricDefinition>>> ListWithHttpMessagesAsync(string resourceUri, ODataQuery<MetricDefinition> odataQuery = default(ODataQuery<MetricDefinition>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceUri == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceUri");
}
string apiVersion = "2016-03-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("odataQuery", odataQuery);
tracingParameters.Add("resourceUri", resourceUri);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "{resourceUri}/providers/microsoft.insights/metricDefinitions").ToString();
_url = _url.Replace("{resourceUri}", resourceUri);
List<string> _queryParameters = new List<string>();
if (odataQuery != null)
{
var _odataFilter = odataQuery.ToString();
if (!string.IsNullOrEmpty(_odataFilter))
{
_queryParameters.Add(_odataFilter);
}
}
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);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<MetricDefinition>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<MetricDefinition>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Data.Common;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Baseline;
using Marten.Events.Schema;
using Marten.Exceptions;
using Marten.Internal;
using Marten.Internal.Operations;
using Marten.Linq;
using Marten.Linq.Fields;
using Marten.Linq.Parsing;
using Marten.Linq.QueryHandlers;
using Marten.Linq.Selectors;
using Marten.Linq.SqlGeneration;
using Weasel.Postgresql;
using Marten.Schema;
using Marten.Services;
using Marten.Storage;
using Marten.Util;
using Remotion.Linq;
namespace Marten.Events
{
// NOTE!!!! This type has to remain public for the code generation to work
/// <summary>
/// Base type for the IEventStorage type that provides all the read/write operation
/// mapping for the event store in a running system. The actual implementation of this
/// base type is generated and compiled at runtime by Marten
/// </summary>
public abstract class EventDocumentStorage : IEventStorage
{
private readonly EventQueryMapping _mapping;
private readonly ISerializer _serializer;
private readonly string[] _fields;
private readonly string _selectClause;
public EventDocumentStorage(StoreOptions options)
{
Events = options.EventGraph;
_mapping = new EventQueryMapping(options);
FromObject = _mapping.TableName.QualifiedName;
Fields = _mapping;
_serializer = options.Serializer();
IdType = Events.StreamIdentity == StreamIdentity.AsGuid ? typeof(Guid) : typeof(string);
TenancyStyle = options.Events.TenancyStyle;
// The json data column has to go first
var table = new EventsTable(Events);
var columns = table.SelectColumns();
_fields = columns.Select(x => x.Name).ToArray();
_selectClause = $"select {_fields.Join(", ")} from {Events.DatabaseSchemaName}.mt_events as d";
}
public void TruncateDocumentStorage(ITenant tenant)
{
tenant.RunSql($"truncate table {Events.DatabaseSchemaName}.mt_streams cascade");
}
public Task TruncateDocumentStorageAsync(ITenant tenant)
{
return tenant.RunSqlAsync($"truncate table {Events.DatabaseSchemaName}.mt_streams cascade");
}
public EventGraph Events { get; }
public TenancyStyle TenancyStyle { get; }
public IDeletion DeleteForDocument(IEvent document, ITenant tenant)
{
throw new NotSupportedException();
}
public void EjectById(IMartenSession session, object id)
{
// Nothing
}
public void RemoveDirtyTracker(IMartenSession session, object id)
{
// Nothing
}
public IDeletion HardDeleteForDocument(IEvent document, ITenant tenant)
{
throw new NotImplementedException();
}
public string FromObject { get; }
public Type SelectedType => typeof(IEvent);
public void WriteSelectClause(CommandBuilder sql)
{
sql.Append(_selectClause);
}
public string[] SelectFields()
{
return _fields;
}
public ISelector BuildSelector(IMartenSession session)
{
return this;
}
public IQueryHandler<T> BuildHandler<T>(IMartenSession session, Statement topStatement, Statement currentStatement)
{
return LinqHandlerBuilder.BuildHandler<IEvent, T>(this, topStatement);
}
public ISelectClause UseStatistics(QueryStatistics statistics)
{
throw new NotSupportedException();
}
public Type SourceType => typeof(IEvent);
public IFieldMapping Fields { get; }
public ISqlFragment FilterDocuments(QueryModel model, ISqlFragment query)
{
return query;
}
public ISqlFragment DefaultWhereFragment()
{
return null;
}
public bool UseOptimisticConcurrency { get; } = false;
public IOperationFragment DeleteFragment => throw new NotSupportedException();
public IOperationFragment HardDeleteFragment { get; }
public DuplicatedField[] DuplicatedFields { get; } = new DuplicatedField[0];
public DbObjectName TableName => _mapping.TableName;
public Type DocumentType => typeof(IEvent);
public object IdentityFor(IEvent document)
{
return Events.StreamIdentity == StreamIdentity.AsGuid ? (object) document.Id : document.StreamKey;
}
public Type IdType { get; }
public Guid? VersionFor(IEvent document, IMartenSession session)
{
return null;
}
public void Store(IMartenSession session, IEvent document)
{
// Nothing
}
public void Store(IMartenSession session, IEvent document, Guid? version)
{
// Nothing
}
public void Eject(IMartenSession session, IEvent document)
{
// Nothing
}
public IStorageOperation Update(IEvent document, IMartenSession session, ITenant tenant)
{
throw new NotSupportedException();
}
public IStorageOperation Insert(IEvent document, IMartenSession session, ITenant tenant)
{
throw new NotSupportedException();
}
public IStorageOperation Upsert(IEvent document, IMartenSession session, ITenant tenant)
{
throw new NotImplementedException();
}
public IStorageOperation Overwrite(IEvent document, IMartenSession session, ITenant tenant)
{
throw new NotSupportedException();
}
public abstract IStorageOperation AppendEvent(EventGraph events, IMartenSession session, StreamAction stream, IEvent e);
public abstract IStorageOperation InsertStream(StreamAction stream);
public abstract IQueryHandler<StreamState> QueryForStream(StreamAction stream);
public abstract IStorageOperation UpdateStreamVersion(StreamAction stream);
public IEvent Resolve(DbDataReader reader)
{
var eventTypeName = reader.GetString(1);
var mapping = Events.EventMappingFor(eventTypeName);
if (mapping == null)
{
var dotnetTypeName = reader.GetFieldValue<string>(2);
if (dotnetTypeName.IsEmpty())
{
throw new UnknownEventTypeException(eventTypeName);
}
var type = Events.TypeForDotNetName(dotnetTypeName);
mapping = Events.EventMappingFor(type);
}
var data = _serializer.FromJson(mapping.DocumentType, reader, 0).As<object>();
var @event = mapping.Wrap(data);
ApplyReaderDataToEvent(reader, @event);
return @event;
}
public abstract void ApplyReaderDataToEvent(DbDataReader reader, IEvent e);
public async Task<IEvent> ResolveAsync(DbDataReader reader, CancellationToken token)
{
var eventTypeName = await reader.GetFieldValueAsync<string>(1, token);
var mapping = Events.EventMappingFor(eventTypeName);
if (mapping == null)
{
var dotnetTypeName = await reader.GetFieldValueAsync<string>(2, token);
if (dotnetTypeName.IsEmpty())
{
throw new UnknownEventTypeException(eventTypeName);
}
Type type;
try
{
type = Events.TypeForDotNetName(dotnetTypeName);
}
catch (ArgumentNullException)
{
throw new UnknownEventTypeException(dotnetTypeName);
}
mapping = Events.EventMappingFor(type);
}
var data = await _serializer.FromJsonAsync(mapping.DocumentType, reader, 0, token);
var @event = mapping.Wrap(data);
await ApplyReaderDataToEventAsync(reader, @event, token);
return @event;
}
public abstract Task ApplyReaderDataToEventAsync(DbDataReader reader, IEvent e, CancellationToken token);
}
}
| |
// 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
{
public sealed partial class DBNull
{
internal DBNull() { }
public static readonly System.DBNull Value;
public override string ToString() { return default(string); }
public string ToString(System.IFormatProvider provider) { return default(string); }
}
}
namespace System.Data
{
[System.FlagsAttribute]
public enum CommandBehavior
{
CloseConnection = 32,
Default = 0,
KeyInfo = 4,
SchemaOnly = 2,
SequentialAccess = 16,
SingleResult = 1,
SingleRow = 8,
}
public enum CommandType
{
StoredProcedure = 4,
TableDirect = 512,
Text = 1,
}
[System.FlagsAttribute]
public enum ConnectionState
{
Broken = 16,
Closed = 0,
Connecting = 2,
Executing = 4,
Fetching = 8,
Open = 1,
}
public enum DbType
{
AnsiString = 0,
AnsiStringFixedLength = 22,
Binary = 1,
Boolean = 3,
Byte = 2,
Currency = 4,
Date = 5,
DateTime = 6,
DateTime2 = 26,
DateTimeOffset = 27,
Decimal = 7,
Double = 8,
Guid = 9,
Int16 = 10,
Int32 = 11,
Int64 = 12,
Object = 13,
SByte = 14,
Single = 15,
String = 16,
StringFixedLength = 23,
Time = 17,
UInt16 = 18,
UInt32 = 19,
UInt64 = 20,
VarNumeric = 21,
Xml = 25,
}
public enum IsolationLevel
{
Chaos = 16,
ReadCommitted = 4096,
ReadUncommitted = 256,
RepeatableRead = 65536,
Serializable = 1048576,
Snapshot = 16777216,
Unspecified = -1,
}
public enum ParameterDirection
{
Input = 1,
InputOutput = 3,
Output = 2,
ReturnValue = 6,
}
public sealed partial class StateChangeEventArgs : System.EventArgs
{
public StateChangeEventArgs(System.Data.ConnectionState originalState, System.Data.ConnectionState currentState) { }
public System.Data.ConnectionState CurrentState { get { return default(System.Data.ConnectionState); } }
public System.Data.ConnectionState OriginalState { get { return default(System.Data.ConnectionState); } }
}
public delegate void StateChangeEventHandler(object sender, System.Data.StateChangeEventArgs e);
public enum UpdateRowSource
{
Both = 3,
FirstReturnedRecord = 2,
None = 0,
OutputParameters = 1,
}
}
namespace System.Data.Common
{
public abstract partial class DbCommand : System.IDisposable
{
protected DbCommand() { }
public abstract string CommandText { get; set; }
public abstract int CommandTimeout { get; set; }
public abstract System.Data.CommandType CommandType { get; set; }
public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } set { } }
protected abstract System.Data.Common.DbConnection DbConnection { get; set; }
protected abstract System.Data.Common.DbParameterCollection DbParameterCollection { get; }
protected abstract System.Data.Common.DbTransaction DbTransaction { get; set; }
public abstract bool DesignTimeVisible { get; set; }
public System.Data.Common.DbParameterCollection Parameters { get { return default(System.Data.Common.DbParameterCollection); } }
public System.Data.Common.DbTransaction Transaction { get { return default(System.Data.Common.DbTransaction); } set { } }
public abstract System.Data.UpdateRowSource UpdatedRowSource { get; set; }
public abstract void Cancel();
protected abstract System.Data.Common.DbParameter CreateDbParameter();
public System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); }
protected abstract System.Data.Common.DbDataReader ExecuteDbDataReader(System.Data.CommandBehavior behavior);
protected virtual System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteDbDataReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public abstract int ExecuteNonQuery();
public System.Threading.Tasks.Task<int> ExecuteNonQueryAsync() { return default(System.Threading.Tasks.Task<int>); }
public virtual System.Threading.Tasks.Task<int> ExecuteNonQueryAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<int>); }
public System.Data.Common.DbDataReader ExecuteReader() { return default(System.Data.Common.DbDataReader); }
public System.Data.Common.DbDataReader ExecuteReader(System.Data.CommandBehavior behavior) { return default(System.Data.Common.DbDataReader); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync() { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Data.CommandBehavior behavior, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public System.Threading.Tasks.Task<System.Data.Common.DbDataReader> ExecuteReaderAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<System.Data.Common.DbDataReader>); }
public abstract object ExecuteScalar();
public System.Threading.Tasks.Task<object> ExecuteScalarAsync() { return default(System.Threading.Tasks.Task<object>); }
public virtual System.Threading.Tasks.Task<object> ExecuteScalarAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<object>); }
public abstract void Prepare();
}
public abstract partial class DbConnection : System.IDisposable
{
protected DbConnection() { }
public abstract string ConnectionString { get; set; }
public virtual int ConnectionTimeout { get { return default(int); } }
public abstract string Database { get; }
public abstract string DataSource { get; }
public abstract string ServerVersion { get; }
public abstract System.Data.ConnectionState State { get; }
public virtual event System.Data.StateChangeEventHandler StateChange { add { } remove { } }
protected abstract System.Data.Common.DbTransaction BeginDbTransaction(System.Data.IsolationLevel isolationLevel);
public System.Data.Common.DbTransaction BeginTransaction() { return default(System.Data.Common.DbTransaction); }
public System.Data.Common.DbTransaction BeginTransaction(System.Data.IsolationLevel isolationLevel) { return default(System.Data.Common.DbTransaction); }
public abstract void ChangeDatabase(string databaseName);
public abstract void Close();
public System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); }
protected abstract System.Data.Common.DbCommand CreateDbCommand();
protected virtual void OnStateChange(System.Data.StateChangeEventArgs stateChange) { }
public abstract void Open();
public System.Threading.Tasks.Task OpenAsync() { return default(System.Threading.Tasks.Task); }
public virtual System.Threading.Tasks.Task OpenAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task); }
}
public partial class DbConnectionStringBuilder : System.Collections.ICollection, System.Collections.IDictionary, System.Collections.IEnumerable
{
public DbConnectionStringBuilder() { }
public string ConnectionString { get { return default(string); } set { } }
public virtual int Count { get { return default(int); } }
public virtual object this[string keyword] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Keys { get { return default(System.Collections.ICollection); } }
bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } }
object System.Collections.ICollection.SyncRoot { get { return default(object); } }
bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } }
object System.Collections.IDictionary.this[object keyword] { get { return default(object); } set { } }
public virtual System.Collections.ICollection Values { get { return default(System.Collections.ICollection); } }
public void Add(string keyword, object value) { }
public static void AppendKeyValuePair(System.Text.StringBuilder builder, string keyword, string value) { }
public virtual void Clear() { }
public virtual bool ContainsKey(string keyword) { return default(bool); }
public virtual bool EquivalentTo(System.Data.Common.DbConnectionStringBuilder connectionStringBuilder) { return default(bool); }
public virtual bool Remove(string keyword) { return default(bool); }
public virtual bool ShouldSerialize(string keyword) { return default(bool); }
void System.Collections.ICollection.CopyTo(System.Array array, int index) { }
void System.Collections.IDictionary.Add(object keyword, object value) { }
bool System.Collections.IDictionary.Contains(object keyword) { return default(bool); }
System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator() { return default(System.Collections.IDictionaryEnumerator); }
void System.Collections.IDictionary.Remove(object keyword) { }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return default(System.Collections.IEnumerator); }
public override string ToString() { return default(string); }
public virtual bool TryGetValue(string keyword, out object value) { value = default(object); return default(bool); }
}
public abstract partial class DbDataReader : System.Collections.IEnumerable, System.IDisposable
{
protected DbDataReader() { }
public abstract int Depth { get; }
public abstract int FieldCount { get; }
public abstract bool HasRows { get; }
public abstract bool IsClosed { get; }
public abstract object this[int ordinal] { get; }
public abstract object this[string name] { get; }
public abstract int RecordsAffected { get; }
public virtual int VisibleFieldCount { get { return default(int); } }
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract bool GetBoolean(int ordinal);
public abstract byte GetByte(int ordinal);
public abstract long GetBytes(int ordinal, long dataOffset, byte[] buffer, int bufferOffset, int length);
public abstract char GetChar(int ordinal);
public abstract long GetChars(int ordinal, long dataOffset, char[] buffer, int bufferOffset, int length);
public System.Data.Common.DbDataReader GetData(int ordinal) { return default(System.Data.Common.DbDataReader); }
public abstract string GetDataTypeName(int ordinal);
public abstract System.DateTime GetDateTime(int ordinal);
protected virtual System.Data.Common.DbDataReader GetDbDataReader(int ordinal) { return default(System.Data.Common.DbDataReader); }
public abstract decimal GetDecimal(int ordinal);
public abstract double GetDouble(int ordinal);
public abstract System.Collections.IEnumerator GetEnumerator();
public abstract System.Type GetFieldType(int ordinal);
public virtual T GetFieldValue<T>(int ordinal) { return default(T); }
public System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal) { return default(System.Threading.Tasks.Task<T>); }
public virtual System.Threading.Tasks.Task<T> GetFieldValueAsync<T>(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<T>); }
public abstract float GetFloat(int ordinal);
public abstract System.Guid GetGuid(int ordinal);
public abstract short GetInt16(int ordinal);
public abstract int GetInt32(int ordinal);
public abstract long GetInt64(int ordinal);
public abstract string GetName(int ordinal);
public abstract int GetOrdinal(string name);
public virtual System.Type GetProviderSpecificFieldType(int ordinal) { return default(System.Type); }
public virtual object GetProviderSpecificValue(int ordinal) { return default(object); }
public virtual int GetProviderSpecificValues(object[] values) { return default(int); }
public virtual System.IO.Stream GetStream(int ordinal) { return default(System.IO.Stream); }
public abstract string GetString(int ordinal);
public virtual System.IO.TextReader GetTextReader(int ordinal) { return default(System.IO.TextReader); }
public abstract object GetValue(int ordinal);
public abstract int GetValues(object[] values);
public abstract bool IsDBNull(int ordinal);
public System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal) { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> IsDBNullAsync(int ordinal, System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool NextResult();
public System.Threading.Tasks.Task<bool> NextResultAsync() { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> NextResultAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
public abstract bool Read();
public System.Threading.Tasks.Task<bool> ReadAsync() { return default(System.Threading.Tasks.Task<bool>); }
public virtual System.Threading.Tasks.Task<bool> ReadAsync(System.Threading.CancellationToken cancellationToken) { return default(System.Threading.Tasks.Task<bool>); }
}
public abstract partial class DbException : System.Exception
{
protected DbException() { }
protected DbException(string message) { }
protected DbException(string message, System.Exception innerException) { }
}
public abstract partial class DbParameter
{
protected DbParameter() { }
public abstract System.Data.DbType DbType { get; set; }
public abstract System.Data.ParameterDirection Direction { get; set; }
public abstract bool IsNullable { get; set; }
public abstract string ParameterName { get; set; }
public virtual byte Precision { get { return default(byte); } set { } }
public virtual byte Scale { get { return default(byte); } set { } }
public abstract int Size { get; set; }
public abstract string SourceColumn { get; set; }
public abstract bool SourceColumnNullMapping { get; set; }
public abstract object Value { get; set; }
public abstract void ResetDbType();
}
public abstract partial class DbParameterCollection : System.Collections.ICollection, System.Collections.IEnumerable, System.Collections.IList
{
protected DbParameterCollection() { }
public abstract int Count { get; }
public System.Data.Common.DbParameter this[int index] { get { return default(System.Data.Common.DbParameter); } set { } }
public System.Data.Common.DbParameter this[string parameterName] { get { return default(System.Data.Common.DbParameter); } set { } }
public abstract object SyncRoot { get; }
object System.Collections.IList.this[int index] { get { return default(object); } set { } }
public abstract int Add(object value);
public abstract void AddRange(System.Array values);
public abstract void Clear();
public abstract bool Contains(object value);
public abstract bool Contains(string value);
public abstract void CopyTo(System.Array array, int index);
public abstract System.Collections.IEnumerator GetEnumerator();
protected abstract System.Data.Common.DbParameter GetParameter(int index);
protected abstract System.Data.Common.DbParameter GetParameter(string parameterName);
public abstract int IndexOf(object value);
public abstract int IndexOf(string parameterName);
public abstract void Insert(int index, object value);
public abstract void Remove(object value);
public abstract void RemoveAt(int index);
public abstract void RemoveAt(string parameterName);
protected abstract void SetParameter(int index, System.Data.Common.DbParameter value);
protected abstract void SetParameter(string parameterName, System.Data.Common.DbParameter value);
}
public abstract partial class DbProviderFactory
{
protected DbProviderFactory() { }
public virtual System.Data.Common.DbCommand CreateCommand() { return default(System.Data.Common.DbCommand); }
public virtual System.Data.Common.DbConnection CreateConnection() { return default(System.Data.Common.DbConnection); }
public virtual System.Data.Common.DbConnectionStringBuilder CreateConnectionStringBuilder() { return default(System.Data.Common.DbConnectionStringBuilder); }
public virtual System.Data.Common.DbParameter CreateParameter() { return default(System.Data.Common.DbParameter); }
}
public abstract partial class DbTransaction : System.IDisposable
{
protected DbTransaction() { }
public System.Data.Common.DbConnection Connection { get { return default(System.Data.Common.DbConnection); } }
protected abstract System.Data.Common.DbConnection DbConnection { get; }
public abstract System.Data.IsolationLevel IsolationLevel { get; }
public abstract void Commit();
public void Dispose() { }
protected virtual void Dispose(bool disposing) { }
public abstract void Rollback();
}
}
| |
// 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 0.16.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.EventHub
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for NamespacesOperations.
/// </summary>
public static partial class NamespacesOperationsExtensions
{
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
public static IPage<NamespaceResource> ListBySubscription(this INamespacesOperations operations)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListBySubscriptionAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<NamespaceResource>> ListBySubscriptionAsync(this INamespacesOperations operations, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </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<NamespaceResource> ListByResourceGroup(this INamespacesOperations operations, string resourceGroupName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListByResourceGroupAsync(resourceGroupName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </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<NamespaceResource>> ListByResourceGroupAsync(this INamespacesOperations operations, string resourceGroupName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupWithHttpMessagesAsync(resourceGroupName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates Updates namespace. Once created, this namespace's resource
/// manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
public static NamespaceResource CreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates Updates namespace. Once created, this namespace's resource
/// manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NamespaceResource> CreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates Updates namespace. Once created, this namespace's resource
/// manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
public static NamespaceResource BeginCreateOrUpdate(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginCreateOrUpdateAsync(resourceGroupName, namespaceName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates Updates namespace. Once created, this namespace's resource
/// manifest is immutable. This operation is idempotent.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to create a Namespace Resource.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NamespaceResource> BeginCreateOrUpdateAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, namespaceName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void Delete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static void BeginDelete(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).BeginDeleteAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing namespace. This operation also removes all associated
/// resources under the namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task BeginDeleteAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Returns the description for the specified namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
public static NamespaceResource Get(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Returns the description for the specified namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<NamespaceResource> GetAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
public static IPage<SharedAccessAuthorizationRuleResource> ListAuthorizationRules(this INamespacesOperations operations, string resourceGroupName, string namespaceName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesAsync(resourceGroupName, namespaceName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rules for a namespace.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<IPage<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesWithHttpMessagesAsync(resourceGroupName, namespaceName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Namespace Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
public static SharedAccessAuthorizationRuleResource CreateOrUpdateAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates an authorization rule for a namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Namespace Aauthorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> CreateOrUpdateAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
public static void DeleteAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
Task.Factory.StartNew(s => ((INamespacesOperations)s).DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes a namespace authorization rule
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task DeleteAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
await operations.DeleteAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Authorization rule for a namespace by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
public static SharedAccessAuthorizationRuleResource GetAuthorizationRule(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).GetAuthorizationRuleAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rule for a namespace by name.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization rule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<SharedAccessAuthorizationRuleResource> GetAuthorizationRuleAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.GetAuthorizationRuleWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Primary and Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
public static ResourceListKeys ListKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListKeysAsync(resourceGroupName, namespaceName, authorizationRuleName), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Primary and Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> ListKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Regenerats the Primary or Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
public static ResourceListKeys RegenerateKeys(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).RegenerateKeysAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Regenerats the Primary or Secondary ConnectionStrings to the namespace
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='authorizationRuleName'>
/// The authorizationRule name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate Auth Rule.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<ResourceListKeys> RegenerateKeysAsync(this INamespacesOperations operations, string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.RegenerateKeysWithHttpMessagesAsync(resourceGroupName, namespaceName, authorizationRuleName, parameters, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </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<NamespaceResource> ListBySubscriptionNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListBySubscriptionNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists all the available namespaces within the subscription irrespective of
/// the resourceGroups.
/// </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<NamespaceResource>> ListBySubscriptionNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListBySubscriptionNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </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<NamespaceResource> ListByResourceGroupNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListByResourceGroupNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the available namespaces within a resourceGroup.
/// </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<NamespaceResource>> ListByResourceGroupNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListByResourceGroupNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Authorization rules for a namespace.
/// </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<SharedAccessAuthorizationRuleResource> ListAuthorizationRulesNext(this INamespacesOperations operations, string nextPageLink)
{
return Task.Factory.StartNew(s => ((INamespacesOperations)s).ListAuthorizationRulesNextAsync(nextPageLink), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Authorization rules for a namespace.
/// </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<SharedAccessAuthorizationRuleResource>> ListAuthorizationRulesNextAsync(this INamespacesOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
{
using (var _result = await operations.ListAuthorizationRulesNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model.
*/
using System;
using Amazon.Runtime;
namespace Amazon.DeviceFarm
{
/// <summary>
/// Constants used for properties of type ArtifactCategory.
/// </summary>
public class ArtifactCategory : ConstantClass
{
/// <summary>
/// Constant FILE for ArtifactCategory
/// </summary>
public static readonly ArtifactCategory FILE = new ArtifactCategory("FILE");
/// <summary>
/// Constant LOG for ArtifactCategory
/// </summary>
public static readonly ArtifactCategory LOG = new ArtifactCategory("LOG");
/// <summary>
/// Constant SCREENSHOT for ArtifactCategory
/// </summary>
public static readonly ArtifactCategory SCREENSHOT = new ArtifactCategory("SCREENSHOT");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ArtifactCategory(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ArtifactCategory FindValue(string value)
{
return FindValue<ArtifactCategory>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ArtifactCategory(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ArtifactType.
/// </summary>
public class ArtifactType : ConstantClass
{
/// <summary>
/// Constant APPIUM_JAVA_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType APPIUM_JAVA_OUTPUT = new ArtifactType("APPIUM_JAVA_OUTPUT");
/// <summary>
/// Constant APPIUM_JAVA_XML_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType APPIUM_JAVA_XML_OUTPUT = new ArtifactType("APPIUM_JAVA_XML_OUTPUT");
/// <summary>
/// Constant APPIUM_SERVER_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType APPIUM_SERVER_OUTPUT = new ArtifactType("APPIUM_SERVER_OUTPUT");
/// <summary>
/// Constant APPLICATION_CRASH_REPORT for ArtifactType
/// </summary>
public static readonly ArtifactType APPLICATION_CRASH_REPORT = new ArtifactType("APPLICATION_CRASH_REPORT");
/// <summary>
/// Constant AUTOMATION_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType AUTOMATION_OUTPUT = new ArtifactType("AUTOMATION_OUTPUT");
/// <summary>
/// Constant CALABASH_JAVA_XML_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType CALABASH_JAVA_XML_OUTPUT = new ArtifactType("CALABASH_JAVA_XML_OUTPUT");
/// <summary>
/// Constant CALABASH_JSON_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType CALABASH_JSON_OUTPUT = new ArtifactType("CALABASH_JSON_OUTPUT");
/// <summary>
/// Constant CALABASH_PRETTY_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType CALABASH_PRETTY_OUTPUT = new ArtifactType("CALABASH_PRETTY_OUTPUT");
/// <summary>
/// Constant CALABASH_STANDARD_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType CALABASH_STANDARD_OUTPUT = new ArtifactType("CALABASH_STANDARD_OUTPUT");
/// <summary>
/// Constant DEVICE_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType DEVICE_LOG = new ArtifactType("DEVICE_LOG");
/// <summary>
/// Constant EXERCISER_MONKEY_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType EXERCISER_MONKEY_OUTPUT = new ArtifactType("EXERCISER_MONKEY_OUTPUT");
/// <summary>
/// Constant EXPLORER_EVENT_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType EXPLORER_EVENT_LOG = new ArtifactType("EXPLORER_EVENT_LOG");
/// <summary>
/// Constant EXPLORER_SUMMARY_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType EXPLORER_SUMMARY_LOG = new ArtifactType("EXPLORER_SUMMARY_LOG");
/// <summary>
/// Constant INSTRUMENTATION_OUTPUT for ArtifactType
/// </summary>
public static readonly ArtifactType INSTRUMENTATION_OUTPUT = new ArtifactType("INSTRUMENTATION_OUTPUT");
/// <summary>
/// Constant MESSAGE_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType MESSAGE_LOG = new ArtifactType("MESSAGE_LOG");
/// <summary>
/// Constant RESULT_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType RESULT_LOG = new ArtifactType("RESULT_LOG");
/// <summary>
/// Constant SCREENSHOT for ArtifactType
/// </summary>
public static readonly ArtifactType SCREENSHOT = new ArtifactType("SCREENSHOT");
/// <summary>
/// Constant SERVICE_LOG for ArtifactType
/// </summary>
public static readonly ArtifactType SERVICE_LOG = new ArtifactType("SERVICE_LOG");
/// <summary>
/// Constant UNKNOWN for ArtifactType
/// </summary>
public static readonly ArtifactType UNKNOWN = new ArtifactType("UNKNOWN");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ArtifactType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ArtifactType FindValue(string value)
{
return FindValue<ArtifactType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ArtifactType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type BillingMethod.
/// </summary>
public class BillingMethod : ConstantClass
{
/// <summary>
/// Constant METERED for BillingMethod
/// </summary>
public static readonly BillingMethod METERED = new BillingMethod("METERED");
/// <summary>
/// Constant UNMETERED for BillingMethod
/// </summary>
public static readonly BillingMethod UNMETERED = new BillingMethod("UNMETERED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public BillingMethod(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static BillingMethod FindValue(string value)
{
return FindValue<BillingMethod>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator BillingMethod(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DeviceAttribute.
/// </summary>
public class DeviceAttribute : ConstantClass
{
/// <summary>
/// Constant ARN for DeviceAttribute
/// </summary>
public static readonly DeviceAttribute ARN = new DeviceAttribute("ARN");
/// <summary>
/// Constant FORM_FACTOR for DeviceAttribute
/// </summary>
public static readonly DeviceAttribute FORM_FACTOR = new DeviceAttribute("FORM_FACTOR");
/// <summary>
/// Constant MANUFACTURER for DeviceAttribute
/// </summary>
public static readonly DeviceAttribute MANUFACTURER = new DeviceAttribute("MANUFACTURER");
/// <summary>
/// Constant PLATFORM for DeviceAttribute
/// </summary>
public static readonly DeviceAttribute PLATFORM = new DeviceAttribute("PLATFORM");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DeviceAttribute(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DeviceAttribute FindValue(string value)
{
return FindValue<DeviceAttribute>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DeviceAttribute(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DeviceFormFactor.
/// </summary>
public class DeviceFormFactor : ConstantClass
{
/// <summary>
/// Constant PHONE for DeviceFormFactor
/// </summary>
public static readonly DeviceFormFactor PHONE = new DeviceFormFactor("PHONE");
/// <summary>
/// Constant TABLET for DeviceFormFactor
/// </summary>
public static readonly DeviceFormFactor TABLET = new DeviceFormFactor("TABLET");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DeviceFormFactor(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DeviceFormFactor FindValue(string value)
{
return FindValue<DeviceFormFactor>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DeviceFormFactor(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DevicePlatform.
/// </summary>
public class DevicePlatform : ConstantClass
{
/// <summary>
/// Constant ANDROID for DevicePlatform
/// </summary>
public static readonly DevicePlatform ANDROID = new DevicePlatform("ANDROID");
/// <summary>
/// Constant IOS for DevicePlatform
/// </summary>
public static readonly DevicePlatform IOS = new DevicePlatform("IOS");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DevicePlatform(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DevicePlatform FindValue(string value)
{
return FindValue<DevicePlatform>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DevicePlatform(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type DevicePoolType.
/// </summary>
public class DevicePoolType : ConstantClass
{
/// <summary>
/// Constant CURATED for DevicePoolType
/// </summary>
public static readonly DevicePoolType CURATED = new DevicePoolType("CURATED");
/// <summary>
/// Constant PRIVATE for DevicePoolType
/// </summary>
public static readonly DevicePoolType PRIVATE = new DevicePoolType("PRIVATE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public DevicePoolType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static DevicePoolType FindValue(string value)
{
return FindValue<DevicePoolType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator DevicePoolType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ExecutionResult.
/// </summary>
public class ExecutionResult : ConstantClass
{
/// <summary>
/// Constant ERRORED for ExecutionResult
/// </summary>
public static readonly ExecutionResult ERRORED = new ExecutionResult("ERRORED");
/// <summary>
/// Constant FAILED for ExecutionResult
/// </summary>
public static readonly ExecutionResult FAILED = new ExecutionResult("FAILED");
/// <summary>
/// Constant PASSED for ExecutionResult
/// </summary>
public static readonly ExecutionResult PASSED = new ExecutionResult("PASSED");
/// <summary>
/// Constant PENDING for ExecutionResult
/// </summary>
public static readonly ExecutionResult PENDING = new ExecutionResult("PENDING");
/// <summary>
/// Constant SKIPPED for ExecutionResult
/// </summary>
public static readonly ExecutionResult SKIPPED = new ExecutionResult("SKIPPED");
/// <summary>
/// Constant STOPPED for ExecutionResult
/// </summary>
public static readonly ExecutionResult STOPPED = new ExecutionResult("STOPPED");
/// <summary>
/// Constant WARNED for ExecutionResult
/// </summary>
public static readonly ExecutionResult WARNED = new ExecutionResult("WARNED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ExecutionResult(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ExecutionResult FindValue(string value)
{
return FindValue<ExecutionResult>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ExecutionResult(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type ExecutionStatus.
/// </summary>
public class ExecutionStatus : ConstantClass
{
/// <summary>
/// Constant COMPLETED for ExecutionStatus
/// </summary>
public static readonly ExecutionStatus COMPLETED = new ExecutionStatus("COMPLETED");
/// <summary>
/// Constant PENDING for ExecutionStatus
/// </summary>
public static readonly ExecutionStatus PENDING = new ExecutionStatus("PENDING");
/// <summary>
/// Constant PROCESSING for ExecutionStatus
/// </summary>
public static readonly ExecutionStatus PROCESSING = new ExecutionStatus("PROCESSING");
/// <summary>
/// Constant RUNNING for ExecutionStatus
/// </summary>
public static readonly ExecutionStatus RUNNING = new ExecutionStatus("RUNNING");
/// <summary>
/// Constant SCHEDULING for ExecutionStatus
/// </summary>
public static readonly ExecutionStatus SCHEDULING = new ExecutionStatus("SCHEDULING");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public ExecutionStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static ExecutionStatus FindValue(string value)
{
return FindValue<ExecutionStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator ExecutionStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type RuleOperator.
/// </summary>
public class RuleOperator : ConstantClass
{
/// <summary>
/// Constant EQUALS_TO for RuleOperator
/// </summary>
public static readonly RuleOperator EQUALS_TO = new RuleOperator("EQUALS");
/// <summary>
/// Constant GREATER_THAN for RuleOperator
/// </summary>
public static readonly RuleOperator GREATER_THAN = new RuleOperator("GREATER_THAN");
/// <summary>
/// Constant IN for RuleOperator
/// </summary>
public static readonly RuleOperator IN = new RuleOperator("IN");
/// <summary>
/// Constant LESS_THAN for RuleOperator
/// </summary>
public static readonly RuleOperator LESS_THAN = new RuleOperator("LESS_THAN");
/// <summary>
/// Constant NOT_IN for RuleOperator
/// </summary>
public static readonly RuleOperator NOT_IN = new RuleOperator("NOT_IN");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public RuleOperator(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static RuleOperator FindValue(string value)
{
return FindValue<RuleOperator>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator RuleOperator(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type SampleType.
/// </summary>
public class SampleType : ConstantClass
{
/// <summary>
/// Constant CPU for SampleType
/// </summary>
public static readonly SampleType CPU = new SampleType("CPU");
/// <summary>
/// Constant MEMORY for SampleType
/// </summary>
public static readonly SampleType MEMORY = new SampleType("MEMORY");
/// <summary>
/// Constant NATIVE_AVG_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType NATIVE_AVG_DRAWTIME = new SampleType("NATIVE_AVG_DRAWTIME");
/// <summary>
/// Constant NATIVE_FPS for SampleType
/// </summary>
public static readonly SampleType NATIVE_FPS = new SampleType("NATIVE_FPS");
/// <summary>
/// Constant NATIVE_FRAMES for SampleType
/// </summary>
public static readonly SampleType NATIVE_FRAMES = new SampleType("NATIVE_FRAMES");
/// <summary>
/// Constant NATIVE_MAX_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType NATIVE_MAX_DRAWTIME = new SampleType("NATIVE_MAX_DRAWTIME");
/// <summary>
/// Constant NATIVE_MIN_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType NATIVE_MIN_DRAWTIME = new SampleType("NATIVE_MIN_DRAWTIME");
/// <summary>
/// Constant OPENGL_AVG_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType OPENGL_AVG_DRAWTIME = new SampleType("OPENGL_AVG_DRAWTIME");
/// <summary>
/// Constant OPENGL_FPS for SampleType
/// </summary>
public static readonly SampleType OPENGL_FPS = new SampleType("OPENGL_FPS");
/// <summary>
/// Constant OPENGL_FRAMES for SampleType
/// </summary>
public static readonly SampleType OPENGL_FRAMES = new SampleType("OPENGL_FRAMES");
/// <summary>
/// Constant OPENGL_MAX_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType OPENGL_MAX_DRAWTIME = new SampleType("OPENGL_MAX_DRAWTIME");
/// <summary>
/// Constant OPENGL_MIN_DRAWTIME for SampleType
/// </summary>
public static readonly SampleType OPENGL_MIN_DRAWTIME = new SampleType("OPENGL_MIN_DRAWTIME");
/// <summary>
/// Constant RX for SampleType
/// </summary>
public static readonly SampleType RX = new SampleType("RX");
/// <summary>
/// Constant RX_RATE for SampleType
/// </summary>
public static readonly SampleType RX_RATE = new SampleType("RX_RATE");
/// <summary>
/// Constant THREADS for SampleType
/// </summary>
public static readonly SampleType THREADS = new SampleType("THREADS");
/// <summary>
/// Constant TX for SampleType
/// </summary>
public static readonly SampleType TX = new SampleType("TX");
/// <summary>
/// Constant TX_RATE for SampleType
/// </summary>
public static readonly SampleType TX_RATE = new SampleType("TX_RATE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public SampleType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static SampleType FindValue(string value)
{
return FindValue<SampleType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator SampleType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type TestType.
/// </summary>
public class TestType : ConstantClass
{
/// <summary>
/// Constant APPIUM_JAVA_JUNIT for TestType
/// </summary>
public static readonly TestType APPIUM_JAVA_JUNIT = new TestType("APPIUM_JAVA_JUNIT");
/// <summary>
/// Constant APPIUM_JAVA_TESTNG for TestType
/// </summary>
public static readonly TestType APPIUM_JAVA_TESTNG = new TestType("APPIUM_JAVA_TESTNG");
/// <summary>
/// Constant BUILTIN_EXPLORER for TestType
/// </summary>
public static readonly TestType BUILTIN_EXPLORER = new TestType("BUILTIN_EXPLORER");
/// <summary>
/// Constant BUILTIN_FUZZ for TestType
/// </summary>
public static readonly TestType BUILTIN_FUZZ = new TestType("BUILTIN_FUZZ");
/// <summary>
/// Constant CALABASH for TestType
/// </summary>
public static readonly TestType CALABASH = new TestType("CALABASH");
/// <summary>
/// Constant INSTRUMENTATION for TestType
/// </summary>
public static readonly TestType INSTRUMENTATION = new TestType("INSTRUMENTATION");
/// <summary>
/// Constant UIAUTOMATION for TestType
/// </summary>
public static readonly TestType UIAUTOMATION = new TestType("UIAUTOMATION");
/// <summary>
/// Constant UIAUTOMATOR for TestType
/// </summary>
public static readonly TestType UIAUTOMATOR = new TestType("UIAUTOMATOR");
/// <summary>
/// Constant XCTEST for TestType
/// </summary>
public static readonly TestType XCTEST = new TestType("XCTEST");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public TestType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static TestType FindValue(string value)
{
return FindValue<TestType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator TestType(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type UploadStatus.
/// </summary>
public class UploadStatus : ConstantClass
{
/// <summary>
/// Constant FAILED for UploadStatus
/// </summary>
public static readonly UploadStatus FAILED = new UploadStatus("FAILED");
/// <summary>
/// Constant INITIALIZED for UploadStatus
/// </summary>
public static readonly UploadStatus INITIALIZED = new UploadStatus("INITIALIZED");
/// <summary>
/// Constant PROCESSING for UploadStatus
/// </summary>
public static readonly UploadStatus PROCESSING = new UploadStatus("PROCESSING");
/// <summary>
/// Constant SUCCEEDED for UploadStatus
/// </summary>
public static readonly UploadStatus SUCCEEDED = new UploadStatus("SUCCEEDED");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public UploadStatus(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static UploadStatus FindValue(string value)
{
return FindValue<UploadStatus>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator UploadStatus(string value)
{
return FindValue(value);
}
}
/// <summary>
/// Constants used for properties of type UploadType.
/// </summary>
public class UploadType : ConstantClass
{
/// <summary>
/// Constant ANDROID_APP for UploadType
/// </summary>
public static readonly UploadType ANDROID_APP = new UploadType("ANDROID_APP");
/// <summary>
/// Constant APPIUM_JAVA_JUNIT_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType APPIUM_JAVA_JUNIT_TEST_PACKAGE = new UploadType("APPIUM_JAVA_JUNIT_TEST_PACKAGE");
/// <summary>
/// Constant APPIUM_JAVA_TESTNG_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType APPIUM_JAVA_TESTNG_TEST_PACKAGE = new UploadType("APPIUM_JAVA_TESTNG_TEST_PACKAGE");
/// <summary>
/// Constant CALABASH_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType CALABASH_TEST_PACKAGE = new UploadType("CALABASH_TEST_PACKAGE");
/// <summary>
/// Constant EXTERNAL_DATA for UploadType
/// </summary>
public static readonly UploadType EXTERNAL_DATA = new UploadType("EXTERNAL_DATA");
/// <summary>
/// Constant INSTRUMENTATION_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType INSTRUMENTATION_TEST_PACKAGE = new UploadType("INSTRUMENTATION_TEST_PACKAGE");
/// <summary>
/// Constant IOS_APP for UploadType
/// </summary>
public static readonly UploadType IOS_APP = new UploadType("IOS_APP");
/// <summary>
/// Constant UIAUTOMATION_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType UIAUTOMATION_TEST_PACKAGE = new UploadType("UIAUTOMATION_TEST_PACKAGE");
/// <summary>
/// Constant UIAUTOMATOR_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType UIAUTOMATOR_TEST_PACKAGE = new UploadType("UIAUTOMATOR_TEST_PACKAGE");
/// <summary>
/// Constant XCTEST_TEST_PACKAGE for UploadType
/// </summary>
public static readonly UploadType XCTEST_TEST_PACKAGE = new UploadType("XCTEST_TEST_PACKAGE");
/// <summary>
/// This constant constructor does not need to be called if the constant
/// you are attempting to use is already defined as a static instance of
/// this class.
/// This constructor should be used to construct constants that are not
/// defined as statics, for instance if attempting to use a feature that is
/// newer than the current version of the SDK.
/// </summary>
public UploadType(string value)
: base(value)
{
}
/// <summary>
/// Finds the constant for the unique value.
/// </summary>
/// <param name="value">The unique value for the constant</param>
/// <returns>The constant for the unique value</returns>
public static UploadType FindValue(string value)
{
return FindValue<UploadType>(value);
}
/// <summary>
/// Utility method to convert strings to the constant class.
/// </summary>
/// <param name="value">The string value to convert to the constant class.</param>
/// <returns></returns>
public static implicit operator UploadType(string value)
{
return FindValue(value);
}
}
}
| |
namespace android.view
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class ViewTreeObserver : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ViewTreeObserver()
{
InitJNI();
}
internal ViewTreeObserver(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_))]
public interface OnGlobalFocusChangeListener : global::MonoJavaBridge.IJavaObject
{
void onGlobalFocusChanged(android.view.View arg0, android.view.View arg1);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener))]
public sealed partial class OnGlobalFocusChangeListener_ : java.lang.Object, OnGlobalFocusChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnGlobalFocusChangeListener_()
{
InitJNI();
}
internal OnGlobalFocusChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onGlobalFocusChanged9659;
void android.view.ViewTreeObserver.OnGlobalFocusChangeListener.onGlobalFocusChanged(android.view.View arg0, android.view.View arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_._onGlobalFocusChanged9659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_.staticClass, global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_._onGlobalFocusChanged9659, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnGlobalFocusChangeListener"));
global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_._onGlobalFocusChanged9659 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnGlobalFocusChangeListener_.staticClass, "onGlobalFocusChanged", "(Landroid/view/View;Landroid/view/View;)V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnGlobalLayoutListener_))]
public interface OnGlobalLayoutListener : global::MonoJavaBridge.IJavaObject
{
void onGlobalLayout();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnGlobalLayoutListener))]
public sealed partial class OnGlobalLayoutListener_ : java.lang.Object, OnGlobalLayoutListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnGlobalLayoutListener_()
{
InitJNI();
}
internal OnGlobalLayoutListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onGlobalLayout9660;
void android.view.ViewTreeObserver.OnGlobalLayoutListener.onGlobalLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnGlobalLayoutListener_._onGlobalLayout9660);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnGlobalLayoutListener_.staticClass, global::android.view.ViewTreeObserver.OnGlobalLayoutListener_._onGlobalLayout9660);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.OnGlobalLayoutListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnGlobalLayoutListener"));
global::android.view.ViewTreeObserver.OnGlobalLayoutListener_._onGlobalLayout9660 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnGlobalLayoutListener_.staticClass, "onGlobalLayout", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnPreDrawListener_))]
public interface OnPreDrawListener : global::MonoJavaBridge.IJavaObject
{
bool onPreDraw();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnPreDrawListener))]
public sealed partial class OnPreDrawListener_ : java.lang.Object, OnPreDrawListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnPreDrawListener_()
{
InitJNI();
}
internal OnPreDrawListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onPreDraw9661;
bool android.view.ViewTreeObserver.OnPreDrawListener.onPreDraw()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnPreDrawListener_._onPreDraw9661);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnPreDrawListener_.staticClass, global::android.view.ViewTreeObserver.OnPreDrawListener_._onPreDraw9661);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.OnPreDrawListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnPreDrawListener"));
global::android.view.ViewTreeObserver.OnPreDrawListener_._onPreDraw9661 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnPreDrawListener_.staticClass, "onPreDraw", "()Z");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnScrollChangedListener_))]
public interface OnScrollChangedListener : global::MonoJavaBridge.IJavaObject
{
void onScrollChanged();
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnScrollChangedListener))]
public sealed partial class OnScrollChangedListener_ : java.lang.Object, OnScrollChangedListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnScrollChangedListener_()
{
InitJNI();
}
internal OnScrollChangedListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onScrollChanged9662;
void android.view.ViewTreeObserver.OnScrollChangedListener.onScrollChanged()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnScrollChangedListener_._onScrollChanged9662);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnScrollChangedListener_.staticClass, global::android.view.ViewTreeObserver.OnScrollChangedListener_._onScrollChanged9662);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.OnScrollChangedListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnScrollChangedListener"));
global::android.view.ViewTreeObserver.OnScrollChangedListener_._onScrollChanged9662 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnScrollChangedListener_.staticClass, "onScrollChanged", "()V");
}
}
[global::MonoJavaBridge.JavaInterface(typeof(global::android.view.ViewTreeObserver.OnTouchModeChangeListener_))]
public interface OnTouchModeChangeListener : global::MonoJavaBridge.IJavaObject
{
void onTouchModeChanged(bool arg0);
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.view.ViewTreeObserver.OnTouchModeChangeListener))]
public sealed partial class OnTouchModeChangeListener_ : java.lang.Object, OnTouchModeChangeListener
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static OnTouchModeChangeListener_()
{
InitJNI();
}
internal OnTouchModeChangeListener_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onTouchModeChanged9663;
void android.view.ViewTreeObserver.OnTouchModeChangeListener.onTouchModeChanged(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnTouchModeChangeListener_._onTouchModeChanged9663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.OnTouchModeChangeListener_.staticClass, global::android.view.ViewTreeObserver.OnTouchModeChangeListener_._onTouchModeChanged9663, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.OnTouchModeChangeListener_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver$OnTouchModeChangeListener"));
global::android.view.ViewTreeObserver.OnTouchModeChangeListener_._onTouchModeChanged9663 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.OnTouchModeChangeListener_.staticClass, "onTouchModeChanged", "(Z)V");
}
}
internal static global::MonoJavaBridge.MethodId _isAlive9664;
public bool isAlive()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver._isAlive9664);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._isAlive9664);
}
internal static global::MonoJavaBridge.MethodId _addOnGlobalFocusChangeListener9665;
public void addOnGlobalFocusChangeListener(android.view.ViewTreeObserver.OnGlobalFocusChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._addOnGlobalFocusChangeListener9665, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._addOnGlobalFocusChangeListener9665, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeOnGlobalFocusChangeListener9666;
public void removeOnGlobalFocusChangeListener(android.view.ViewTreeObserver.OnGlobalFocusChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._removeOnGlobalFocusChangeListener9666, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._removeOnGlobalFocusChangeListener9666, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addOnGlobalLayoutListener9667;
public void addOnGlobalLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._addOnGlobalLayoutListener9667, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._addOnGlobalLayoutListener9667, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeGlobalOnLayoutListener9668;
public void removeGlobalOnLayoutListener(android.view.ViewTreeObserver.OnGlobalLayoutListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._removeGlobalOnLayoutListener9668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._removeGlobalOnLayoutListener9668, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addOnPreDrawListener9669;
public void addOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._addOnPreDrawListener9669, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._addOnPreDrawListener9669, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeOnPreDrawListener9670;
public void removeOnPreDrawListener(android.view.ViewTreeObserver.OnPreDrawListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._removeOnPreDrawListener9670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._removeOnPreDrawListener9670, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addOnScrollChangedListener9671;
public void addOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._addOnScrollChangedListener9671, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._addOnScrollChangedListener9671, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeOnScrollChangedListener9672;
public void removeOnScrollChangedListener(android.view.ViewTreeObserver.OnScrollChangedListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._removeOnScrollChangedListener9672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._removeOnScrollChangedListener9672, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addOnTouchModeChangeListener9673;
public void addOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._addOnTouchModeChangeListener9673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._addOnTouchModeChangeListener9673, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _removeOnTouchModeChangeListener9674;
public void removeOnTouchModeChangeListener(android.view.ViewTreeObserver.OnTouchModeChangeListener arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._removeOnTouchModeChangeListener9674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._removeOnTouchModeChangeListener9674, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _dispatchOnGlobalLayout9675;
public void dispatchOnGlobalLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver._dispatchOnGlobalLayout9675);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._dispatchOnGlobalLayout9675);
}
internal static global::MonoJavaBridge.MethodId _dispatchOnPreDraw9676;
public bool dispatchOnPreDraw()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver._dispatchOnPreDraw9676);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.view.ViewTreeObserver.staticClass, global::android.view.ViewTreeObserver._dispatchOnPreDraw9676);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.view.ViewTreeObserver.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/view/ViewTreeObserver"));
global::android.view.ViewTreeObserver._isAlive9664 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "isAlive", "()Z");
global::android.view.ViewTreeObserver._addOnGlobalFocusChangeListener9665 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "addOnGlobalFocusChangeListener", "(Landroid/view/ViewTreeObserver$OnGlobalFocusChangeListener;)V");
global::android.view.ViewTreeObserver._removeOnGlobalFocusChangeListener9666 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "removeOnGlobalFocusChangeListener", "(Landroid/view/ViewTreeObserver$OnGlobalFocusChangeListener;)V");
global::android.view.ViewTreeObserver._addOnGlobalLayoutListener9667 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "addOnGlobalLayoutListener", "(Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V");
global::android.view.ViewTreeObserver._removeGlobalOnLayoutListener9668 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "removeGlobalOnLayoutListener", "(Landroid/view/ViewTreeObserver$OnGlobalLayoutListener;)V");
global::android.view.ViewTreeObserver._addOnPreDrawListener9669 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "addOnPreDrawListener", "(Landroid/view/ViewTreeObserver$OnPreDrawListener;)V");
global::android.view.ViewTreeObserver._removeOnPreDrawListener9670 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "removeOnPreDrawListener", "(Landroid/view/ViewTreeObserver$OnPreDrawListener;)V");
global::android.view.ViewTreeObserver._addOnScrollChangedListener9671 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "addOnScrollChangedListener", "(Landroid/view/ViewTreeObserver$OnScrollChangedListener;)V");
global::android.view.ViewTreeObserver._removeOnScrollChangedListener9672 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "removeOnScrollChangedListener", "(Landroid/view/ViewTreeObserver$OnScrollChangedListener;)V");
global::android.view.ViewTreeObserver._addOnTouchModeChangeListener9673 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "addOnTouchModeChangeListener", "(Landroid/view/ViewTreeObserver$OnTouchModeChangeListener;)V");
global::android.view.ViewTreeObserver._removeOnTouchModeChangeListener9674 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "removeOnTouchModeChangeListener", "(Landroid/view/ViewTreeObserver$OnTouchModeChangeListener;)V");
global::android.view.ViewTreeObserver._dispatchOnGlobalLayout9675 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "dispatchOnGlobalLayout", "()V");
global::android.view.ViewTreeObserver._dispatchOnPreDraw9676 = @__env.GetMethodIDNoThrow(global::android.view.ViewTreeObserver.staticClass, "dispatchOnPreDraw", "()Z");
}
}
}
| |
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//------------------------------------------------------------------------------
// <auto-generated>
// Types declaration for SharpDX.DirectSound namespace.
// This code was generated by a tool.
// Date : 28/03/2015 21:51:16
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Runtime.InteropServices;
using System.Security;
namespace SharpDX.DirectSound {
#pragma warning disable 419
#pragma warning disable 1587
#pragma warning disable 1574
/// <summary>
/// Functions
/// </summary>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.DirectSound.CaptureEffectGuid']/*"/>
static partial class CaptureEffectGuid {
/// <summary>Constant AcousticEchoCancellationCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_CLASS_AEC</unmanaged>
public static readonly System.Guid AcousticEchoCancellationCaptureEffect = new System.Guid("bf963d80-c559-11d0-8a2b-00a0c9255ac1");
/// <summary>Constant MicrosoftAcousticEchoCancellationCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_MS_AEC</unmanaged>
public static readonly System.Guid MicrosoftAcousticEchoCancellationCaptureEffect = new System.Guid("cdebb919-379a-488a-8765-f53cfd36de40");
/// <summary>Constant SystemAcousticEchoCancellationCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_SYSTEM_AEC</unmanaged>
public static readonly System.Guid SystemAcousticEchoCancellationCaptureEffect = new System.Guid("1c22c56d-9879-4f5b-a389-27996ddc2810");
/// <summary>Constant NoiseSuppressionCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_CLASS_NS</unmanaged>
public static readonly System.Guid NoiseSuppressionCaptureEffect = new System.Guid("e07f903f-62fd-4e60-8cdd-dea7236665b5");
/// <summary>Constant MicrosoftNoiseSuppressionCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_MS_NS</unmanaged>
public static readonly System.Guid MicrosoftNoiseSuppressionCaptureEffect = new System.Guid("11c5c73b-66e9-4ba1-a0ba-e814c6eed92d");
/// <summary>Constant SystemNoiseSuppressionCaptureEffect.</summary>
/// <unmanaged>GUID_DSCFX_SYSTEM_NS</unmanaged>
public static readonly System.Guid SystemNoiseSuppressionCaptureEffect = new System.Guid("5ab0882e-7274-4516-877d-4eee99ba4fd0");
}
/// <summary>
/// Functions
/// </summary>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.DirectSound.DirectSound3DAlgorithmGuid']/*"/>
static partial class DirectSound3DAlgorithmGuid {
/// <summary>Constant FullHrt3DAlgorithm.</summary>
/// <unmanaged>DS3DALG_HRTF_FULL</unmanaged>
public static readonly System.Guid FullHrt3DAlgorithm = new System.Guid("c2413340-1c1b-11d2-94f5-00c04fc28aca");
/// <summary>Constant LightHrt3DAlgorithm.</summary>
/// <unmanaged>DS3DALG_HRTF_LIGHT</unmanaged>
public static readonly System.Guid LightHrt3DAlgorithm = new System.Guid("c2413342-1c1b-11d2-94f5-00c04fc28aca");
/// <summary>Constant NoVirtualization3DAlgorithm.</summary>
/// <unmanaged>DS3DALG_NO_VIRTUALIZATION</unmanaged>
public static readonly System.Guid NoVirtualization3DAlgorithm = new System.Guid("c241333f-1c1b-11d2-94f5-00c04fc28aca");
}
/// <summary>
/// Functions
/// </summary>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.DirectSound.DSound']/*"/>
static partial class DSound {
/// <summary>Constant AllObjects.</summary>
/// <unmanaged>GUID_All_Objects</unmanaged>
public static readonly System.Guid AllObjects = new System.Guid("aa114de5-c262-4169-a1c8-23d698cc73b5");
/// <summary>
/// The DirectSoundCaptureCreate8 function creates and initializes an object that supports the IDirectSoundCapture8 interface. Although the older<strong>DirectSoundCaptureCreate</strong>function can also be used to obtain theIDirectSoundCapture8interface, the object created by that function cannot be used to create capture buffers that support theIDirectSoundCaptureBuffer8interface.
/// </summary>
/// <param name="cGuidDeviceRef">No documentation.</param>
/// <param name="dSC8Out">No documentation.</param>
/// <param name="unkOuterRef">No documentation.</param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following values.</p> <table> <tr><th>Return Code</th></tr> <tr><td>DSERR_ALLOCATED</td></tr> <tr><td>DSERR_INVALIDPARAM</td></tr> <tr><td>DSERR_NOAGGREGATION</td></tr> <tr><td>DSERR_OUTOFMEMORY</td></tr> </table></returns>
/// <remarks>
/// <p>On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.</p>
/// </remarks>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCaptureCreate8']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundcapturecreate8</msdn-id>
/// <unmanaged>HRESULT DirectSoundCaptureCreate8([In, Optional] const GUID* pcGuidDevice,[Out, Fast] IDirectSoundCapture** ppDSC8,[In] IUnknown* pUnkOuter)</unmanaged>
/// <unmanaged-short>DirectSoundCaptureCreate8</unmanaged-short>
public static void CaptureCreate8(System.Guid? cGuidDeviceRef, SharpDX.DirectSound.DirectSoundCapture dSC8Out, SharpDX.ComObject unkOuterRef) {
unsafe {
System.Guid cGuidDeviceRef_;
if (cGuidDeviceRef.HasValue)
cGuidDeviceRef_ = cGuidDeviceRef.Value;
IntPtr dSC8Out_ = IntPtr.Zero;
SharpDX.Result __result__;
__result__=
DirectSoundCaptureCreate8_((cGuidDeviceRef.HasValue)?&cGuidDeviceRef_:(void*)IntPtr.Zero, &dSC8Out_, (void*)((unkOuterRef == null)?IntPtr.Zero:unkOuterRef.NativePointer));
((SharpDX.DirectSound.DirectSoundCapture)dSC8Out).NativePointer = dSC8Out_;
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCaptureCreate8", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCaptureCreate8_(void* arg0,void* arg1,void* arg2);
/// <summary>
/// The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.
/// </summary>
/// <param name="dSEnumCallbackRef"><dd> Address of the DSEnumCallback function that will be called for each device installed in the system. </dd></param>
/// <param name="contextRef"><dd> Address of the user-defined context passed to the enumeration callback function every time that function is called. </dd></param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.</p></returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundEnumerateA']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundenumerate</msdn-id>
/// <unmanaged>HRESULT DirectSoundEnumerateA([In] __function__stdcall* pDSEnumCallback,[In, Optional] void* pContext)</unmanaged>
/// <unmanaged-short>DirectSoundEnumerateA</unmanaged-short>
public static void EnumerateA(SharpDX.FunctionCallback dSEnumCallbackRef, System.IntPtr contextRef) {
unsafe {
SharpDX.Result __result__;
__result__=
DirectSoundEnumerateA_(dSEnumCallbackRef, (void*)contextRef);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundEnumerateA", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundEnumerateA_(void* arg0,void* arg1);
/// <summary>
/// The DirectSoundEnumerate function enumerates the DirectSound drivers installed in the system.
/// </summary>
/// <param name="dSEnumCallbackRef"><dd> Address of the DSEnumCallback function that will be called for each device installed in the system. </dd></param>
/// <param name="contextRef"><dd> Address of the user-defined context passed to the enumeration callback function every time that function is called. </dd></param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.</p></returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundEnumerateW']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundenumerate</msdn-id>
/// <unmanaged>HRESULT DirectSoundEnumerateW([In] __function__stdcall* pDSEnumCallback,[In, Optional] void* pContext)</unmanaged>
/// <unmanaged-short>DirectSoundEnumerateW</unmanaged-short>
public static void EnumerateW(SharpDX.FunctionCallback dSEnumCallbackRef, System.IntPtr contextRef) {
unsafe {
SharpDX.Result __result__;
__result__=
DirectSoundEnumerateW_(dSEnumCallbackRef, (void*)contextRef);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundEnumerateW", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundEnumerateW_(void* arg0,void* arg1);
/// <summary>
/// The DirectSoundCaptureCreate8 function creates and initializes an object that supports the IDirectSoundCapture8 interface. Although the older<strong>DirectSoundCaptureCreate</strong>function can also be used to obtain theIDirectSoundCapture8interface, the object created by that function cannot be used to create capture buffers that support theIDirectSoundCaptureBuffer8interface.
/// </summary>
/// <param name="cGuidDeviceRef">No documentation.</param>
/// <param name="dSCOut">No documentation.</param>
/// <param name="unkOuterRef">No documentation.</param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following values.</p> <table> <tr><th>Return Code</th></tr> <tr><td>DSERR_ALLOCATED</td></tr> <tr><td>DSERR_INVALIDPARAM</td></tr> <tr><td>DSERR_NOAGGREGATION</td></tr> <tr><td>DSERR_OUTOFMEMORY</td></tr> </table></returns>
/// <remarks>
/// <p>On sound cards that do not support full duplex, this method will fail and return DSERR_ALLOCATED.</p>
/// </remarks>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCaptureCreate']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundcapturecreate8</msdn-id>
/// <unmanaged>HRESULT DirectSoundCaptureCreate([In, Optional] const GUID* pcGuidDevice,[Out] IDirectSoundCapture** ppDSC,[In] IUnknown* pUnkOuter)</unmanaged>
/// <unmanaged-short>DirectSoundCaptureCreate</unmanaged-short>
public static void CaptureCreate(System.Guid? cGuidDeviceRef, out SharpDX.DirectSound.DirectSoundCapture dSCOut, SharpDX.ComObject unkOuterRef) {
unsafe {
System.Guid cGuidDeviceRef_;
if (cGuidDeviceRef.HasValue)
cGuidDeviceRef_ = cGuidDeviceRef.Value;
IntPtr dSCOut_ = IntPtr.Zero;
SharpDX.Result __result__;
__result__=
DirectSoundCaptureCreate_((cGuidDeviceRef.HasValue)?&cGuidDeviceRef_:(void*)IntPtr.Zero, &dSCOut_, (void*)((unkOuterRef == null)?IntPtr.Zero:unkOuterRef.NativePointer));
dSCOut= (dSCOut_ == IntPtr.Zero)?null:new SharpDX.DirectSound.DirectSoundCapture(dSCOut_);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCaptureCreate", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCaptureCreate_(void* arg0,void* arg1,void* arg2);
/// <summary>
/// <p>The <strong>DirectSoundFullDuplexCreate</strong> function is documented under a different name. For complete documentation of this function, see DirectSoundFullDuplexCreate8. </p>
/// </summary>
/// <param name="cGuidCaptureDeviceRef">No documentation.</param>
/// <param name="cGuidRenderDeviceRef">No documentation.</param>
/// <param name="cDSCBufferDescRef">No documentation.</param>
/// <param name="cDSBufferDescRef">No documentation.</param>
/// <param name="hWnd">No documentation.</param>
/// <param name="dwLevel">No documentation.</param>
/// <param name="dSFDOut">No documentation.</param>
/// <param name="dSCBuffer8Out">No documentation.</param>
/// <param name="dSBuffer8Out">No documentation.</param>
/// <param name="unkOuterRef">No documentation.</param>
/// <returns><p>If this function succeeds, it returns <strong><see cref="SharpDX.Result.Ok"/></strong>. Otherwise, it returns an <strong><see cref="SharpDX.Result"/></strong> error code.</p></returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundFullDuplexCreate']/*"/>
/// <msdn-id>bb432248</msdn-id>
/// <unmanaged>HRESULT DirectSoundFullDuplexCreate([In, Optional] const GUID* pcGuidCaptureDevice,[In, Optional] const GUID* pcGuidRenderDevice,[In] const DSCBUFFERDESC* pcDSCBufferDesc,[In] const DSBUFFERDESC* pcDSBufferDesc,[In] HWND hWnd,[In] unsigned int dwLevel,[Out, Fast] IDirectSoundFullDuplex** ppDSFD,[Out] IDirectSoundCaptureBuffer8** ppDSCBuffer8,[Out] IDirectSoundBuffer8** ppDSBuffer8,[In] IUnknown* pUnkOuter)</unmanaged>
/// <unmanaged-short>DirectSoundFullDuplexCreate</unmanaged-short>
public static void FullDuplexCreate(System.Guid? cGuidCaptureDeviceRef, System.Guid? cGuidRenderDeviceRef, SharpDX.DirectSound.CaptureBufferDescription cDSCBufferDescRef, SharpDX.DirectSound.SoundBufferDescription cDSBufferDescRef, System.IntPtr hWnd, int dwLevel, SharpDX.DirectSound.FullDuplex dSFDOut, out SharpDX.DirectSound.CaptureBuffer dSCBuffer8Out, out SharpDX.DirectSound.SecondarySoundBuffer dSBuffer8Out, SharpDX.ComObject unkOuterRef) {
unsafe {
System.Guid cGuidCaptureDeviceRef_;
if (cGuidCaptureDeviceRef.HasValue)
cGuidCaptureDeviceRef_ = cGuidCaptureDeviceRef.Value;
System.Guid cGuidRenderDeviceRef_;
if (cGuidRenderDeviceRef.HasValue)
cGuidRenderDeviceRef_ = cGuidRenderDeviceRef.Value;
var cDSCBufferDescRef_ = SharpDX.DirectSound.CaptureBufferDescription.__NewNative();
cDSCBufferDescRef.__MarshalTo(ref cDSCBufferDescRef_);
var cDSBufferDescRef_ = SharpDX.DirectSound.SoundBufferDescription.__NewNative();
cDSBufferDescRef.__MarshalTo(ref cDSBufferDescRef_);
IntPtr dSFDOut_ = IntPtr.Zero;
IntPtr dSCBuffer8Out_ = IntPtr.Zero;
IntPtr dSBuffer8Out_ = IntPtr.Zero;
SharpDX.Result __result__;
__result__=
DirectSoundFullDuplexCreate_((cGuidCaptureDeviceRef.HasValue)?&cGuidCaptureDeviceRef_:(void*)IntPtr.Zero, (cGuidRenderDeviceRef.HasValue)?&cGuidRenderDeviceRef_:(void*)IntPtr.Zero, &cDSCBufferDescRef_, &cDSBufferDescRef_, (void*)hWnd, dwLevel, &dSFDOut_, &dSCBuffer8Out_, &dSBuffer8Out_, (void*)((unkOuterRef == null)?IntPtr.Zero:unkOuterRef.NativePointer));
cDSCBufferDescRef.__MarshalFree(ref cDSCBufferDescRef_);
cDSBufferDescRef.__MarshalFree(ref cDSBufferDescRef_);
((SharpDX.DirectSound.FullDuplex)dSFDOut).NativePointer = dSFDOut_;
dSCBuffer8Out= (dSCBuffer8Out_ == IntPtr.Zero)?null:new SharpDX.DirectSound.CaptureBuffer(dSCBuffer8Out_);
dSBuffer8Out= (dSBuffer8Out_ == IntPtr.Zero)?null:new SharpDX.DirectSound.SecondarySoundBuffer(dSBuffer8Out_);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundFullDuplexCreate", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundFullDuplexCreate_(void* arg0,void* arg1,void* arg2,void* arg3,void* arg4,int arg5,void* arg6,void* arg7,void* arg8,void* arg9);
/// <summary>
/// No documentation.
/// </summary>
/// <param name="cGuidDeviceRef">No documentation.</param>
/// <param name="dSOut">No documentation.</param>
/// <param name="unkOuterRef">No documentation.</param>
/// <returns>No documentation.</returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCreate']/*"/>
/// <unmanaged>HRESULT DirectSoundCreate([In, Optional] const GUID* pcGuidDevice,[Out] IDirectSound** ppDS,[In] IUnknown* pUnkOuter)</unmanaged>
/// <unmanaged-short>DirectSoundCreate</unmanaged-short>
public static void Create(System.Guid? cGuidDeviceRef, out SharpDX.DirectSound.DirectSoundBase dSOut, SharpDX.ComObject unkOuterRef) {
unsafe {
System.Guid cGuidDeviceRef_;
if (cGuidDeviceRef.HasValue)
cGuidDeviceRef_ = cGuidDeviceRef.Value;
IntPtr dSOut_ = IntPtr.Zero;
SharpDX.Result __result__;
__result__=
DirectSoundCreate_((cGuidDeviceRef.HasValue)?&cGuidDeviceRef_:(void*)IntPtr.Zero, &dSOut_, (void*)((unkOuterRef == null)?IntPtr.Zero:unkOuterRef.NativePointer));
dSOut= (dSOut_ == IntPtr.Zero)?null:new SharpDX.DirectSound.DirectSoundBase(dSOut_);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCreate", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCreate_(void* arg0,void* arg1,void* arg2);
/// <summary>
/// The GetDeviceID function retrieves the unique device identifier of the default playback and capture devices selected by the user in Control Panel.
/// </summary>
/// <param name="guidSrcRef"><dd> Address of a variable that specifies a valid device identifier, or the address of one of the following predefined variables.<table> <tr><th>Value</th><th>Description</th></tr> <tr><td>DSDEVID_DefaultPlayback</td><td>System-wide default audio playback device.</td></tr> <tr><td>DSDEVID_DefaultCapture</td><td>System-wide default audio capture device.</td></tr> <tr><td>DSDEVID_DefaultVoicePlayback</td><td>Default voice playback device.</td></tr> <tr><td>DSDEVID_DefaultVoiceCapture</td><td>Default voice capture device.</td></tr> </table> </dd></param>
/// <param name="guidDestRef"><dd> Address of a variable that receives the unique identifier of the device. </dd></param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.</p></returns>
/// <remarks>
/// <p>If pGuidSrc points to a valid device identifier, the same value is returned in pGuidDest. If pGuidSrc is one of the listed constants, pGuidDest returns the address of the corresponding device <see cref="System.Guid"/>.</p>
/// </remarks>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='GetDeviceID']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.getdeviceid</msdn-id>
/// <unmanaged>HRESULT GetDeviceID([In, Optional] const GUID* pGuidSrc,[Out] GUID* pGuidDest)</unmanaged>
/// <unmanaged-short>GetDeviceID</unmanaged-short>
public static void GetDeviceID(System.Guid? guidSrcRef, out System.Guid guidDestRef) {
unsafe {
System.Guid guidSrcRef_;
if (guidSrcRef.HasValue)
guidSrcRef_ = guidSrcRef.Value;
guidDestRef = new System.Guid();
SharpDX.Result __result__;
fixed (void* guidDestRef_ = &guidDestRef)
__result__=
GetDeviceID_((guidSrcRef.HasValue)?&guidSrcRef_:(void*)IntPtr.Zero, guidDestRef_);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "GetDeviceID", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int GetDeviceID_(void* arg0,void* arg1);
/// <summary>
/// The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.
/// </summary>
/// <param name="dSEnumCallbackRef"><dd> Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system. </dd></param>
/// <param name="contextRef"><dd> Address of the user-defined context passed to the enumeration callback function every time that function is called. </dd></param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.</p></returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCaptureEnumerateA']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundcaptureenumerate</msdn-id>
/// <unmanaged>HRESULT DirectSoundCaptureEnumerateA([In] __function__stdcall* pDSEnumCallback,[In, Optional] void* pContext)</unmanaged>
/// <unmanaged-short>DirectSoundCaptureEnumerateA</unmanaged-short>
public static void CaptureEnumerateA(SharpDX.FunctionCallback dSEnumCallbackRef, System.IntPtr contextRef) {
unsafe {
SharpDX.Result __result__;
__result__=
DirectSoundCaptureEnumerateA_(dSEnumCallbackRef, (void*)contextRef);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCaptureEnumerateA", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCaptureEnumerateA_(void* arg0,void* arg1);
/// <summary>
/// The DirectSoundCaptureEnumerate function enumerates the DirectSoundCapture objects installed in the system.
/// </summary>
/// <param name="dSEnumCallbackRef"><dd> Address of the DSEnumCallback function that will be called for each DirectSoundCapture object installed in the system. </dd></param>
/// <param name="contextRef"><dd> Address of the user-defined context passed to the enumeration callback function every time that function is called. </dd></param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be DSERR_INVALIDPARAM.</p></returns>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCaptureEnumerateW']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundcaptureenumerate</msdn-id>
/// <unmanaged>HRESULT DirectSoundCaptureEnumerateW([In] __function__stdcall* pDSEnumCallback,[In, Optional] void* pContext)</unmanaged>
/// <unmanaged-short>DirectSoundCaptureEnumerateW</unmanaged-short>
public static void CaptureEnumerateW(SharpDX.FunctionCallback dSEnumCallbackRef, System.IntPtr contextRef) {
unsafe {
SharpDX.Result __result__;
__result__=
DirectSoundCaptureEnumerateW_(dSEnumCallbackRef, (void*)contextRef);
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCaptureEnumerateW", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCaptureEnumerateW_(void* arg0,void* arg1);
/// <summary>
/// The DirectSoundCreate8 function creates and initializes an object that supports theIDirectSound8interface.
/// </summary>
/// <param name="cGuidDeviceRef">No documentation.</param>
/// <param name="dS8Out">No documentation.</param>
/// <param name="unkOuterRef">No documentation.</param>
/// <returns><p>If the function succeeds, it returns DS_OK. If it fails, the return value may be one of the following.</p> <table> <tr><th>Return Code</th></tr> <tr><td>DSERR_ALLOCATED</td></tr> <tr><td>DSERR_INVALIDPARAM</td></tr> <tr><td>DSERR_NOAGGREGATION</td></tr> <tr><td>DSERR_NODRIVER</td></tr> <tr><td>DSERR_OUTOFMEMORY</td></tr> </table></returns>
/// <remarks>
/// <p>The application must call the IDirectSound8::SetCooperativeLevel method immediately after creating a device object.</p>
/// </remarks>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='DirectSoundCreate8']/*"/>
/// <msdn-id>microsoft.directx_sdk.reference.directsoundcreate8</msdn-id>
/// <unmanaged>HRESULT DirectSoundCreate8([In, Optional] const GUID* pcGuidDevice,[Out, Fast] IDirectSound8** ppDS8,[In] IUnknown* pUnkOuter)</unmanaged>
/// <unmanaged-short>DirectSoundCreate8</unmanaged-short>
public static void Create8(System.Guid? cGuidDeviceRef, SharpDX.DirectSound.DirectSound dS8Out, SharpDX.ComObject unkOuterRef) {
unsafe {
System.Guid cGuidDeviceRef_;
if (cGuidDeviceRef.HasValue)
cGuidDeviceRef_ = cGuidDeviceRef.Value;
IntPtr dS8Out_ = IntPtr.Zero;
SharpDX.Result __result__;
__result__=
DirectSoundCreate8_((cGuidDeviceRef.HasValue)?&cGuidDeviceRef_:(void*)IntPtr.Zero, &dS8Out_, (void*)((unkOuterRef == null)?IntPtr.Zero:unkOuterRef.NativePointer));
((SharpDX.DirectSound.DirectSound)dS8Out).NativePointer = dS8Out_;
__result__.CheckError();
}
}
[DllImport("dsound.dll", EntryPoint = "DirectSoundCreate8", CallingConvention = CallingConvention.StdCall)]
private unsafe static extern int DirectSoundCreate8_(void* arg0,void* arg1,void* arg2);
}
/// <summary>
/// Functions
/// </summary>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.DirectSound.SoundEffectGuid']/*"/>
static partial class SoundEffectGuid {
/// <summary>Constant StandardFlanger.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_FLANGER</unmanaged>
public static readonly System.Guid StandardFlanger = new System.Guid("efca3d92-dfd8-4672-a603-7420894bad98");
/// <summary>Constant StandardChorus.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_CHORUS</unmanaged>
public static readonly System.Guid StandardChorus = new System.Guid("efe6629c-81f7-4281-bd91-c9d604a95af6");
/// <summary>Constant StandardCompressor.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_COMPRESSOR</unmanaged>
public static readonly System.Guid StandardCompressor = new System.Guid("ef011f79-4000-406d-87af-bffb3fc39d57");
/// <summary>Constant StandardI3DL2REVERB.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_I3DL2REVERB</unmanaged>
public static readonly System.Guid StandardI3DL2REVERB = new System.Guid("ef985e71-d5c7-42d4-ba4d-2d073e2e96f4");
/// <summary>Constant WavesReverb.</summary>
/// <unmanaged>GUID_DSFX_WAVES_REVERB</unmanaged>
public static readonly System.Guid WavesReverb = new System.Guid("87fc0268-9a55-4360-95aa-004a1d9de26c");
/// <summary>Constant StandardGargle.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_GARGLE</unmanaged>
public static readonly System.Guid StandardGargle = new System.Guid("dafd8210-5711-4b91-9fe3-f75b7ae279bf");
/// <summary>Constant StandardEcho.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_ECHO</unmanaged>
public static readonly System.Guid StandardEcho = new System.Guid("ef3e932c-d40b-4f51-8ccf-3f98f1b29d5d");
/// <summary>Constant StandardParameq.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_PARAMEQ</unmanaged>
public static readonly System.Guid StandardParameq = new System.Guid("120ced89-3bf4-4173-a132-3cb406cf3231");
/// <summary>Constant StandardDistortion.</summary>
/// <unmanaged>GUID_DSFX_STANDARD_DISTORTION</unmanaged>
public static readonly System.Guid StandardDistortion = new System.Guid("ef114c90-cd1d-484e-96e5-09cfaf912a21");
}
/// <summary>
/// Functions
/// </summary>
/// <include file='.\..\Documentation\CodeComments.xml' path="/comments/comment[@id='SharpDX.DirectSound.Volume']/*"/>
public static partial class Volume {
/// <summary>Constant Minimum.</summary>
/// <unmanaged>DSBVOLUME_MIN</unmanaged>
public const int Minimum = -0x000002710;
/// <summary>Constant Maximum.</summary>
/// <unmanaged>DSBVOLUME_MAX</unmanaged>
public const int Maximum = 0;
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#if NETCOREAPP
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
using osu.Framework.Logging;
namespace osu.Framework.Testing
{
public class RoslynTypeReferenceBuilder : ITypeReferenceBuilder
{
// The "Attribute" suffix disappears when used via a nuget package, so it is trimmed here.
private static readonly string exclude_attribute_name = nameof(ExcludeFromDynamicCompileAttribute).Replace(nameof(Attribute), string.Empty);
private readonly Logger logger;
private readonly Dictionary<TypeReference, IReadOnlyCollection<TypeReference>> referenceMap = new Dictionary<TypeReference, IReadOnlyCollection<TypeReference>>();
private readonly Dictionary<Project, Compilation> compilationCache = new Dictionary<Project, Compilation>();
private readonly Dictionary<SyntaxTree, SemanticModel> semanticModelCache = new Dictionary<SyntaxTree, SemanticModel>();
private readonly Dictionary<TypeReference, bool> typeInheritsFromGameCache = new Dictionary<TypeReference, bool>();
private Solution solution;
public RoslynTypeReferenceBuilder()
{
logger = Logger.GetLogger("dynamic-compilation");
logger.OutputToListeners = false;
}
public async Task Initialise(string solutionFile)
{
MSBuildLocator.RegisterDefaults();
solution = await MSBuildWorkspace.Create().OpenSolutionAsync(solutionFile);
}
public async Task<IReadOnlyCollection<string>> GetReferencedFiles(Type testType, string changedFile)
{
clearCaches();
updateFile(changedFile);
await buildReferenceMapAsync(testType, changedFile);
var directedGraph = getDirectedGraph();
return getReferencedFiles(getTypesFromFile(changedFile), directedGraph);
}
public async Task<IReadOnlyCollection<string>> GetReferencedAssemblies(Type testType, string changedFile) => await Task.Run(() =>
{
// Todo: This is temporary, and is potentially missing assemblies.
var assemblies = new HashSet<string>();
foreach (var ass in AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic))
assemblies.Add(ass.Location);
assemblies.Add(typeof(JetBrains.Annotations.NotNullAttribute).Assembly.Location);
return assemblies;
});
public void Reset()
{
clearCaches();
referenceMap.Clear();
}
/// <summary>
/// Builds the reference map, connecting all types to their immediate references. Results are placed inside <see cref="referenceMap"/>.
/// </summary>
/// <param name="testType">The test target - the top-most level.</param>
/// <param name="changedFile">The file that was changed.</param>
/// <exception cref="InvalidOperationException">If <paramref name="testType"/> could not be retrieved from the solution.</exception>
private async Task buildReferenceMapAsync(Type testType, string changedFile)
{
// We want to find a graph of types from the testType symbol (P) to all the types which it references recursively.
//
// P
// / \
// / \
// / \
// C1 C2 ---
// / \ | /
// C3 C4 C5 /
// \ / /
// C6 ---
//
// The reference map is a key-value pairing of all types to their immediate references. A directed graph can be built by traversing through types.
//
// P -> { C1, C2 }
// C1 -> { C3, C4 }
// C2 -> { C5, C6 }
// C3 -> { }
// C4 -> { C6 }
// C5 -> { C6 }
// C6 -> { C2 }
logger.Add("Building reference map...");
var compiledTestProject = await compileProjectAsync(findTestProject());
var compiledTestType = compiledTestProject.GetTypeByMetadataName(testType.FullName);
if (compiledTestType == null)
throw new InvalidOperationException("Failed to retrieve test type from the solution.");
if (referenceMap.Count > 0)
{
logger.Add("Attempting to use cache...");
// We already have some references, so we can do a partial re-process of the map for only the changed file.
var oldTypes = getTypesFromFile(changedFile).ToArray();
foreach (var t in oldTypes)
{
referenceMap.Remove(t);
typeInheritsFromGameCache.Remove(t);
}
foreach (var t in oldTypes)
{
string typePath = t.Symbol.Locations.First().SourceTree?.FilePath;
// The type we have is on an old compilation, we need to re-retrieve it on the new one.
var project = getProjectFromFile(typePath);
if (project == null)
{
logger.Add("File has been renamed. Rebuilding reference map from scratch...");
Reset();
break;
}
var compilation = await compileProjectAsync(project);
var syntaxTree = compilation.SyntaxTrees.First(tree => tree.FilePath == typePath);
var semanticModel = await getSemanticModelAsync(syntaxTree);
var referencedTypes = await getReferencedTypesAsync(semanticModel);
referenceMap[TypeReference.FromSymbol(t.Symbol)] = referencedTypes;
foreach (var referenced in referencedTypes)
await buildReferenceMapRecursiveAsync(referenced);
}
}
if (referenceMap.Count == 0)
{
// We have no cache available, so we must rebuild the whole map.
await buildReferenceMapRecursiveAsync(TypeReference.FromSymbol(compiledTestType));
}
}
/// <summary>
/// Builds the reference map starting from a root type reference, connecting all types to their immediate references. Results are placed inside <see cref="referenceMap"/>.
/// </summary>
/// <remarks>
/// This should not be used by itself. Use <see cref="buildReferenceMapAsync"/> instead.
/// </remarks>
/// <param name="rootReference">The root, where the map should start being build from.</param>
private async Task buildReferenceMapRecursiveAsync(TypeReference rootReference)
{
var searchQueue = new Queue<TypeReference>();
searchQueue.Enqueue(rootReference);
while (searchQueue.Count > 0)
{
var toCheck = searchQueue.Dequeue();
var referencedTypes = await getReferencedTypesAsync(toCheck);
referenceMap[toCheck] = referencedTypes;
foreach (var referenced in referencedTypes)
{
// We don't want to cycle over types that have already been explored.
if (!referenceMap.ContainsKey(referenced))
{
// Used for de-duping, so it must be added to the dictionary immediately.
referenceMap[referenced] = null;
searchQueue.Enqueue(referenced);
}
}
}
}
/// <summary>
/// Retrieves all <see cref="TypeReference"/>s referenced by a given <see cref="TypeReference"/>, across all symbol sources.
/// </summary>
/// <param name="typeReference">The target <see cref="TypeReference"/>.</param>
/// <returns>All <see cref="TypeReference"/>s referenced to across all symbol sources by <paramref name="typeReference"/>.</returns>
private async Task<HashSet<TypeReference>> getReferencedTypesAsync(TypeReference typeReference)
{
var result = new HashSet<TypeReference>();
foreach (var reference in typeReference.Symbol.DeclaringSyntaxReferences)
{
foreach (var type in await getReferencedTypesAsync(await getSemanticModelAsync(reference.SyntaxTree)))
result.Add(type);
}
return result;
}
/// <summary>
/// Retrieves all <see cref="TypeReference"/>s referenced by a given <see cref="SemanticModel"/>.
/// </summary>
/// <param name="semanticModel">The target <see cref="SemanticModel"/>.</param>
/// <returns>All <see cref="TypeReference"/>s referenced by <paramref name="semanticModel"/>.</returns>
private async Task<HashSet<TypeReference>> getReferencedTypesAsync(SemanticModel semanticModel)
{
var result = new HashSet<TypeReference>();
var root = await semanticModel.SyntaxTree.GetRootAsync();
var descendantNodes = root.DescendantNodes(n =>
{
var kind = n.Kind();
return kind != SyntaxKind.UsingDirective
&& kind != SyntaxKind.NamespaceKeyword;
});
// Find all the named type symbols in the syntax tree, and mark + recursively iterate through them.
foreach (var node in descendantNodes)
{
switch (node.Kind())
{
case SyntaxKind.GenericName:
case SyntaxKind.IdentifierName:
{
if (semanticModel.GetSymbolInfo(node).Symbol is INamedTypeSymbol t)
addTypeSymbol(t);
break;
}
case SyntaxKind.AsExpression:
case SyntaxKind.IsExpression:
case SyntaxKind.SizeOfExpression:
case SyntaxKind.TypeOfExpression:
case SyntaxKind.CastExpression:
case SyntaxKind.ObjectCreationExpression:
{
if (semanticModel.GetTypeInfo(node).Type is INamedTypeSymbol t)
addTypeSymbol(t);
break;
}
}
}
return result;
void addTypeSymbol(INamedTypeSymbol typeSymbol)
{
// Exclude types marked with the [ExcludeFromDynamicCompile] attribute
if (typeSymbol.GetAttributes().Any(attrib => attrib.AttributeClass.Name.Contains(exclude_attribute_name)))
{
logger.Add($"Type {typeSymbol.Name} referenced but marked for exclusion.");
return;
}
var reference = TypeReference.FromSymbol(typeSymbol);
if (typeInheritsFromGame(reference))
{
logger.Add($"Type {typeSymbol.Name} inherits from game and is marked for exclusion.");
return;
}
result.Add(reference);
}
}
/// <summary>
/// Traverses <see cref="referenceMap"/> to build a directed graph of <see cref="DirectedTypeNode"/> joined by their parents.
/// </summary>
/// <returns>A dictionary containing the directed graph from each <see cref="TypeReference"/> in <see cref="referenceMap"/>.</returns>
private Dictionary<TypeReference, DirectedTypeNode> getDirectedGraph()
{
// Given the reference map (from above):
//
// P -> { C1, C2 }
// C1 -> { C3, C4 }
// C2 -> { C5, C6 }
// C3 -> { }
// C4 -> { C6 }
// C5 -> { C6 }
// C6 -> { C2 }
//
// The respective directed graph is built by traversing upwards and finding all incoming references at each type, such that:
//
// P -> { }
// C1 -> { P }
// C2 -> { C6, P, C5, C4, C2, C1 }
// C3 -> { C1, P }
// C4 -> { C1, P }
// C5 -> { C2, P }
// C6 -> { C5, C4, C2, C1, C6, P }
//
// The directed graph may contain cycles where multiple paths lead to the same node (e.g. C2, C6).
logger.Add("Retrieving reference graph...");
var result = new Dictionary<TypeReference, DirectedTypeNode>();
// Traverse through the reference map and assign parents to all children referenced types.
foreach (var kvp in referenceMap)
{
var parentNode = getNode(kvp.Key);
foreach (var typeRef in kvp.Value)
getNode(typeRef).Parents.Add(parentNode);
}
return result;
DirectedTypeNode getNode(TypeReference typeSymbol)
{
if (!result.TryGetValue(typeSymbol, out var existing))
result[typeSymbol] = existing = new DirectedTypeNode(typeSymbol);
return existing;
}
}
/// <summary>
/// Traverses a directed graph to find all direct and indirect references to a set of <see cref="TypeReference"/>s. References are returned as file names.
/// </summary>
/// <param name="sources">The <see cref="TypeReference"/>s to search from.</param>
/// <param name="directedGraph">The directed graph generated through <see cref="getDirectedGraph"/>.</param>
/// <returns>All files containing direct or indirect references to the given <paramref name="sources"/>.</returns>
private HashSet<string> getReferencedFiles(IEnumerable<TypeReference> sources, IReadOnlyDictionary<TypeReference, DirectedTypeNode> directedGraph)
{
logger.Add("Retrieving referenced files...");
var result = new HashSet<string>();
foreach (var s in sources)
getReferencedFilesRecursive(directedGraph[s], result);
return result;
}
private void getReferencedFilesRecursive(DirectedTypeNode node, HashSet<string> result, HashSet<DirectedTypeNode> seenTypes = null, int level = 0)
{
// A '.' is prepended since the logger trims lines.
logger.Add($"{(level > 0 ? $".{new string(' ', level * 2 - 1)}| " : string.Empty)} {node}");
seenTypes ??= new HashSet<DirectedTypeNode>();
if (seenTypes.Contains(node))
return;
seenTypes.Add(node);
// Add all the current type's locations to the resulting set.
foreach (var location in node.Reference.Symbol.Locations)
{
var syntaxTree = location.SourceTree;
if (syntaxTree != null)
result.Add(syntaxTree.FilePath);
}
// Follow through the process for all parents.
foreach (var p in node.Parents)
getReferencedFilesRecursive(p, result, seenTypes, level + 1);
}
private bool typeInheritsFromGame(TypeReference reference)
{
if (typeInheritsFromGameCache.TryGetValue(reference, out var existing))
return existing;
// When used via a nuget package, the local type name seems to always be more qualified than the symbol's type name.
// E.g. Type name: osu.Framework.Game, symbol name: Framework.Game.
if (typeof(Game).FullName?.Contains(reference.Symbol.ToString()) == true)
return typeInheritsFromGameCache[reference] = true;
if (reference.Symbol.BaseType == null)
return typeInheritsFromGameCache[reference] = false;
return typeInheritsFromGameCache[reference] = typeInheritsFromGame(TypeReference.FromSymbol(reference.Symbol.BaseType));
}
/// <summary>
/// Finds all the <see cref="TypeReference"/>s which list a given filename as any of their sources.
/// </summary>
/// <param name="fileName">The target filename.</param>
/// <returns>All <see cref="TypeReference"/>s with <paramref name="fileName"/> listed as one of their symbol locations.</returns>
private IEnumerable<TypeReference> getTypesFromFile(string fileName) => referenceMap
.Select(kvp => kvp.Key)
.Where(t => t.Symbol.Locations.Any(l => l.SourceTree?.FilePath == fileName));
/// <summary>
/// Compiles a <see cref="Project"/>.
/// </summary>
/// <param name="project">The <see cref="Project"/> to compile.</param>
/// <returns>The resulting <see cref="Compilation"/>.</returns>
private async Task<Compilation> compileProjectAsync(Project project)
{
if (compilationCache.TryGetValue(project, out var existing))
return existing;
logger.Add($"Compiling project {project.Name}...");
return compilationCache[project] = await project.GetCompilationAsync();
}
/// <summary>
/// Retrieves a <see cref="SemanticModel"/> from a given <see cref="SyntaxTree"/>.
/// </summary>
/// <param name="syntaxTree">The target <see cref="SyntaxTree"/>.</param>
/// <returns>The corresponding <see cref="SemanticModel"/>.</returns>
private async Task<SemanticModel> getSemanticModelAsync(SyntaxTree syntaxTree)
{
if (semanticModelCache.TryGetValue(syntaxTree, out var existing))
return existing;
return semanticModelCache[syntaxTree] = (await compileProjectAsync(getProjectFromFile(syntaxTree.FilePath))).GetSemanticModel(syntaxTree, true);
}
/// <summary>
/// Retrieves the <see cref="Project"/> which contains a given filename as a document.
/// </summary>
/// <param name="fileName">The target filename.</param>
/// <returns>The <see cref="Project"/> that contains <paramref name="fileName"/>.</returns>
private Project getProjectFromFile(string fileName) => solution.Projects.FirstOrDefault(p => p.Documents.Any(d => d.FilePath == fileName));
/// <summary>
/// Retrieves the project which contains the currently-executing test.
/// </summary>
/// <returns>The <see cref="Project"/> containing the currently-executing test.</returns>
private Project findTestProject()
{
var executingAssembly = Assembly.GetEntryAssembly()?.GetName().Name;
return solution.Projects.FirstOrDefault(p => p.AssemblyName == executingAssembly);
}
private void clearCaches()
{
compilationCache.Clear();
semanticModelCache.Clear();
}
/// <summary>
/// Updates a file in the solution with its new on-disk contents.
/// </summary>
/// <param name="fileName">The file to update.</param>
private void updateFile(string fileName)
{
logger.Add($"Updating file {fileName} in solution...");
var changedDoc = solution.GetDocumentIdsWithFilePath(fileName)[0];
solution = solution.WithDocumentText(changedDoc, SourceText.From(File.ReadAllText(fileName)));
}
/// <summary>
/// Wraps a <see cref="INamedTypeSymbol"/> for stable inter-<see cref="Compilation"/> hashcode and equality comparisons.
/// </summary>
private readonly struct TypeReference : IEquatable<TypeReference>
{
public readonly INamedTypeSymbol Symbol;
public TypeReference(INamedTypeSymbol symbol)
{
Symbol = symbol;
}
public bool Equals(TypeReference other)
=> Symbol.ContainingNamespace.ToString() == other.Symbol.ContainingNamespace.ToString()
&& Symbol.ToString() == other.Symbol.ToString();
public override int GetHashCode()
{
var hash = new HashCode();
hash.Add(Symbol.ToString(), StringComparer.Ordinal);
return hash.ToHashCode();
}
public override string ToString() => Symbol.ToString();
public static TypeReference FromSymbol(INamedTypeSymbol symbol) => new TypeReference(symbol);
}
/// <summary>
/// A single node in the directed graph of <see cref="TypeReference"/>s, linked upwards by its parenting <see cref="DirectedTypeNode"/>.
/// </summary>
private class DirectedTypeNode : IEquatable<DirectedTypeNode>
{
public readonly TypeReference Reference;
public readonly List<DirectedTypeNode> Parents = new List<DirectedTypeNode>();
public DirectedTypeNode(TypeReference reference)
{
Reference = reference;
}
public bool Equals(DirectedTypeNode other)
=> other != null
&& Reference.Equals(other.Reference);
public override int GetHashCode() => Reference.GetHashCode();
public override string ToString() => Reference.ToString();
}
}
}
#endif
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.AspNetCore.SignalR.Configuration;
using Microsoft.AspNetCore.SignalR.Infrastructure;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Microsoft.AspNetCore.SignalR.Transports
{
/// <summary>
/// Default implementation of <see cref="ITransportHeartbeat"/>.
/// </summary>
public class TransportHeartbeat : ITransportHeartbeat, IDisposable
{
private readonly ConcurrentDictionary<string, ConnectionMetadata> _connections = new ConcurrentDictionary<string, ConnectionMetadata>();
private readonly Timer _timer;
private readonly TransportOptions _transportOptions;
private readonly ILogger _logger;
private readonly IPerformanceCounterManager _counters;
private readonly object _counterLock = new object();
private int _running;
private ulong _heartbeatCount;
/// <summary>
/// Initializes and instance of the <see cref="TransportHeartbeat"/> class.
/// </summary>
/// <param name="serviceProvider">The <see cref="IDependencyResolver"/>.</param>
public TransportHeartbeat(IOptions<SignalROptions> optionsAccessor,
IPerformanceCounterManager counters,
ILoggerFactory loggerFactory)
{
_transportOptions = optionsAccessor.Value.Transports;
_counters = counters;
_logger = loggerFactory.CreateLogger<TransportHeartbeat>();
// REVIEW: When to dispose the timer?
_timer = new Timer(Beat,
null,
_transportOptions.HeartbeatInterval(),
_transportOptions.HeartbeatInterval());
}
private ILogger Logger
{
get
{
return _logger;
}
}
/// <summary>
/// Adds a new connection to the list of tracked connections.
/// </summary>
/// <param name="connection">The connection to be added.</param>
public ITrackingConnection AddOrUpdateConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
var newMetadata = new ConnectionMetadata(connection);
bool isNewConnection = true;
ITrackingConnection oldConnection = null;
_connections.AddOrUpdate(connection.ConnectionId, newMetadata, (key, old) =>
{
Logger.LogDebug(String.Format("Connection {0} exists. Closing previous connection.", old.Connection.ConnectionId));
// Kick out the older connection. This should only happen when
// a previous connection attempt fails on the client side (e.g. transport fallback).
old.Connection.ApplyState(TransportConnectionStates.Replaced);
// Don't bother disposing the registration here since the token source
// gets disposed after the request has ended
old.Connection.End();
// If we have old metadata this isn't a new connection
isNewConnection = false;
oldConnection = old.Connection;
return newMetadata;
});
if (isNewConnection)
{
Logger.LogInformation(String.Format("Connection {0} is New.", connection.ConnectionId));
connection.IncrementConnectionsCount();
}
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
// Set the initial connection time
newMetadata.Initial = DateTime.UtcNow;
newMetadata.Connection.ApplyState(TransportConnectionStates.Added);
return oldConnection;
}
/// <summary>
/// Removes a connection from the list of tracked connections.
/// </summary>
/// <param name="connection">The connection to remove.</param>
public void RemoveConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
// Remove the connection and associated metadata
ConnectionMetadata metadata;
if (_connections.TryRemove(connection.ConnectionId, out metadata))
{
connection.DecrementConnectionsCount();
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
connection.ApplyState(TransportConnectionStates.Removed);
Logger.LogInformation(String.Format("Removing connection {0}", connection.ConnectionId));
}
}
/// <summary>
/// Marks an existing connection as active.
/// </summary>
/// <param name="connection">The connection to mark.</param>
public void MarkConnection(ITrackingConnection connection)
{
if (connection == null)
{
throw new ArgumentNullException("connection");
}
// Do nothing if the connection isn't alive
if (!connection.IsAlive)
{
return;
}
ConnectionMetadata metadata;
if (_connections.TryGetValue(connection.ConnectionId, out metadata))
{
metadata.LastMarked = DateTime.UtcNow;
}
}
public IList<ITrackingConnection> GetConnections()
{
return _connections.Values.Select(metadata => metadata.Connection).ToList();
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We're tracing exceptions and don't want to crash the process.")]
private void Beat(object state)
{
if (Interlocked.Exchange(ref _running, 1) == 1)
{
Logger.LogDebug("Timer handler took longer than current interval");
return;
}
lock (_counterLock)
{
_counters.ConnectionsCurrent.RawValue = _connections.Count;
}
try
{
_heartbeatCount++;
foreach (var metadata in _connections.Values)
{
if (metadata.Connection.IsAlive)
{
CheckTimeoutAndKeepAlive(metadata);
}
else
{
Logger.LogDebug(metadata.Connection.ConnectionId + " is dead");
// Check if we need to disconnect this connection
CheckDisconnect(metadata);
}
}
}
catch (Exception ex)
{
Logger.LogError("SignalR error during transport heart beat on background thread: {0}", ex);
}
finally
{
Interlocked.Exchange(ref _running, 0);
}
}
private void CheckTimeoutAndKeepAlive(ConnectionMetadata metadata)
{
if (RaiseTimeout(metadata))
{
// If we're past the expiration time then just timeout the connection
metadata.Connection.Timeout();
}
else
{
// The connection is still alive so we need to keep it alive with a server side "ping".
// This is for scenarios where networking hardware (proxies, loadbalancers) get in the way
// of us handling timeout's or disconnects gracefully
if (RaiseKeepAlive(metadata))
{
Logger.LogDebug("KeepAlive(" + metadata.Connection.ConnectionId + ")");
// Ensure delegate continues to use the C# Compiler static delegate caching optimization.
metadata.Connection.KeepAlive().Catch((ex, state) => OnKeepAliveError(ex, state), state: Logger, logger: Logger);
}
MarkConnection(metadata.Connection);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We're tracing exceptions and don't want to crash the process.")]
private void CheckDisconnect(ConnectionMetadata metadata)
{
try
{
if (RaiseDisconnect(metadata))
{
// Remove the connection from the list
RemoveConnection(metadata.Connection);
// Fire disconnect on the connection
metadata.Connection.Disconnect();
}
}
catch (Exception ex)
{
// Swallow exceptions that might happen during disconnect
Logger.LogError(String.Format("Raising Disconnect failed: {0}", ex));
}
}
private bool RaiseDisconnect(ConnectionMetadata metadata)
{
// The transport is currently dead but it could just be reconnecting
// so we to check it's last active time to see if it's over the disconnect
// threshold
TimeSpan elapsed = DateTime.UtcNow - metadata.LastMarked;
// The threshold for disconnect is the transport threshold + (potential network issues)
var threshold = metadata.Connection.DisconnectThreshold + _transportOptions.DisconnectTimeout;
return elapsed >= threshold;
}
private bool RaiseKeepAlive(ConnectionMetadata metadata)
{
var keepAlive = _transportOptions.KeepAlive;
// Don't raise keep alive if it's set to 0 or the transport doesn't support
// keep alive
if (keepAlive == null || !metadata.Connection.SupportsKeepAlive)
{
return false;
}
// Raise keep alive if the keep alive value has passed
return _heartbeatCount % (ulong)TransportOptionsExtensions.HeartBeatsPerKeepAlive == 0;
}
private bool RaiseTimeout(ConnectionMetadata metadata)
{
// The connection already timed out so do nothing
if (metadata.Connection.IsTimedOut)
{
return false;
}
// If keep alives are enabled and the transport doesn't require timeouts,
// i.e. anything but long-polling, don't ever timeout.
var keepAlive = _transportOptions.KeepAlive;
if (keepAlive != null && !metadata.Connection.RequiresTimeout)
{
return false;
}
TimeSpan elapsed = DateTime.UtcNow - metadata.Initial;
// Only raise timeout if we're past the configured connection timeout.
return elapsed >= _transportOptions.LongPolling.PollTimeout;
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_timer != null)
{
_timer.Dispose();
}
Logger.LogInformation("Dispose(). Closing all connections");
// Kill all connections
foreach (var pair in _connections)
{
ConnectionMetadata metadata;
if (_connections.TryGetValue(pair.Key, out metadata))
{
metadata.Connection.End();
}
}
}
}
public void Dispose()
{
Dispose(true);
}
private static void OnKeepAliveError(AggregateException ex, object state)
{
((ILogger)state).LogError("Failed to send keep alive: " + ex.GetBaseException());
}
private class ConnectionMetadata
{
public ConnectionMetadata(ITrackingConnection connection)
{
Connection = connection;
Initial = DateTime.UtcNow;
LastMarked = DateTime.UtcNow;
}
// The connection instance
public ITrackingConnection Connection { get; set; }
// The last time the connection had any activity
public DateTime LastMarked { get; set; }
// The initial connection time of the connection
public DateTime Initial { get; set; }
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="SerializationTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.ComponentModel;
using System.Diagnostics;
using Csla.Serialization;
using Csla.Test.ValidationRules;
using UnitDriven;
#if NUNIT
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#else
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Csla.Serialization.Mobile;
using System.IO;
#endif
namespace Csla.Test.Serialization
{
[TestClass()]
public class SerializationTests : TestBase
{
[Serializable]
private class TestCollection : BusinessBindingListBase<TestCollection, TestItem>
{
}
[Serializable]
private class TestItem : BusinessBase<TestItem>
{
protected override object GetIdValue()
{
return 0;
}
public TestItem()
{
MarkAsChild();
}
}
[TestMethod]
public void SerializeDataPortalException()
{
var obj = new Csla.Server.DataPortalException("test message", new Exception("inner message"), null);
var obj2 = (Csla.Server.DataPortalException)Csla.Core.ObjectCloner.Clone(obj);
Assert.IsFalse(ReferenceEquals(obj, obj2));
Assert.AreEqual(obj.Message, obj2.Message);
}
[TestMethod()]
public void TestWithoutSerializableHandler()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
SerializationRoot root = new SerializationRoot();
nonSerializableEventHandler handler = new nonSerializableEventHandler();
handler.Reg(root);
root.Data = "something";
context.Assert.AreEqual(1, Csla.ApplicationContext.GlobalContext["PropertyChangedFiredCount"]);
root.Data = "something else";
context.Assert.AreEqual(2, Csla.ApplicationContext.GlobalContext["PropertyChangedFiredCount"]);
//serialize an object with eventhandling objects that are nonserializable
root = root.Clone();
root.Data = "something new";
//still at 2 even though we changed the property again
//when the clone method performs serialization, the nonserializable
//object containing an event handler for the propertyChanged event
//is lost
context.Assert.AreEqual(2, Csla.ApplicationContext.GlobalContext["PropertyChangedFiredCount"]);
context.Assert.Success();
}
[TestMethod()]
public void Clone()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
SerializationRoot root = new SerializationRoot();
root = (SerializationRoot)root.Clone();
context.Assert.AreEqual(
true,
Csla.ApplicationContext.GlobalContext["Deserialized"],
"Deserialized not called");
context.Assert.Success();
}
[TestMethod()]
public void SerializableEvents()
{
Csla.ApplicationContext.GlobalContext.Clear();
UnitTestContext context = GetContext();
SerializationRoot root = new SerializationRoot();
TestEventSink handler = new TestEventSink();
root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler
(OnIsDirtyChanged);
root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler
(StaticOnIsDirtyChanged);
root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler
(PublicStaticOnIsDirtyChanged);
root.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler
(OnIsDirtyChanged); //will call this method twice since it is assigned twice
handler.Reg(root);
root.Data = "abc";
context.Assert.AreEqual("abc", root.Data, "Data value not set");
context.Assert.AreEqual(
"OnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["OnIsDirtyChanged"],
"Didn't call local handler");
context.Assert.AreEqual(
"StaticOnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["StaticOnIsDirtyChanged"],
"Didn't call static handler");
Assert.AreEqual(
"PublicStaticOnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["PublicStaticOnIsDirtyChanged"],
"Didn't call public static handler");
Assert.AreEqual(
"Test.OnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["Test.OnIsDirtyChanged"],
"Didn't call serializable handler");
Assert.AreEqual(
"Test.PrivateOnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["Test.PrivateOnIsDirtyChanged"],
"Didn't call serializable private handler");
root = (SerializationRoot)root.Clone();
Csla.ApplicationContext.GlobalContext.Clear();
root.Data = "xyz";
context.Assert.AreEqual("xyz", root.Data, "Data value not set");
context.Assert.AreEqual(null, Csla.ApplicationContext.GlobalContext["OnIsDirtyChanged"],
"Called local handler after clone");
context.Assert.AreEqual(null, Csla.ApplicationContext.GlobalContext["StaticOnIsDirtyChanged"],
"Called static handler after clone");
context.Assert.AreEqual(
"PublicStaticOnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["PublicStaticOnIsDirtyChanged"],
"Didn't call public static handler after clone");
context.Assert.AreEqual(
"Test.OnIsDirtyChanged",
Csla.ApplicationContext.GlobalContext["Test.OnIsDirtyChanged"],
"Didn't call serializable handler after clone");
context.Assert.AreEqual(null, Csla.ApplicationContext.GlobalContext["Test.PrivateOnIsDirtyChanged"],
"Called serializable private handler after clone");
context.Assert.Success();
}
[TestMethod()]
public void TestSerializableEventsActionFails()
{
var root = new SerializationRoot();
var nonSerClass = new NonSerializedClass();
Action<object, PropertyChangedEventArgs> h = (sender, eventArgs) => { nonSerClass.Do(); };
var method = typeof (Action<object, PropertyChangedEventArgs>).GetMethod("Invoke");
var delgate = (PropertyChangedEventHandler)(object)method.CreateDelegate(typeof (PropertyChangedEventHandler), h);
root.PropertyChanged += delgate;
var b = new BinaryFormatterWrapper();
try
{
b.Serialize(new MemoryStream(), root);
Assert.Fail("Serialization should have thrown an exception");
}
catch (System.Runtime.Serialization.SerializationException ex)
{
// serialization failed as expected
}
}
[TestMethod()]
public void TestSerializableEventsActionSucceeds()
{
var root = new OverrideSerializationRoot();
var nonSerClass = new NonSerializedClass();
Action<object, PropertyChangedEventArgs> h = (sender, eventArgs) => { nonSerClass.Do(); };
var method = typeof (Action<object, PropertyChangedEventArgs>).GetMethod("Invoke");
var delgate = (PropertyChangedEventHandler)(object)method.CreateDelegate(typeof (PropertyChangedEventHandler), h);
root.PropertyChanged += delgate;
Action<object, PropertyChangingEventArgs> h1 = (sender, eventArgs) => { nonSerClass.Do(); };
var method1 = typeof(Action<object, PropertyChangingEventArgs>).GetMethod("Invoke");
var delgate1 = (PropertyChangingEventHandler)(object)method1.CreateDelegate(typeof(PropertyChangingEventHandler), h1);
root.PropertyChanging += delgate1;
var b = new BinaryFormatterWrapper();
b.Serialize(new MemoryStream(), root);
}
[TestMethod()]
public void TestValidationRulesAfterSerialization()
{
UnitTestContext context = GetContext();
HasRulesManager.NewHasRulesManager((o, e) =>
{
HasRulesManager root = e.Object;
root.Name = "";
context.Assert.AreEqual(false, root.IsValid, "root should not start valid");
root = root.Clone();
context.Assert.AreEqual(false, root.IsValid, "root should not be valid after clone");
root.Name = "something";
context.Assert.AreEqual(true, root.IsValid, "root should be valid after property set");
root = root.Clone();
context.Assert.AreEqual(true, root.IsValid, "root should be valid after second clone");
context.Assert.Success();
});
context.Complete();
}
[TestMethod()]
public void TestSerializationCslaBinaryReaderWriterList()
{
var test = new BinaryReaderWriterTestClassList();
BinaryReaderWriterTestClassList result;
test.Setup();
var serialized = MobileFormatter.SerializeToDTO(test);
CslaBinaryWriter writer = new CslaBinaryWriter();
byte[] data;
using (var stream = new MemoryStream())
{
writer.Write(stream, serialized);
data = stream.ToArray();
}
CslaBinaryReader reader = new CslaBinaryReader();
using (var stream = new MemoryStream(data))
{
var deserialized = reader.Read(stream);
result = (BinaryReaderWriterTestClassList)MobileFormatter.DeserializeFromDTO(deserialized);
}
Assert.AreEqual(test.Count, result.Count);
for (int i = 0; i < test.Count; i++)
{
Assert.AreEqual(test[i].CharTest, result[i].CharTest);
Assert.AreEqual(test[i].DateTimeOffsetTest, result[i].DateTimeOffsetTest);
Assert.AreEqual(test[i].DateTimeTest, result[i].DateTimeTest);
Assert.AreEqual(test[i].DecimalTest, result[i].DecimalTest);
Assert.AreEqual(test[i].DoubleTest, result[i].DoubleTest);
Assert.AreEqual(test[i].EnumTest, result[i].EnumTest);
Assert.AreEqual(test[i].GuidTest, result[i].GuidTest);
Assert.AreEqual(test[i].Int16Test, result[i].Int16Test);
Assert.AreEqual(test[i].Int32Test, result[i].Int32Test);
Assert.AreEqual(test[i].Int64Test, result[i].Int64Test);
Assert.AreEqual(test[i].SByteTest, result[i].SByteTest);
Assert.AreEqual(test[i].SingleTest, result[i].SingleTest);
Assert.AreEqual(test[i].StringTest, result[i].StringTest);
Assert.AreEqual(test[i].TimeSpanTest, result[i].TimeSpanTest);
Assert.AreEqual(test[i].UInt16Test, result[i].UInt16Test);
Assert.AreEqual(test[i].UInt32Test, result[i].UInt32Test);
Assert.AreEqual(test[i].UInt64Test, result[i].UInt64Test);
Assert.AreEqual(test[i].EmptySmartDateTest, result[i].EmptySmartDateTest);
Assert.AreEqual(test[i].EmptySmartDateTest.FormatString, result[i].EmptySmartDateTest.FormatString);
Assert.AreEqual(test[i].EmptySmartDateTest.EmptyIsMin, result[i].EmptySmartDateTest.EmptyIsMin);
Assert.AreEqual(test[i].EmptySmartDateTest.IsEmpty, result[i].EmptySmartDateTest.IsEmpty);
Assert.AreEqual(test[i].EmptySmartDateTest.Date, result[i].EmptySmartDateTest.Date);
Assert.AreEqual(test[i].FilledSmartDateTest, result[i].FilledSmartDateTest);
Assert.AreEqual(test[i].FilledSmartDateTest.FormatString, result[i].FilledSmartDateTest.FormatString);
Assert.AreEqual(test[i].FilledSmartDateTest.EmptyIsMin, result[i].FilledSmartDateTest.EmptyIsMin);
Assert.AreEqual(test[i].FilledSmartDateTest.IsEmpty, result[i].FilledSmartDateTest.IsEmpty);
Assert.AreEqual(test[i].FilledSmartDateTest.Date, result[i].FilledSmartDateTest.Date);
}
}
[TestMethod()]
public void TestSerializationCslaBinaryReaderWriter()
{
var test = new BinaryReaderWriterTestClass();
BinaryReaderWriterTestClass result;
test.Setup();
var serialized = MobileFormatter.SerializeToDTO(test);
CslaBinaryWriter writer = new CslaBinaryWriter();
byte[] data;
using (var stream = new MemoryStream())
{
writer.Write(stream, serialized);
data = stream.ToArray();
}
CslaBinaryReader reader = new CslaBinaryReader();
using (var stream = new MemoryStream(data))
{
var deserialized = reader.Read(stream);
result = (BinaryReaderWriterTestClass)MobileFormatter.DeserializeFromDTO(deserialized);
}
Assert.AreEqual(test.BoolTest, result.BoolTest);
Assert.AreEqual(test.ByteArrayTest.Length, result.ByteArrayTest.Length);
for (int i = 0; i < test.ByteArrayTest.Length; i++)
{
Assert.AreEqual(test.ByteArrayTest[i], result.ByteArrayTest[i]);
}
Assert.AreEqual(test.ByteTest, result.ByteTest);
Assert.AreEqual(test.CharArrayTest.Length, result.CharArrayTest.Length);
for (int i = 0; i < test.CharArrayTest.Length; i++)
{
Assert.AreEqual(test.CharArrayTest[i], result.CharArrayTest[i]);
}
Assert.AreEqual(test.CharTest, result.CharTest);
Assert.AreEqual(test.DateTimeOffsetTest, result.DateTimeOffsetTest);
Assert.AreEqual(test.DateTimeTest, result.DateTimeTest);
Assert.AreEqual(test.DecimalTest, result.DecimalTest);
Assert.AreEqual(test.DoubleTest, result.DoubleTest);
Assert.AreEqual(test.EnumTest, result.EnumTest);
Assert.AreEqual(test.GuidTest, result.GuidTest);
Assert.AreEqual(test.Int16Test, result.Int16Test);
Assert.AreEqual(test.Int32Test, result.Int32Test);
Assert.AreEqual(test.Int64Test, result.Int64Test);
Assert.AreEqual(test.SByteTest, result.SByteTest);
Assert.AreEqual(test.SingleTest, result.SingleTest);
Assert.AreEqual(test.StringTest, result.StringTest);
Assert.AreEqual(test.TimeSpanTest, result.TimeSpanTest);
Assert.AreEqual(test.UInt16Test, result.UInt16Test);
Assert.AreEqual(test.UInt32Test, result.UInt32Test);
Assert.AreEqual(test.UInt64Test, result.UInt64Test);
Assert.AreEqual(test.EmptySmartDateTest, result.EmptySmartDateTest);
Assert.AreEqual(test.EmptySmartDateTest.FormatString, result.EmptySmartDateTest.FormatString);
Assert.AreEqual(test.EmptySmartDateTest.EmptyIsMin, result.EmptySmartDateTest.EmptyIsMin);
Assert.AreEqual(test.EmptySmartDateTest.IsEmpty, result.EmptySmartDateTest.IsEmpty);
Assert.AreEqual(test.EmptySmartDateTest.Date, result.EmptySmartDateTest.Date);
Assert.AreEqual(test.FilledSmartDateTest, result.FilledSmartDateTest);
Assert.AreEqual(test.FilledSmartDateTest.FormatString, result.FilledSmartDateTest.FormatString);
Assert.AreEqual(test.FilledSmartDateTest.EmptyIsMin, result.FilledSmartDateTest.EmptyIsMin);
Assert.AreEqual(test.FilledSmartDateTest.IsEmpty, result.FilledSmartDateTest.IsEmpty);
Assert.AreEqual(test.FilledSmartDateTest.Date, result.FilledSmartDateTest.Date);
}
[TestMethod()]
public void TestAuthorizationRulesAfterSerialization()
{
Csla.Test.Security.PermissionsRoot root = Csla.Test.Security.PermissionsRoot.NewPermissionsRoot();
try
{
root.FirstName = "something";
Assert.Fail("Exception didn't occur");
}
catch (Csla.Security.SecurityException ex)
{
Assert.AreEqual("Property set not allowed", ex.Message);
}
Csla.Test.Security.TestPrincipal.SimulateLogin();
try
{
root.FirstName = "something";
}
catch (Csla.Security.SecurityException ex)
{
Assert.Fail("exception occurred");
}
Csla.Test.Security.TestPrincipal.SimulateLogout();
Csla.Test.Security.PermissionsRoot rootClone = root.Clone();
try
{
rootClone.FirstName = "something else";
Assert.Fail("Exception didn't occur");
}
catch (Csla.Security.SecurityException ex)
{
Assert.AreEqual("Property set not allowed", ex.Message);
}
Csla.Test.Security.TestPrincipal.SimulateLogin();
try
{
rootClone.FirstName = "something new";
}
catch (Csla.Security.SecurityException ex)
{
Assert.Fail("exception occurred");
}
Csla.Test.Security.TestPrincipal.SimulateLogout();
}
private void OnIsDirtyChanged(object sender, PropertyChangedEventArgs e)
{
Csla.ApplicationContext.GlobalContext["OnIsDirtyChanged"] = "OnIsDirtyChanged";
}
private static void StaticOnIsDirtyChanged(object sender, PropertyChangedEventArgs e)
{
Csla.ApplicationContext.GlobalContext["StaticOnIsDirtyChanged"] =
"StaticOnIsDirtyChanged";
}
public static void PublicStaticOnIsDirtyChanged(object sender, PropertyChangedEventArgs e)
{
Csla.ApplicationContext.GlobalContext["PublicStaticOnIsDirtyChanged"] =
"PublicStaticOnIsDirtyChanged";
}
[TestMethod]
public void DCClone()
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] =
"NetDataContractSerializer";
Assert.AreEqual(
Csla.ApplicationContext.SerializationFormatters.NetDataContractSerializer,
Csla.ApplicationContext.SerializationFormatter,
"Formatter should be NetDataContractSerializer");
DCRoot root = new DCRoot();
root.Data = 123;
DCRoot clone = root.Clone();
Assert.IsFalse(ReferenceEquals(root, clone), "Object instance should be different");
Assert.AreEqual(root.Data, clone.Data, "Data should match");
Assert.IsTrue(root.IsDirty, "Root IsDirty should be true");
Assert.IsTrue(clone.IsDirty, "Clone IsDirty should be true");
}
[TestMethod]
public void DCEditLevels()
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] =
"NetDataContractSerializer";
Assert.AreEqual(
Csla.ApplicationContext.SerializationFormatters.NetDataContractSerializer,
Csla.ApplicationContext.SerializationFormatter,
"Formatter should be NetDataContractSerializer");
DCRoot root = new DCRoot();
root.BeginEdit();
root.Data = 123;
root.CancelEdit();
Assert.AreEqual(0, root.Data, "Data should be 0");
root.BeginEdit();
root.Data = 123;
root.ApplyEdit();
Assert.AreEqual(123, root.Data, "Data should be 123");
}
[TestMethod]
public void AsyncLoadManagerSerializationTest()
{
Csla.Test.Basic.Children list = Csla.Test.Basic.Children.NewChildren();
list.Add("1");
list.Add("2");
IEditableObject item = list[1] as IEditableObject;
int editLevel = (int)item.GetType().GetProperty("EditLevel", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null);
object manager = item.GetType().GetProperty("LoadManager", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null);
item.BeginEdit();
int newEditLevel = (int)item.GetType().GetProperty("EditLevel", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.FlattenHierarchy).GetValue(item, null);
Assert.AreEqual(editLevel + 1, newEditLevel, "Edit level incorrect after begin edit");
}
[TestMethod]
public void SerializeCommand()
{
var cmd = new TestCommand();
cmd.Name = "test data";
var buffer = new System.IO.MemoryStream();
#if !SILVERLIGHT
var bf = (TestCommand)Csla.Core.ObjectCloner.Clone(cmd);
Assert.AreEqual(cmd.Name, bf.Name, "after BinaryFormatter");
var ndcs = new System.Runtime.Serialization.NetDataContractSerializer();
ndcs.Serialize(buffer, cmd);
buffer.Position = 0;
var n = (TestCommand)ndcs.Deserialize(buffer);
Assert.AreEqual(cmd.Name, n.Name, "after NDCS");
#endif
buffer = new System.IO.MemoryStream();
var mf = new Csla.Serialization.Mobile.MobileFormatter();
mf.Serialize(buffer, cmd);
buffer.Position = 0;
var m = (TestCommand)mf.Deserialize(buffer);
Assert.AreEqual(cmd.Name, m.Name, "after MobileFormatter");
}
#if !SILVERLIGHT
[TestMethod]
public void CommandOverDataPortal()
{
Csla.ApplicationContext.DataPortalProxy = "Csla.Testing.Business.TestProxies.AppDomainProxy, Csla.Testing.Business";
try
{
var cmd = new TestCommand();
cmd.Name = "test data";
var result = Csla.DataPortal.Execute<TestCommand>(cmd);
Assert.IsFalse(ReferenceEquals(cmd, result), "References should not match");
Assert.AreEqual(cmd.Name + " server", result.Name);
}
finally
{
System.Configuration.ConfigurationManager.AppSettings["CslaDataPortalProxy"] = null;
}
}
#endif
#if !SILVERLIGHT && !NETFX_CORE
[TestMethod]
public void UseCustomSerializationFormatter()
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "Csla.Serialization.NetDataContractSerializerWrapper, Csla";
try
{
var formatter = SerializationFormatterFactory.GetFormatter();
Assert.AreEqual(ApplicationContext.SerializationFormatter, ApplicationContext.SerializationFormatters.CustomFormatter);
Assert.IsInstanceOfType(formatter, typeof(NetDataContractSerializerWrapper));
}
finally
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = null;
}
}
[TestMethod]
public void UseNetDataContractSerializer()
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "NetDataContractSerializer";
try
{
var formatter = SerializationFormatterFactory.GetFormatter();
Assert.AreEqual(ApplicationContext.SerializationFormatter, ApplicationContext.SerializationFormatters.NetDataContractSerializer);
Assert.IsInstanceOfType(formatter, typeof(NetDataContractSerializerWrapper));
}
finally
{
System.Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = null;
}
}
}
#endif
[Serializable]
public class TestCommand : CommandBase<TestCommand>
{
private static PropertyInfo<string> NameProperty = RegisterProperty(typeof(TestCommand), new PropertyInfo<string>("Name"));
public string Name
{
get { return ReadProperty(NameProperty); }
set { LoadProperty(NameProperty, value); }
}
protected override void DataPortal_Execute()
{
Name = Name + " server";
}
}
}
| |
using System;
using System.Collections.Generic;
using Android.Runtime;
namespace Org.Webrtc {
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder']"
[global::Android.Runtime.Register ("org/webrtc/MediaCodecVideoEncoder", DoNotGenerateAcw=true)]
public partial class MediaCodecVideoEncoder : global::Java.Lang.Object {
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.EncoderProperties']"
[global::Android.Runtime.Register ("org/webrtc/MediaCodecVideoEncoder$EncoderProperties", DoNotGenerateAcw=true)]
public partial class EncoderProperties : global::Java.Lang.Object {
static IntPtr codecName_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.EncoderProperties']/field[@name='codecName']"
[Register ("codecName")]
public string CodecName {
get {
if (codecName_jfieldId == IntPtr.Zero)
codecName_jfieldId = JNIEnv.GetFieldID (class_ref, "codecName", "Ljava/lang/String;");
IntPtr __ret = JNIEnv.GetObjectField (Handle, codecName_jfieldId);
return JNIEnv.GetString (__ret, JniHandleOwnership.TransferLocalRef);
}
set {
if (codecName_jfieldId == IntPtr.Zero)
codecName_jfieldId = JNIEnv.GetFieldID (class_ref, "codecName", "Ljava/lang/String;");
IntPtr native_value = JNIEnv.NewString (value);
try {
JNIEnv.SetField (Handle, codecName_jfieldId, native_value);
} finally {
JNIEnv.DeleteLocalRef (native_value);
}
}
}
static IntPtr colorFormat_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.EncoderProperties']/field[@name='colorFormat']"
[Register ("colorFormat")]
public int ColorFormat {
get {
if (colorFormat_jfieldId == IntPtr.Zero)
colorFormat_jfieldId = JNIEnv.GetFieldID (class_ref, "colorFormat", "I");
return JNIEnv.GetIntField (Handle, colorFormat_jfieldId);
}
set {
if (colorFormat_jfieldId == IntPtr.Zero)
colorFormat_jfieldId = JNIEnv.GetFieldID (class_ref, "colorFormat", "I");
try {
JNIEnv.SetField (Handle, colorFormat_jfieldId, value);
} finally {
}
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/MediaCodecVideoEncoder$EncoderProperties", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (EncoderProperties); }
}
protected EncoderProperties (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_Ljava_lang_String_I;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.EncoderProperties']/constructor[@name='MediaCodecVideoEncoder.EncoderProperties' and count(parameter)=2 and parameter[1][@type='java.lang.String'] and parameter[2][@type='int']]"
[Register (".ctor", "(Ljava/lang/String;I)V", "")]
public unsafe EncoderProperties (string p0, int p1)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [2];
__args [0] = new JValue (native_p0);
__args [1] = new JValue (p1);
if (GetType () != typeof (EncoderProperties)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(Ljava/lang/String;I)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(Ljava/lang/String;I)V", __args);
return;
}
if (id_ctor_Ljava_lang_String_I == IntPtr.Zero)
id_ctor_Ljava_lang_String_I = JNIEnv.GetMethodID (class_ref, "<init>", "(Ljava/lang/String;I)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_Ljava_lang_String_I, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_Ljava_lang_String_I, __args);
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.OutputBufferInfo']"
[global::Android.Runtime.Register ("org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo", DoNotGenerateAcw=true)]
public partial class OutputBufferInfo : global::Java.Lang.Object {
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/MediaCodecVideoEncoder$OutputBufferInfo", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (OutputBufferInfo); }
}
protected OutputBufferInfo (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_ctor_ILjava_nio_ByteBuffer_ZJ;
// Metadata.xml XPath constructor reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.OutputBufferInfo']/constructor[@name='MediaCodecVideoEncoder.OutputBufferInfo' and count(parameter)=4 and parameter[1][@type='int'] and parameter[2][@type='java.nio.ByteBuffer'] and parameter[3][@type='boolean'] and parameter[4][@type='long']]"
[Register (".ctor", "(ILjava/nio/ByteBuffer;ZJ)V", "")]
public unsafe OutputBufferInfo (int p0, global::Java.Nio.ByteBuffer p1, bool p2, long p3)
: base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer)
{
if (Handle != IntPtr.Zero)
return;
try {
JValue* __args = stackalloc JValue [4];
__args [0] = new JValue (p0);
__args [1] = new JValue (p1);
__args [2] = new JValue (p2);
__args [3] = new JValue (p3);
if (GetType () != typeof (OutputBufferInfo)) {
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (GetType (), "(ILjava/nio/ByteBuffer;ZJ)V", __args),
JniHandleOwnership.TransferLocalRef);
global::Android.Runtime.JNIEnv.FinishCreateInstance (Handle, "(ILjava/nio/ByteBuffer;ZJ)V", __args);
return;
}
if (id_ctor_ILjava_nio_ByteBuffer_ZJ == IntPtr.Zero)
id_ctor_ILjava_nio_ByteBuffer_ZJ = JNIEnv.GetMethodID (class_ref, "<init>", "(ILjava/nio/ByteBuffer;ZJ)V");
SetHandle (
global::Android.Runtime.JNIEnv.StartCreateInstance (class_ref, id_ctor_ILjava_nio_ByteBuffer_ZJ, __args),
JniHandleOwnership.TransferLocalRef);
JNIEnv.FinishCreateInstance (Handle, class_ref, id_ctor_ILjava_nio_ByteBuffer_ZJ, __args);
} finally {
}
}
}
// Metadata.xml XPath class reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']"
[global::Android.Runtime.Register ("org/webrtc/MediaCodecVideoEncoder$VideoCodecType", DoNotGenerateAcw=true)]
public sealed partial class VideoCodecType : global::Java.Lang.Enum {
static IntPtr VIDEO_CODEC_H264_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']/field[@name='VIDEO_CODEC_H264']"
[Register ("VIDEO_CODEC_H264")]
public static global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType VideoCodecH264 {
get {
if (VIDEO_CODEC_H264_jfieldId == IntPtr.Zero)
VIDEO_CODEC_H264_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "VIDEO_CODEC_H264", "Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, VIDEO_CODEC_H264_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType> (__ret, JniHandleOwnership.TransferLocalRef);
}
}
static IntPtr VIDEO_CODEC_VP8_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']/field[@name='VIDEO_CODEC_VP8']"
[Register ("VIDEO_CODEC_VP8")]
public static global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType VideoCodecVp8 {
get {
if (VIDEO_CODEC_VP8_jfieldId == IntPtr.Zero)
VIDEO_CODEC_VP8_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "VIDEO_CODEC_VP8", "Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, VIDEO_CODEC_VP8_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType> (__ret, JniHandleOwnership.TransferLocalRef);
}
}
static IntPtr VIDEO_CODEC_VP9_jfieldId;
// Metadata.xml XPath field reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']/field[@name='VIDEO_CODEC_VP9']"
[Register ("VIDEO_CODEC_VP9")]
public static global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType VideoCodecVp9 {
get {
if (VIDEO_CODEC_VP9_jfieldId == IntPtr.Zero)
VIDEO_CODEC_VP9_jfieldId = JNIEnv.GetStaticFieldID (class_ref, "VIDEO_CODEC_VP9", "Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;");
IntPtr __ret = JNIEnv.GetStaticObjectField (class_ref, VIDEO_CODEC_VP9_jfieldId);
return global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType> (__ret, JniHandleOwnership.TransferLocalRef);
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/MediaCodecVideoEncoder$VideoCodecType", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (VideoCodecType); }
}
internal VideoCodecType (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_valueOf_Ljava_lang_String_;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']/method[@name='valueOf' and count(parameter)=1 and parameter[1][@type='java.lang.String']]"
[Register ("valueOf", "(Ljava/lang/String;)Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;", "")]
public static unsafe global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType ValueOf (string p0)
{
if (id_valueOf_Ljava_lang_String_ == IntPtr.Zero)
id_valueOf_Ljava_lang_String_ = JNIEnv.GetStaticMethodID (class_ref, "valueOf", "(Ljava/lang/String;)Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;");
IntPtr native_p0 = JNIEnv.NewString (p0);
try {
JValue* __args = stackalloc JValue [1];
__args [0] = new JValue (native_p0);
global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType __ret = global::Java.Lang.Object.GetObject<global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType> (JNIEnv.CallStaticObjectMethod (class_ref, id_valueOf_Ljava_lang_String_, __args), JniHandleOwnership.TransferLocalRef);
return __ret;
} finally {
JNIEnv.DeleteLocalRef (native_p0);
}
}
static IntPtr id_values;
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder.VideoCodecType']/method[@name='values' and count(parameter)=0]"
[Register ("values", "()[Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;", "")]
public static unsafe global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType[] Values ()
{
if (id_values == IntPtr.Zero)
id_values = JNIEnv.GetStaticMethodID (class_ref, "values", "()[Lorg/webrtc/MediaCodecVideoEncoder$VideoCodecType;");
try {
return (global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType[]) JNIEnv.GetArray (JNIEnv.CallStaticObjectMethod (class_ref, id_values), JniHandleOwnership.TransferLocalRef, typeof (global::Org.Webrtc.MediaCodecVideoEncoder.VideoCodecType));
} finally {
}
}
}
internal static IntPtr java_class_handle;
internal static IntPtr class_ref {
get {
return JNIEnv.FindClass ("org/webrtc/MediaCodecVideoEncoder", ref java_class_handle);
}
}
protected override IntPtr ThresholdClass {
get { return class_ref; }
}
protected override global::System.Type ThresholdType {
get { return typeof (MediaCodecVideoEncoder); }
}
protected MediaCodecVideoEncoder (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {}
static IntPtr id_isH264HwSupported;
public static unsafe bool IsH264HwSupported {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder']/method[@name='isH264HwSupported' and count(parameter)=0]"
[Register ("isH264HwSupported", "()Z", "GetIsH264HwSupportedHandler")]
get {
if (id_isH264HwSupported == IntPtr.Zero)
id_isH264HwSupported = JNIEnv.GetStaticMethodID (class_ref, "isH264HwSupported", "()Z");
try {
return JNIEnv.CallStaticBooleanMethod (class_ref, id_isH264HwSupported);
} finally {
}
}
}
static IntPtr id_isVp8HwSupported;
public static unsafe bool IsVp8HwSupported {
// Metadata.xml XPath method reference: path="/api/package[@name='org.webrtc']/class[@name='MediaCodecVideoEncoder']/method[@name='isVp8HwSupported' and count(parameter)=0]"
[Register ("isVp8HwSupported", "()Z", "GetIsVp8HwSupportedHandler")]
get {
if (id_isVp8HwSupported == IntPtr.Zero)
id_isVp8HwSupported = JNIEnv.GetStaticMethodID (class_ref, "isVp8HwSupported", "()Z");
try {
return JNIEnv.CallStaticBooleanMethod (class_ref, id_isVp8HwSupported);
} finally {
}
}
}
}
}
| |
//
// Copyright (c) 2004-2020 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.Layouts
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using NLog.Config;
using NLog.Internal;
using NLog.Common;
/// <summary>
/// Abstract interface that layouts must implement.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1724:TypeNamesShouldNotMatchNamespaces", Justification = "Few people will see this conflict.")]
[NLogConfigurationItem]
public abstract class Layout : ISupportsInitialize, IRenderable
{
/// <summary>
/// Is this layout initialized? See <see cref="Initialize(NLog.Config.LoggingConfiguration)"/>
/// </summary>
internal bool IsInitialized;
private bool _scannedForObjects;
/// <summary>
/// Gets a value indicating whether this layout is thread-agnostic (can be rendered on any thread).
/// </summary>
/// <remarks>
/// Layout is thread-agnostic if it has been marked with [ThreadAgnostic] attribute and all its children are
/// like that as well.
///
/// Thread-agnostic layouts only use contents of <see cref="LogEventInfo"/> for its output.
/// </remarks>
internal bool ThreadAgnostic { get; set; }
internal bool ThreadSafe { get; set; }
internal bool MutableUnsafe { get; set; }
/// <summary>
/// Gets the level of stack trace information required for rendering.
/// </summary>
internal StackTraceUsage StackTraceUsage { get; private set; }
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Converts a given text to a <see cref="Layout" />.
/// </summary>
/// <param name="text">Text to be converted.</param>
/// <returns><see cref="SimpleLayout"/> object represented by the text.</returns>
public static implicit operator Layout([Localizable(false)] string text)
{
return FromString(text, ConfigurationItemFactory.Default);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>'
public static Layout FromString(string layoutText)
{
return FromString(layoutText, ConfigurationItemFactory.Default);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <param name="configurationItemFactory">The NLog factories to use when resolving layout renderers.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText, ConfigurationItemFactory configurationItemFactory)
{
return new SimpleLayout(layoutText, configurationItemFactory);
}
/// <summary>
/// Implicitly converts the specified string to a <see cref="SimpleLayout"/>.
/// </summary>
/// <param name="layoutText">The layout string.</param>
/// <param name="throwConfigExceptions">Whether <see cref="NLogConfigurationException"/> should be thrown on parse errors (false = replace unrecognized tokens with a space).</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromString(string layoutText, bool throwConfigExceptions)
{
try
{
return new SimpleLayout(layoutText, ConfigurationItemFactory.Default, throwConfigExceptions);
}
catch (NLogConfigurationException)
{
throw;
}
catch (Exception ex)
{
if (!throwConfigExceptions || ex.MustBeRethrownImmediately())
throw;
throw new NLogConfigurationException($"Invalid Layout: {layoutText}", ex);
}
}
/// <summary>
/// Create a <see cref="SimpleLayout"/> from a lambda method.
/// </summary>
/// <param name="layoutMethod">Method that renders the layout.</param>
/// <param name="options">Tell if method is safe for concurrent threading.</param>
/// <returns>Instance of <see cref="SimpleLayout"/>.</returns>
public static Layout FromMethod(Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options = LayoutRenderOptions.None)
{
if (layoutMethod == null)
throw new ArgumentNullException(nameof(layoutMethod));
#if NETSTANDARD1_0
var name = $"{layoutMethod.Target?.ToString()}";
#else
var name = $"{layoutMethod.Method?.DeclaringType?.ToString()}.{layoutMethod.Method?.Name}";
#endif
var layoutRenderer = CreateFuncLayoutRenderer(layoutMethod, options, name);
return new SimpleLayout(new[] { layoutRenderer }, layoutRenderer.LayoutRendererName, ConfigurationItemFactory.Default);
}
private static LayoutRenderers.FuncLayoutRenderer CreateFuncLayoutRenderer(Func<LogEventInfo, object> layoutMethod, LayoutRenderOptions options, string name)
{
if ((options & LayoutRenderOptions.ThreadAgnostic) == LayoutRenderOptions.ThreadAgnostic)
return new LayoutRenderers.FuncThreadAgnosticLayoutRenderer(name, (l, c) => layoutMethod(l));
else if ((options & LayoutRenderOptions.ThreadSafe) != 0)
return new LayoutRenderers.FuncThreadSafeLayoutRenderer(name, (l, c) => layoutMethod(l));
else
return new LayoutRenderers.FuncLayoutRenderer(name, (l, c) => layoutMethod(l));
}
/// <summary>
/// Precalculates the layout for the specified log event and stores the result
/// in per-log event cache.
///
/// Only if the layout doesn't have [ThreadAgnostic] and doesn't contain layouts with [ThreadAgnostic].
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// Calling this method enables you to store the log event in a buffer
/// and/or potentially evaluate it in another thread even though the
/// layout may contain thread-dependent renderer.
/// </remarks>
public virtual void Precalculate(LogEventInfo logEvent)
{
if (!ThreadAgnostic || MutableUnsafe)
{
Render(logEvent);
}
}
/// <summary>
/// Renders the event info in layout.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <returns>String representing log event.</returns>
public string Render(LogEventInfo logEvent)
{
if (!IsInitialized)
{
Initialize(LoggingConfiguration);
}
if (!ThreadAgnostic || MutableUnsafe)
{
object cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
return cachedValue?.ToString() ?? string.Empty;
}
}
string layoutValue = GetFormattedMessage(logEvent) ?? string.Empty;
if (!ThreadAgnostic || MutableUnsafe)
{
// Would be nice to only do this in Precalculate(), but we need to ensure internal cache
// is updated for for custom Layouts that overrides Precalculate (without calling base.Precalculate)
logEvent.AddCachedLayoutValue(this, layoutValue);
}
return layoutValue;
}
internal virtual void PrecalculateBuilder(LogEventInfo logEvent, StringBuilder target)
{
Precalculate(logEvent); // Allow custom Layouts to work with OptimizeBufferReuse
}
/// <summary>
/// Optimized version of <see cref="Render(LogEventInfo)"/> for internal Layouts. Works best
/// when override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available.
/// </summary>
/// <param name="logEvent">The event info.</param>
/// <param name="target">Appends the string representing log event to target</param>
/// <param name="cacheLayoutResult">Should rendering result be cached on LogEventInfo</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder target, bool cacheLayoutResult = false)
{
if (!IsInitialized)
{
Initialize(LoggingConfiguration);
}
if (!ThreadAgnostic || MutableUnsafe)
{
object cachedValue;
if (logEvent.TryGetCachedLayoutValue(this, out cachedValue))
{
target.Append(cachedValue?.ToString() ?? string.Empty);
return;
}
}
cacheLayoutResult = cacheLayoutResult && !ThreadAgnostic;
using (var localTarget = new AppendBuilderCreator(target, cacheLayoutResult))
{
RenderFormattedMessage(logEvent, localTarget.Builder);
if (cacheLayoutResult)
{
// when needed as it generates garbage
logEvent.AddCachedLayoutValue(this, localTarget.Builder.ToString());
}
}
}
/// <summary>
/// Valid default implementation of <see cref="GetFormattedMessage" />, when having implemented the optimized <see cref="RenderFormattedMessage"/>
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="reusableBuilder">StringBuilder to help minimize allocations [optional].</param>
/// <returns>The rendered layout.</returns>
internal string RenderAllocateBuilder(LogEventInfo logEvent, StringBuilder reusableBuilder = null)
{
int initialLength = _maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var sb = reusableBuilder ?? new StringBuilder(initialLength);
RenderFormattedMessage(logEvent, sb);
if (sb.Length > _maxRenderedLength)
{
_maxRenderedLength = sb.Length;
}
return sb.ToString();
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <param name="target"><see cref="StringBuilder"/> for the result</param>
protected virtual void RenderFormattedMessage(LogEventInfo logEvent, StringBuilder target)
{
target.Append(GetFormattedMessage(logEvent) ?? string.Empty);
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (!IsInitialized)
{
LoggingConfiguration = configuration;
IsInitialized = true;
_scannedForObjects = false;
InitializeLayout();
if (!_scannedForObjects)
{
InternalLogger.Debug("{0} Initialized Layout done but not scanned for objects", GetType());
PerformObjectScanning();
}
}
}
internal void PerformObjectScanning()
{
var objectGraphScannerList = ObjectGraphScanner.FindReachableObjects<object>(true, this);
var objectGraphTypes = new HashSet<Type>(objectGraphScannerList.Select(o => o.GetType()));
objectGraphTypes.Remove(typeof(SimpleLayout));
objectGraphTypes.Remove(typeof(NLog.LayoutRenderers.LiteralLayoutRenderer));
// determine whether the layout is thread-agnostic
// layout is thread agnostic if it is thread-agnostic and
// all its nested objects are thread-agnostic.
ThreadAgnostic = objectGraphTypes.All(t => t.IsDefined(typeof(ThreadAgnosticAttribute), true));
ThreadSafe = objectGraphTypes.All(t => t.IsDefined(typeof(ThreadSafeAttribute), true));
MutableUnsafe = objectGraphTypes.Any(t => t.IsDefined(typeof(MutableUnsafeAttribute), true));
if ((ThreadAgnostic || !MutableUnsafe) && objectGraphScannerList.Count > 1 && objectGraphTypes.Count > 0)
{
foreach (var nestedLayout in objectGraphScannerList.OfType<Layout>())
{
if (!ReferenceEquals(nestedLayout, this))
{
nestedLayout.Initialize(LoggingConfiguration);
ThreadAgnostic = nestedLayout.ThreadAgnostic && ThreadAgnostic;
MutableUnsafe = nestedLayout.MutableUnsafe || MutableUnsafe;
}
}
}
// determine the max StackTraceUsage, to decide if Logger needs to capture callsite
StackTraceUsage = StackTraceUsage.None; // In case this Layout should implement IUsesStackTrace
StackTraceUsage = objectGraphScannerList.OfType<IUsesStackTrace>().DefaultIfEmpty().Max(item => item?.StackTraceUsage ?? StackTraceUsage.None);
_scannedForObjects = true;
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (IsInitialized)
{
LoggingConfiguration = null;
IsInitialized = false;
CloseLayout();
}
}
/// <summary>
/// Initializes the layout.
/// </summary>
protected virtual void InitializeLayout()
{
PerformObjectScanning();
}
/// <summary>
/// Closes the layout.
/// </summary>
protected virtual void CloseLayout()
{
}
/// <summary>
/// Renders the layout for the specified logging event by invoking layout renderers.
/// </summary>
/// <param name="logEvent">The logging event.</param>
/// <returns>The rendered layout.</returns>
protected abstract string GetFormattedMessage(LogEventInfo logEvent);
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the Layout.</typeparam>
/// <param name="name"> Name of the Layout.</param>
public static void Register<T>(string name)
where T : Layout
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom Layout.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutType"> Type of the Layout.</param>
/// <param name="name"> Name of the Layout.</param>
public static void Register(string name, Type layoutType)
{
ConfigurationItemFactory.Default.Layouts
.RegisterDefinition(name, layoutType);
}
/// <summary>
/// Optimized version of <see cref="Precalculate(LogEventInfo)"/> for internal Layouts, when
/// override of <see cref="RenderFormattedMessage(LogEventInfo, StringBuilder)"/> is available.
/// </summary>
internal void PrecalculateBuilderInternal(LogEventInfo logEvent, StringBuilder target)
{
if (!ThreadAgnostic || MutableUnsafe)
{
RenderAppendBuilder(logEvent, target, true);
}
}
internal string ToStringWithNestedItems<T>(IList<T> nestedItems, Func<T, string> nextItemToString)
{
if (nestedItems?.Count > 0)
{
var nestedNames = nestedItems.Select(c => nextItemToString(c)).ToArray();
return string.Concat(GetType().Name, "=", string.Join("|", nestedNames));
}
return base.ToString();
}
/// <summary>
/// Try get value
/// </summary>
/// <param name="logEvent"></param>
/// <param name="rawValue">rawValue if return result is true</param>
/// <returns>false if we could not determine the rawValue</returns>
internal virtual bool TryGetRawValue(LogEventInfo logEvent, out object rawValue)
{
rawValue = null;
return false;
}
}
}
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Framework;
using Microsoft.DotNet.MSBuildSdkResolver;
using Microsoft.DotNet.Tools.Test.Utilities;
using System.Collections.Generic;
using System.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
using Xunit.Abstractions;
using System;
[assembly: CollectionBehavior(DisableTestParallelization = true)]
namespace Microsoft.DotNet.Cli.Utils.Tests
{
public class GivenAnMSBuildSdkResolver : TestBase
{
private ITestOutputHelper _logger;
public GivenAnMSBuildSdkResolver(ITestOutputHelper logger)
{
_logger = logger;
}
[Fact]
public void ItHasCorrectNameAndPriority()
{
var resolver = new DotNetMSBuildSdkResolver();
Assert.Equal(5000, resolver.Priority);
Assert.Equal("Microsoft.DotNet.MSBuildSdkResolver", resolver.Name);
}
[Fact]
public void ItDoesNotFindMSBuildSdkThatIsMissingFromLocatedNETCoreSdk()
{
var environment = new TestEnvironment();
var expected = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.97");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.SdkThatDoesNotExist", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().NotBeEmpty();
}
[Fact]
public void ItFindsTheVersionSpecifiedInGlobalJson()
{
var environment = new TestEnvironment();
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.97");
var expected = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.98");
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99");
environment.CreateGlobalJson(environment.TestDirectory, "99.99.98");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be("99.99.98");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Fact]
public void ItReturnsNullIfTheVersionFoundDoesNotSatisfyTheMinVersion()
{
var environment = new TestEnvironment();
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "999.99.99"),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().Contain(string.Format(Strings.NETCoreSDKSmallerThanMinimumRequestedVersion, "99.99.99", "999.99.99"));
}
[Fact]
public void ItReturnsNullWhenTheSDKRequiresAHigherVersionOfMSBuildThanAnyOneAvailable()
{
var environment = new TestEnvironment();
var expected =
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99", new Version(2, 0));
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "99.99.99"),
new MockContext
{
MSBuildVersion = new Version(1, 0),
ProjectFileDirectory = environment.TestDirectory
},
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().Contain(string.Format(Strings.MSBuildSmallerThanMinimumVersion, "99.99.99", "2.0", "1.0"));
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ItReturnsHighestSdkAvailableThatIsCompatibleWithMSBuild(bool disallowPreviews)
{
var environment = new TestEnvironment(identifier: disallowPreviews.ToString())
{
DisallowPrereleaseByDefault = disallowPreviews
};
var compatibleRtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "98.98.98", new Version(19, 0, 0, 0));
var compatiblePreview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99-preview", new Version(20, 0, 0, 0));
var incompatible = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "100.100.100", new Version(21, 0, 0, 0));
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext
{
MSBuildVersion = new Version(20, 0, 0, 0),
ProjectFileDirectory = environment.TestDirectory,
},
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be((disallowPreviews ? compatibleRtm : compatiblePreview).FullName);
result.Version.Should().Be(disallowPreviews ? "98.98.98" : "99.99.99-preview");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ItDoesNotReturnHighestSdkAvailableThatIsCompatibleWithMSBuildWhenVersionInGlobalJsonCannotBeFound(bool disallowPreviews)
{
var environment = new TestEnvironment(callingMethod: "ItDoesNotReturnHighest___", identifier: disallowPreviews.ToString())
{
DisallowPrereleaseByDefault = disallowPreviews
};
var compatibleRtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "98.98.98", new Version(19, 0, 0, 0));
var compatiblePreview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99-preview", new Version(20, 0, 0, 0));
var incompatible = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "100.100.100", new Version(21, 0, 0, 0));
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.CreateGlobalJson(environment.TestDirectory, "1.2.3");
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext
{
MSBuildVersion = new Version(20, 0, 0, 0),
ProjectFileDirectory = environment.TestDirectory,
},
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();;
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().NotBeEmpty();
}
[Fact]
public void ItReturnsNullWhenTheDefaultVSRequiredSDKVersionIsHigherThanTheSDKVersionAvailable()
{
var environment = new TestEnvironment();
var expected =
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "1.0.1");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "1.0.0"),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().Contain(string.Format(Strings.NETCoreSDKSmallerThanMinimumVersionRequiredByVisualStudio, "1.0.1", "1.0.4"));
}
[Fact]
public void ItReturnsNullWhenTheTheVSRequiredSDKVersionIsHigherThanTheSDKVersionAvailable()
{
var environment = new TestEnvironment();
var expected =
environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "1.0.1");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.CreateMinimumVSDefinedSDKVersionFile("2.0.0");
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "1.0.0"),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeFalse();
result.Path.Should().BeNull();
result.Version.Should().BeNull();
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().Contain(string.Format(Strings.NETCoreSDKSmallerThanMinimumVersionRequiredByVisualStudio, "1.0.1", "2.0.0"));
}
[Fact]
public void ItReturnsTheVersionIfItIsEqualToTheMinVersionAndTheVSDefinedMinVersion()
{
var environment = new TestEnvironment();
var expected = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "99.99.99");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.CreateMinimumVSDefinedSDKVersionFile("99.99.99");
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "99.99.99"),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be("99.99.99");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Fact]
public void ItReturnsTheVersionIfItIsHigherThanTheMinVersionAndTheVSDefinedMinVersion()
{
var environment = new TestEnvironment();
var expected = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "999.99.99");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.CreateMinimumVSDefinedSDKVersionFile("999.99.98");
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, "99.99.99"),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be("999.99.99");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ItDisallowsPreviewsBasedOnDefault(bool disallowPreviewsByDefault)
{
var environment = new TestEnvironment(identifier: disallowPreviewsByDefault.ToString());
var rtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "10.0.0");
var preview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "11.0.0-preview1");
var expected = disallowPreviewsByDefault ? rtm : preview;
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.DisallowPrereleaseByDefault = disallowPreviewsByDefault;
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be(disallowPreviewsByDefault ? "10.0.0" : "11.0.0-preview1");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Theory]
[InlineData(true)]
[InlineData(false)]
public void ItDisallowsPreviewsBasedOnFile(bool disallowPreviews)
{
var environment = new TestEnvironment(identifier: disallowPreviews.ToString());
var rtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "10.0.0");
var preview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "11.0.0-preview1");
var expected = disallowPreviews ? rtm : preview;
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.DisallowPrereleaseByDefault = !disallowPreviews;
environment.CreateVSSettingsFile(disallowPreviews);
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be(disallowPreviews ? "10.0.0" : "11.0.0-preview1");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Fact]
public void ItObservesChangesToVSSettingsFile()
{
var environment = new TestEnvironment();
var rtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "10.0.0");
var preview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "11.0.0-preview1");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.CreateVSSettingsFile(disallowPreviews: true);
var resolver = environment.CreateResolver();
void Check(bool disallowPreviews, string message)
{
// check twice because file-up-to-date is a separate code path
for (int i = 0; i < 2; i++)
{
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
string m = $"{message} ({i})";
var expected = disallowPreviews ? rtm : preview;
result.Success.Should().BeTrue(m);
result.Path.Should().Be(expected.FullName, m);
result.Version.Should().Be(disallowPreviews ? "10.0.0" : "11.0.0-preview1", m);
result.Warnings.Should().BeNullOrEmpty(m);
result.Errors.Should().BeNullOrEmpty(m);
}
}
environment.DeleteVSSettingsFile();
Check(disallowPreviews: false, message: "default with no file");
environment.CreateVSSettingsFile(disallowPreviews: true);
Check(disallowPreviews: true, message: "file changed to disallow previews");
environment.CreateVSSettingsFile(disallowPreviews: false);
Check(disallowPreviews: false, message: "file changed to not disallow previews");
environment.CreateVSSettingsFile(disallowPreviews: true);
Check(disallowPreviews: true, message: "file changed back to disallow previews");
environment.DeleteVSSettingsFile();
Check(disallowPreviews: false, message: "file deleted to return to default");
}
[Fact]
public void ItAllowsPreviewWhenGlobalJsonHasPreviewIrrespectiveOfSetting()
{
var environment = new TestEnvironment();
var rtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "10.0.0");
var preview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "11.0.0-preview1");
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
environment.DisallowPrereleaseByDefault = true;
environment.CreateGlobalJson(environment.TestDirectory, "11.0.0-preview1");
var resolver = environment.CreateResolver();
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(preview.FullName);
result.Version.Should().Be("11.0.0-preview1");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
[Fact]
public void ItRespectsAmbientVSSettings()
{
// When run in test explorer in VS, this will actually locate the settings for the current VS instance
// based on location of testhost executable. This gives us some coverage threw that path but we cannot
// fix our expectations since the behavior will vary (by design) based on the current VS instance's settings.
var vsSettings = VSSettings.Ambient;
var environment = new TestEnvironment();
var rtm = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "10.0.0");
var preview = environment.CreateSdkDirectory(ProgramFiles.X64, "Some.Test.Sdk", "11.0.0-preview1");
var expected = vsSettings.DisallowPrerelease() ? rtm : preview;
environment.CreateMuxerAndAddToPath(ProgramFiles.X64);
var resolver = environment.CreateResolver(useAmbientSettings: true);
var result = (MockResult)resolver.Resolve(
new SdkReference("Some.Test.Sdk", null, null),
new MockContext { ProjectFileDirectory = environment.TestDirectory },
new MockFactory());
result.Success.Should().BeTrue();
result.Path.Should().Be(expected.FullName);
result.Version.Should().Be(vsSettings.DisallowPrerelease() ? "10.0.0" : "11.0.0-preview1");
result.Warnings.Should().BeNullOrEmpty();
result.Errors.Should().BeNullOrEmpty();
}
private enum ProgramFiles
{
X64,
X86,
Default,
}
private sealed class TestEnvironment : SdkResolverContext
{
public string Muxer => RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "dotnet.exe" : "dotnet";
public string PathEnvironmentVariable { get; set; }
public DirectoryInfo TestDirectory { get; }
public FileInfo VSSettingsFile { get; set; }
public bool DisallowPrereleaseByDefault { get; set; }
public TestEnvironment(string identifier = "", [CallerMemberName] string callingMethod = "")
{
TestDirectory = TestAssets.CreateTestDirectory(
"temp",
identifier: identifier,
callingMethod: callingMethod);
DeleteMinimumVSDefinedSDKVersionFile();
PathEnvironmentVariable = string.Empty;
}
public SdkResolver CreateResolver(bool useAmbientSettings = false)
=> new DotNetMSBuildSdkResolver(
GetEnvironmentVariable,
useAmbientSettings
? VSSettings.Ambient
: new VSSettings(VSSettingsFile?.FullName, DisallowPrereleaseByDefault));
public DirectoryInfo GetSdkDirectory(ProgramFiles programFiles, string sdkName, string sdkVersion)
=> TestDirectory.GetDirectory(
GetProgramFilesDirectory(programFiles).FullName,
"dotnet",
"sdk",
sdkVersion,
"Sdks",
sdkName,
"Sdk");
public DirectoryInfo GetProgramFilesDirectory(ProgramFiles programFiles)
=> TestDirectory.GetDirectory($"ProgramFiles{programFiles}");
public DirectoryInfo CreateSdkDirectory(
ProgramFiles programFiles,
string sdkName,
string sdkVersion,
Version minimumMSBuildVersion = null)
{
var dir = GetSdkDirectory(programFiles, sdkName, sdkVersion);
dir.Create();
if (minimumMSBuildVersion != null)
{
CreateMSBuildRequiredVersionFile(programFiles, sdkVersion, minimumMSBuildVersion);
}
return dir;
}
public void CreateMuxerAndAddToPath(ProgramFiles programFiles)
{
var muxerDirectory =
TestDirectory.GetDirectory(GetProgramFilesDirectory(programFiles).FullName, "dotnet");
new FileInfo(Path.Combine(muxerDirectory.FullName, Muxer)).Create();
PathEnvironmentVariable = $"{muxerDirectory}{Path.PathSeparator}{PathEnvironmentVariable}";
}
private void CreateMSBuildRequiredVersionFile(
ProgramFiles programFiles,
string sdkVersion,
Version minimumMSBuildVersion)
{
if (minimumMSBuildVersion == null)
{
minimumMSBuildVersion = new Version(1, 0);
}
var cliDirectory = TestDirectory.GetDirectory(
GetProgramFilesDirectory(programFiles).FullName,
"dotnet",
"sdk",
sdkVersion);
File.WriteAllText(
Path.Combine(cliDirectory.FullName, "minimumMSBuildVersion"),
minimumMSBuildVersion.ToString());
}
public void CreateGlobalJson(DirectoryInfo directory, string version)
=> File.WriteAllText(directory.GetFile("global.json").FullName,
$@"{{ ""sdk"": {{ ""version"": ""{version}"" }} }}");
public string GetEnvironmentVariable(string variable)
{
switch (variable)
{
case "PATH":
return PathEnvironmentVariable;
default:
return null;
}
}
public void CreateMinimumVSDefinedSDKVersionFile(string version)
{
File.WriteAllText(GetMinimumVSDefinedSDKVersionFilePath(), version);
}
private void DeleteMinimumVSDefinedSDKVersionFile()
{
File.Delete(GetMinimumVSDefinedSDKVersionFilePath());
}
private string GetMinimumVSDefinedSDKVersionFilePath()
{
string baseDirectory = AppContext.BaseDirectory;
return Path.Combine(baseDirectory, "minimumVSDefinedSDKVersion");
}
public void CreateVSSettingsFile(bool disallowPreviews)
{
VSSettingsFile = TestDirectory.GetFile("sdk.txt");
// Guard against tests writing too fast for the up-to-date check
// It happens more often on Unix due to https://github.com/dotnet/corefx/issues/12403
var lastWriteTimeUtc = VSSettingsFile.Exists ? VSSettingsFile.LastWriteTimeUtc : DateTime.MinValue;
for (int sleep = 10; sleep < 3000; sleep *= 2)
{
File.WriteAllText(VSSettingsFile.FullName, $"UsePreviews={!disallowPreviews}");
VSSettingsFile.Refresh();
if (VSSettingsFile.LastWriteTimeUtc > lastWriteTimeUtc)
{
return;
}
System.Threading.Thread.Sleep(sleep);
}
throw new InvalidOperationException("LastWriteTime is not changing.");
}
public void DeleteVSSettingsFile()
{
VSSettingsFile.Delete();
}
}
private sealed class MockContext : SdkResolverContext
{
public new string ProjectFilePath { get => base.ProjectFilePath; set => base.ProjectFilePath = value; }
public new string SolutionFilePath { get => base.SolutionFilePath; set => base.SolutionFilePath = value; }
public new Version MSBuildVersion { get => base.MSBuildVersion; set => base.MSBuildVersion = value; }
public DirectoryInfo ProjectFileDirectory
{
get => new DirectoryInfo(Path.GetDirectoryName(ProjectFilePath));
set => ProjectFilePath = value.GetFile("test.csproj").FullName;
}
public MockContext()
{
MSBuildVersion = new Version(15, 3, 0);
}
}
private sealed class MockFactory : SdkResultFactory
{
public override SdkResult IndicateFailure(IEnumerable<string> errors, IEnumerable<string> warnings = null)
=> new MockResult(success: false, path: null, version: null, warnings: warnings, errors: errors);
public override SdkResult IndicateSuccess(string path, string version, IEnumerable<string> warnings = null)
=> new MockResult(success: true, path: path, version: version, warnings: warnings);
}
private sealed class MockResult : SdkResult
{
public MockResult(bool success, string path, string version, IEnumerable<string> warnings = null,
IEnumerable<string> errors = null)
{
Success = success;
Path = path;
Version = version;
Warnings = warnings;
Errors = errors;
}
public override bool Success { get; protected set; }
public override string Version { get; protected set; }
public override string Path { get; protected set; }
public IEnumerable<string> Errors { get; }
public IEnumerable<string> Warnings { get; }
}
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// ZipQueryOperator.cs
//
// <OWNER>[....]</OWNER>
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Threading;
namespace System.Linq.Parallel
{
/// <summary>
/// A Zip operator combines two input data sources into a single output stream,
/// using a pairwise element matching algorithm. For example, the result of zipping
/// two vectors a = {0, 1, 2, 3} and b = {9, 8, 7, 6} is the vector of pairs,
/// c = {(0,9), (1,8), (2,7), (3,6)}. Because the expectation is that each element
/// is matched with the element in the other data source at the same ordinal
/// position, the zip operator requires order preservation.
/// </summary>
/// <typeparam name="TLeftInput"></typeparam>
/// <typeparam name="TRightInput"></typeparam>
/// <typeparam name="TOutput"></typeparam>
internal sealed class ZipQueryOperator<TLeftInput, TRightInput, TOutput>
: QueryOperator<TOutput>
{
private readonly Func<TLeftInput, TRightInput, TOutput> m_resultSelector; // To select result elements.
private readonly QueryOperator<TLeftInput> m_leftChild;
private readonly QueryOperator<TRightInput> m_rightChild;
private readonly bool m_prematureMergeLeft = false; // Whether to prematurely merge the left data source
private readonly bool m_prematureMergeRight = false; // Whether to prematurely merge the right data source
private readonly bool m_limitsParallelism = false; // Whether this operator limits parallelism
//---------------------------------------------------------------------------------------
// Initializes a new zip operator.
//
// Arguments:
// leftChild - the left data source from which to pull data.
// rightChild - the right data source from which to pull data.
//
internal ZipQueryOperator(
ParallelQuery<TLeftInput> leftChildSource, IEnumerable<TRightInput> rightChildSource,
Func<TLeftInput, TRightInput, TOutput> resultSelector)
:this(
QueryOperator<TLeftInput>.AsQueryOperator(leftChildSource),
QueryOperator<TRightInput>.AsQueryOperator(rightChildSource),
resultSelector)
{
}
private ZipQueryOperator(
QueryOperator<TLeftInput> left, QueryOperator<TRightInput> right,
Func<TLeftInput, TRightInput, TOutput> resultSelector)
: base(left.SpecifiedQuerySettings.Merge(right.SpecifiedQuerySettings))
{
Contract.Assert(resultSelector != null, "operator cannot be null");
m_leftChild = left;
m_rightChild = right;
m_resultSelector = resultSelector;
m_outputOrdered = m_leftChild.OutputOrdered || m_rightChild.OutputOrdered;
OrdinalIndexState leftIndexState = m_leftChild.OrdinalIndexState;
OrdinalIndexState rightIndexState = m_rightChild.OrdinalIndexState;
m_prematureMergeLeft = leftIndexState != OrdinalIndexState.Indexible;
m_prematureMergeRight = rightIndexState != OrdinalIndexState.Indexible;
m_limitsParallelism =
(m_prematureMergeLeft && leftIndexState != OrdinalIndexState.Shuffled)
|| (m_prematureMergeRight && rightIndexState != OrdinalIndexState.Shuffled);
}
//---------------------------------------------------------------------------------------
// Just opens the current operator, including opening the children and wrapping them with
// partitions as needed.
//
internal override QueryResults<TOutput> Open(QuerySettings settings, bool preferStriping)
{
// We just open our child operators, left and then right.
QueryResults<TLeftInput> leftChildResults = m_leftChild.Open(settings, preferStriping);
QueryResults<TRightInput> rightChildResults = m_rightChild.Open(settings, preferStriping);
int partitionCount = settings.DegreeOfParallelism.Value;
if (m_prematureMergeLeft)
{
PartitionedStreamMerger<TLeftInput> merger = new PartitionedStreamMerger<TLeftInput>(
false, ParallelMergeOptions.FullyBuffered, settings.TaskScheduler, m_leftChild.OutputOrdered,
settings.CancellationState, settings.QueryId);
leftChildResults.GivePartitionedStream(merger);
leftChildResults = new ListQueryResults<TLeftInput>(
merger.MergeExecutor.GetResultsAsArray(), partitionCount, preferStriping);
}
if (m_prematureMergeRight)
{
PartitionedStreamMerger<TRightInput> merger = new PartitionedStreamMerger<TRightInput>(
false, ParallelMergeOptions.FullyBuffered, settings.TaskScheduler, m_rightChild.OutputOrdered,
settings.CancellationState, settings.QueryId);
rightChildResults.GivePartitionedStream(merger);
rightChildResults = new ListQueryResults<TRightInput>(
merger.MergeExecutor.GetResultsAsArray(), partitionCount, preferStriping);
}
return new ZipQueryOperatorResults(leftChildResults, rightChildResults, m_resultSelector, partitionCount, preferStriping);
}
//---------------------------------------------------------------------------------------
// Returns an enumerable that represents the query executing sequentially.
//
internal override IEnumerable<TOutput> AsSequentialQuery(CancellationToken token)
{
using(IEnumerator<TLeftInput> leftEnumerator = m_leftChild.AsSequentialQuery(token).GetEnumerator())
using(IEnumerator<TRightInput> rightEnumerator = m_rightChild.AsSequentialQuery(token).GetEnumerator())
{
while(leftEnumerator.MoveNext() && rightEnumerator.MoveNext())
{
yield return m_resultSelector(leftEnumerator.Current, rightEnumerator.Current);
}
}
}
//---------------------------------------------------------------------------------------
// The state of the order index of the results returned by this operator.
//
internal override OrdinalIndexState OrdinalIndexState
{
get
{
return OrdinalIndexState.Indexible;
}
}
//---------------------------------------------------------------------------------------
// Whether this operator performs a premature merge that would not be performed in
// a similar sequential operation (i.e., in LINQ to Objects).
//
internal override bool LimitsParallelism
{
get
{
return m_limitsParallelism;
}
}
//---------------------------------------------------------------------------------------
// A special QueryResults class for the Zip operator. It requires that both of the child
// QueryResults are indexible.
//
internal class ZipQueryOperatorResults : QueryResults<TOutput>
{
private readonly QueryResults<TLeftInput> m_leftChildResults;
private readonly QueryResults<TRightInput> m_rightChildResults;
private readonly Func<TLeftInput, TRightInput, TOutput> m_resultSelector; // To select result elements.
private readonly int m_count;
private readonly int m_partitionCount;
private readonly bool m_preferStriping;
internal ZipQueryOperatorResults(
QueryResults<TLeftInput> leftChildResults, QueryResults<TRightInput> rightChildResults,
Func<TLeftInput, TRightInput, TOutput> resultSelector, int partitionCount, bool preferStriping)
{
m_leftChildResults = leftChildResults;
m_rightChildResults = rightChildResults;
m_resultSelector = resultSelector;
m_partitionCount = partitionCount;
m_preferStriping = preferStriping;
Contract.Assert(m_leftChildResults.IsIndexible);
Contract.Assert(m_rightChildResults.IsIndexible);
m_count = Math.Min(m_leftChildResults.Count, m_rightChildResults.Count);
}
internal override int ElementsCount
{
get { return m_count; }
}
internal override bool IsIndexible
{
get { return true; }
}
internal override TOutput GetElement(int index)
{
return m_resultSelector(m_leftChildResults.GetElement(index), m_rightChildResults.GetElement(index));
}
internal override void GivePartitionedStream(IPartitionedStreamRecipient<TOutput> recipient)
{
PartitionedStream<TOutput, int> partitionedStream = ExchangeUtilities.PartitionDataSource(this, m_partitionCount, m_preferStriping);
recipient.Receive(partitionedStream);
}
}
}
}
| |
// 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.Data.Common;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using System.Runtime.Versioning;
namespace System.Data.OleDb
{
internal struct SchemaSupport
{
internal Guid _schemaRowset;
internal int _restrictions;
}
internal sealed class OleDbConnectionString : DbConnectionOptions
{
// instances of this class are intended to be immutable, i.e readonly
// used by pooling classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
internal static class KEY
{
internal const string Asynchronous_Processing = "asynchronous processing";
internal const string Connect_Timeout = "connect timeout";
internal const string Data_Provider = "data provider";
internal const string Data_Source = "data source";
internal const string Extended_Properties = "extended properties";
internal const string File_Name = "file name";
internal const string Initial_Catalog = "initial catalog";
internal const string Ole_DB_Services = "ole db services";
internal const string Persist_Security_Info = "persist security info";
internal const string Prompt = "prompt";
internal const string Provider = "provider";
internal const string RemoteProvider = "remote provider";
internal const string WindowHandle = "window handle";
}
// registry key and dword value entry for udl pooling
private static class UDL
{
internal const string Header = "\xfeff[oledb]\r\n; Everything after this line is an OLE DB initstring\r\n";
internal const string Location = "SOFTWARE\\Microsoft\\DataAccess\\Udl Pooling";
internal const string Pooling = "Cache Size";
static internal volatile bool _PoolSizeInit;
static internal int _PoolSize;
static internal volatile Dictionary<string, string> _Pool;
static internal object _PoolLock = new object();
}
private static class VALUES
{
internal const string NoPrompt = "noprompt";
}
// set during ctor
internal readonly bool PossiblePrompt;
internal readonly string ActualConnectionString; // cached value passed to GetDataSource
private readonly string _expandedConnectionString;
internal SchemaSupport[] _schemaSupport;
internal int _sqlSupport;
internal bool _supportMultipleResults;
internal bool _supportIRow;
internal bool _hasSqlSupport;
internal bool _hasSupportMultipleResults, _hasSupportIRow;
private int _oledbServices;
// these are cached delegates (per unique connectionstring)
internal UnsafeNativeMethods.IUnknownQueryInterface DangerousDataSourceIUnknownQueryInterface;
internal UnsafeNativeMethods.IDBInitializeInitialize DangerousIDBInitializeInitialize;
internal UnsafeNativeMethods.IDBCreateSessionCreateSession DangerousIDBCreateSessionCreateSession;
internal UnsafeNativeMethods.IDBCreateCommandCreateCommand DangerousIDBCreateCommandCreateCommand;
// since IDBCreateCommand interface may not be supported for a particular provider (only IOpenRowset)
// we cache that fact rather than call QueryInterface on every call to Open
internal bool HaveQueriedForCreateCommand;
// SxS: if user specifies a value for "File Name=" (UDL) in connection string, OleDbConnectionString will load the connection string
// from the UDL file. The UDL file is opened as FileMode.Open, FileAccess.Read, FileShare.Read, allowing concurrent access to it.
internal OleDbConnectionString(string connectionString, bool validate) : base(connectionString)
{
string prompt = this[KEY.Prompt];
PossiblePrompt = ((!ADP.IsEmpty(prompt) && (0 != String.Compare(prompt, VALUES.NoPrompt, StringComparison.OrdinalIgnoreCase)))
|| !ADP.IsEmpty(this[KEY.WindowHandle]));
if (!IsEmpty)
{
string udlConnectionString = null;
if (!validate)
{
int position = 0;
string udlFileName = null;
_expandedConnectionString = ExpandDataDirectories(ref udlFileName, ref position);
if (!ADP.IsEmpty(udlFileName))
{ // fail via new FileStream vs. GetFullPath
udlFileName = ADP.GetFullPath(udlFileName);
}
if (null != udlFileName)
{
udlConnectionString = LoadStringFromStorage(udlFileName);
if (!ADP.IsEmpty(udlConnectionString))
{
_expandedConnectionString = _expandedConnectionString.Substring(0, position) + udlConnectionString + ';' + _expandedConnectionString.Substring(position);
}
}
}
if (validate || ADP.IsEmpty(udlConnectionString))
{
ActualConnectionString = ValidateConnectionString(connectionString);
}
}
}
internal int ConnectTimeout
{
get { return base.ConvertValueToInt32(KEY.Connect_Timeout, ADP.DefaultConnectionTimeout); }
}
internal string DataSource
{
get { return base.ConvertValueToString(KEY.Data_Source, string.Empty); }
}
internal string InitialCatalog
{
get { return base.ConvertValueToString(KEY.Initial_Catalog, string.Empty); }
}
internal string Provider
{
get
{
Debug.Assert(!ADP.IsEmpty(this[KEY.Provider]), "no Provider");
return this[KEY.Provider];
}
}
internal int OleDbServices
{
get
{
return _oledbServices;
}
}
internal SchemaSupport[] SchemaSupport
{ // OleDbConnection.GetSchemaRowsetInformation
get { return _schemaSupport; }
set { _schemaSupport = value; }
}
protected internal override string Expand()
{
if (null != _expandedConnectionString)
{
return _expandedConnectionString;
}
else
{
return base.Expand();
}
}
internal int GetSqlSupport(OleDbConnection connection)
{
int sqlSupport = _sqlSupport;
if (!_hasSqlSupport)
{
object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_SQLSUPPORT);
if (value is Int32)
{ // not OleDbPropertyStatus
sqlSupport = (int)value;
}
_sqlSupport = sqlSupport;
_hasSqlSupport = true;
}
return sqlSupport;
}
internal bool GetSupportIRow(OleDbConnection connection, OleDbCommand command)
{
bool supportIRow = _supportIRow;
if (!_hasSupportIRow)
{
object value = command.GetPropertyValue(OleDbPropertySetGuid.Rowset, ODB.DBPROP_IRow);
// SQLOLEDB always returns VARIANT_FALSE for DBPROP_IROW, so base the answer on existance
supportIRow = !(value is OleDbPropertyStatus);
_supportIRow = supportIRow;
_hasSupportIRow = true;
}
return supportIRow;
}
internal bool GetSupportMultipleResults(OleDbConnection connection)
{
bool supportMultipleResults = _supportMultipleResults;
if (!_hasSupportMultipleResults)
{
object value = connection.GetDataSourcePropertyValue(OleDbPropertySetGuid.DataSourceInfo, ODB.DBPROP_MULTIPLERESULTS);
if (value is Int32)
{// not OleDbPropertyStatus
supportMultipleResults = (ODB.DBPROPVAL_MR_NOTSUPPORTED != (int)value);
}
_supportMultipleResults = supportMultipleResults;
_hasSupportMultipleResults = true;
}
return supportMultipleResults;
}
static private int UdlPoolSize
{
// SxS: UdpPoolSize reads registry value to get the pool size
get
{
int poolsize = UDL._PoolSize;
if (!UDL._PoolSizeInit)
{
object value = ADP.LocalMachineRegistryValue(UDL.Location, UDL.Pooling);
if (value is Int32)
{
poolsize = (int)value;
poolsize = ((0 < poolsize) ? poolsize : 0);
UDL._PoolSize = poolsize;
}
UDL._PoolSizeInit = true;
}
return poolsize;
}
}
static private string LoadStringFromStorage(string udlfilename)
{
string udlConnectionString = null;
Dictionary<string, string> udlcache = UDL._Pool;
if ((null == udlcache) || !udlcache.TryGetValue(udlfilename, out udlConnectionString))
{
udlConnectionString = LoadStringFromFileStorage(udlfilename);
if (null != udlConnectionString)
{
Debug.Assert(!ADP.IsEmpty(udlfilename), "empty filename didn't fail");
if (0 < UdlPoolSize)
{
Debug.Assert(udlfilename == ADP.GetFullPath(udlfilename), "only cache full path filenames");
if (null == udlcache)
{
udlcache = new Dictionary<string, string>();
udlcache[udlfilename] = udlConnectionString;
lock (UDL._PoolLock)
{
if (null != UDL._Pool)
{
udlcache = UDL._Pool;
}
else
{
UDL._Pool = udlcache;
udlcache = null;
}
}
}
if (null != udlcache)
{
lock (udlcache)
{
udlcache[udlfilename] = udlConnectionString;
}
}
}
}
}
return udlConnectionString;
}
static private string LoadStringFromFileStorage(string udlfilename)
{
// Microsoft Data Link File Format
// The first two lines of a .udl file must have exactly the following contents in order to work properly:
// [oledb]
// ; Everything after this line is an OLE DB initstring
//
string connectionString = null;
Exception failure = null;
try
{
int hdrlength = ADP.CharSize * UDL.Header.Length;
using (FileStream fstream = new FileStream(udlfilename, FileMode.Open, FileAccess.Read, FileShare.Read))
{
long length = fstream.Length;
if (length < hdrlength || (0 != length % ADP.CharSize))
{
failure = ADP.InvalidUDL();
}
else
{
byte[] bytes = new Byte[hdrlength];
int count = fstream.Read(bytes, 0, bytes.Length);
if (count < hdrlength)
{
failure = ADP.InvalidUDL();
}
else if (System.Text.Encoding.Unicode.GetString(bytes, 0, hdrlength) != UDL.Header)
{
failure = ADP.InvalidUDL();
}
else
{ // please verify header before allocating memory block for connection string
bytes = new Byte[length - hdrlength];
count = fstream.Read(bytes, 0, bytes.Length);
connectionString = System.Text.Encoding.Unicode.GetString(bytes, 0, count);
}
}
}
}
catch (Exception e)
{
// UNDONE - should not be catching all exceptions!!!
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
throw ADP.UdlFileError(e);
}
if (null != failure)
{
throw failure;
}
return connectionString.Trim();
}
private string ValidateConnectionString(string connectionString)
{
if (ConvertValueToBoolean(KEY.Asynchronous_Processing, false))
{
throw ODB.AsynchronousNotSupported();
}
int connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, 0);
if (connectTimeout < 0)
{
throw ADP.InvalidConnectTimeoutValue();
}
string progid = ConvertValueToString(KEY.Data_Provider, null);
if (null != progid)
{
progid = progid.Trim();
if (0 < progid.Length)
{ // don't fail on empty 'Data Provider' value
ValidateProvider(progid);
}
}
progid = ConvertValueToString(KEY.RemoteProvider, null);
if (null != progid)
{
progid = progid.Trim();
if (0 < progid.Length)
{ // don't fail on empty 'Data Provider' value
ValidateProvider(progid);
}
}
progid = ConvertValueToString(KEY.Provider, string.Empty).Trim();
ValidateProvider(progid); // will fail on empty 'Provider' value
// initialize to default
// If the value is not provided in connection string and OleDbServices registry key has not been set by the provider,
// the default for the provider is -1 (all services are ON).
// our default is -13, we turn off ODB.DBPROPVAL_OS_AGR_AFTERSESSION and ODB.DBPROPVAL_OS_CLIENTCURSOR flags
_oledbServices = DbConnectionStringDefaults.OleDbServices;
bool hasOleDBServices = (base.ContainsKey(KEY.Ole_DB_Services) && !ADP.IsEmpty((string)base[KEY.Ole_DB_Services]));
if (!hasOleDBServices)
{ // don't touch registry if they have OLE DB Services
string classid = (string)ADP.ClassesRootRegistryValue(progid + "\\CLSID", String.Empty);
if ((null != classid) && (0 < classid.Length))
{
// CLSID detection of 'Microsoft OLE DB Provider for ODBC Drivers'
Guid classidProvider = new Guid(classid);
if (ODB.CLSID_MSDASQL == classidProvider)
{
throw ODB.MSDASQLNotSupported();
}
object tmp = ADP.ClassesRootRegistryValue("CLSID\\{" + classidProvider.ToString("D", CultureInfo.InvariantCulture) + "}", ODB.OLEDB_SERVICES);
if (null != tmp)
{
// @devnote: some providers like MSDataShape don't have the OLEDB_SERVICES value
// the MSDataShape provider doesn't support the 'Ole Db Services' keyword
// hence, if the value doesn't exist - don't prepend to string
try
{
_oledbServices = (int)tmp;
}
catch (InvalidCastException e)
{
ADP.TraceExceptionWithoutRethrow(e);
}
_oledbServices &= ~(ODB.DBPROPVAL_OS_AGR_AFTERSESSION | ODB.DBPROPVAL_OS_CLIENTCURSOR);
StringBuilder builder = new StringBuilder();
builder.Append(KEY.Ole_DB_Services);
builder.Append("=");
builder.Append(_oledbServices.ToString(CultureInfo.InvariantCulture));
builder.Append(";");
builder.Append(connectionString);
connectionString = builder.ToString();
}
}
}
else
{
// parse the Ole Db Services value from connection string
_oledbServices = ConvertValueToInt32(KEY.Ole_DB_Services, DbConnectionStringDefaults.OleDbServices);
}
return connectionString;
}
internal static bool IsMSDASQL(string progid)
{
return (("msdasql" == progid) || progid.StartsWith("msdasql.", StringComparison.Ordinal) || ("microsoft ole db provider for odbc drivers" == progid));
}
static private void ValidateProvider(string progid)
{
if (ADP.IsEmpty(progid))
{
throw ODB.NoProviderSpecified();
}
if (ODB.MaxProgIdLength <= progid.Length)
{
throw ODB.InvalidProviderSpecified();
}
progid = progid.ToLower(CultureInfo.InvariantCulture);
if (IsMSDASQL(progid))
{
// fail msdasql even if not on the machine.
throw ODB.MSDASQLNotSupported();
}
}
static internal void ReleaseObjectPool()
{
UDL._PoolSizeInit = false;
UDL._Pool = null;
}
}
}
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Moq.Tests
{
public class MockBehaviorFixture
{
[Fact]
public void ShouldThrowIfStrictNoExpectation()
{
var mock = new Mock<IFoo>(MockBehavior.Strict);
try
{
mock.Object.Do();
Assert.True(false, "Should have thrown for unexpected call with MockBehavior.Strict");
}
catch (MockException mex)
{
Assert.Equal(MockExceptionReasons.NoSetup, mex.Reasons);
}
}
[Fact]
public void ShouldReturnDefaultForLooseBehaviorOnInterface()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.Equal(0, mock.Object.Get());
Assert.Null(mock.Object.GetObject());
}
[Fact]
public void ShouldReturnDefaultForLooseBehaviorOnAbstract()
{
var mock = new Mock<Foo>(MockBehavior.Loose);
Assert.Equal(0, mock.Object.AbstractGet());
Assert.Null(mock.Object.GetObject());
}
[Fact]
public void ShouldReturnEmptyArrayOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.NotNull(mock.Object.GetArray());
Assert.Empty(mock.Object.GetArray());
}
[Fact]
public void ShouldReturnEmptyArrayTwoDimensionsOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.NotNull(mock.Object.GetArrayTwoDimensions());
Assert.Empty(mock.Object.GetArrayTwoDimensions());
}
[Fact]
public void ShouldReturnNullListOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.Null(mock.Object.GetList());
}
[Fact]
public void ShouldReturnEmptyEnumerableStringOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.NotNull(mock.Object.GetEnumerable());
Assert.Empty(mock.Object.GetEnumerable());
}
[Fact]
public void ShouldReturnEmptyEnumerableObjectsOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.NotNull(mock.Object.GetEnumerableObjects());
Assert.Empty(mock.Object.GetEnumerableObjects().Cast<object>());
}
[Fact]
public void ShouldReturnDefaultGuidOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.Equal(default(Guid), mock.Object.GetGuid());
}
[Fact]
public void ShouldReturnNullStringOnLoose()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
Assert.Null(mock.Object.DoReturnString());
}
[Fact]
public void ShouldReturnNullStringOnLooseWithExpect()
{
var mock = new Mock<IFoo>(MockBehavior.Loose);
mock.Setup(x => x.DoReturnString());
Assert.Null(mock.Object.DoReturnString());
}
[Fact]
public void ReturnsMockDefaultValueForLooseBehaviorOnInterface()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
var value = mock.Object.GetObject();
Assert.True(value is IMocked);
}
[Fact]
public void ReturnsMockDefaultValueForLooseBehaviorOnAbstract()
{
var mock = new Mock<Foo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
var value = mock.Object.Bar;
Assert.True(value is IMocked);
value = mock.Object.GetBar();
Assert.True(value is IMocked);
}
[Fact]
public void ReturnsEmptyArrayOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetArray());
Assert.Empty(mock.Object.GetArray());
}
[Fact]
public void ReturnsEmptyArrayTwoDimensionsOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetArrayTwoDimensions());
Assert.Empty(mock.Object.GetArrayTwoDimensions());
}
[Fact]
public void ReturnsMockListOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetList());
var list = mock.Object.GetList();
list.Add("foo");
Assert.Equal("foo", list[0]);
}
[Fact]
public void ReturnsEmptyEnumerableStringOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetEnumerable());
Assert.Empty(mock.Object.GetEnumerable());
}
[Fact]
public void ReturnsEmptyQueryableStringOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetQueryable());
Assert.Equal(0, mock.Object.GetQueryable().Count());
}
[Fact]
public void ReturnsEmptyEnumerableObjectsOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetEnumerableObjects());
Assert.Empty(mock.Object.GetEnumerableObjects().Cast<object>());
}
[Fact]
public void ReturnsEmptyQueryableObjectsOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.NotNull(mock.Object.GetQueryableObjects());
Assert.Equal(0, mock.Object.GetQueryableObjects().Cast<object>().Count());
}
[Fact]
public void ReturnsDefaultGuidOnLooseWithMockDefaultValueWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.Equal(default(Guid), mock.Object.GetGuid());
}
[Fact]
public void ReturnsNullStringOnLooseWithMockDefaultValue()
{
var mock = new Mock<IFoo>(MockBehavior.Loose) { DefaultValue = DefaultValue.Mock };
Assert.Null(mock.Object.DoReturnString());
}
public interface IFoo
{
void Do();
int Get();
Guid GetGuid();
object GetObject();
string[] GetArray();
string[][] GetArrayTwoDimensions();
List<string> GetList();
IEnumerable<string> GetEnumerable();
IEnumerable GetEnumerableObjects();
string DoReturnString();
IQueryable<string> GetQueryable();
IQueryable GetQueryableObjects();
}
public interface IBar { }
public abstract class Foo : IFoo
{
public abstract IBar Bar { get; set; }
public abstract IBar GetBar();
public abstract void Do();
public abstract object GetObject();
public abstract string DoReturnString();
public void DoNonVirtual() { }
public virtual void DoVirtual() { }
public int NonVirtualGet()
{
return 0;
}
public int VirtualGet()
{
return 0;
}
public virtual int Get()
{
return AbstractGet();
}
public abstract int AbstractGet();
public string[] GetArray()
{
return new string[0];
}
public string[][] GetArrayTwoDimensions()
{
return new string[0][];
}
public List<string> GetList()
{
return null;
}
public IEnumerable<string> GetEnumerable()
{
return new string[0];
}
public IEnumerable GetEnumerableObjects()
{
return new object[0];
}
public Guid GetGuid()
{
return default(Guid);
}
public IQueryable<string> GetQueryable()
{
return new string[0].AsQueryable();
}
public IQueryable GetQueryableObjects()
{
return new object[0].AsQueryable();
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Globalization;
using System.IO;
using System.Runtime;
using System.Runtime.Diagnostics;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Diagnostics.Application;
using System.Text;
using System.Xml;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using System.Net.Http.Headers;
namespace System.ServiceModel.Channels
{
internal class TextMessageEncoderFactory : MessageEncoderFactory
{
private TextMessageEncoder _messageEncoder;
internal static ContentEncoding[] Soap11Content = GetContentEncodingMap(MessageVersion.Soap11WSAddressing10);
internal static ContentEncoding[] Soap12Content = GetContentEncodingMap(MessageVersion.Soap12WSAddressing10);
internal static ContentEncoding[] SoapNoneContent = GetContentEncodingMap(MessageVersion.None);
internal const string Soap11MediaType = "text/xml";
internal const string Soap12MediaType = "application/soap+xml";
private const string XmlMediaType = "application/xml";
public TextMessageEncoderFactory(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas)
{
_messageEncoder = new TextMessageEncoder(version, writeEncoding, maxReadPoolSize, maxWritePoolSize, quotas);
}
public override MessageEncoder Encoder
{
get { return _messageEncoder; }
}
public override MessageVersion MessageVersion
{
get { return _messageEncoder.MessageVersion; }
}
public int MaxWritePoolSize
{
get { return _messageEncoder.MaxWritePoolSize; }
}
public int MaxReadPoolSize
{
get { return _messageEncoder.MaxReadPoolSize; }
}
public static Encoding[] GetSupportedEncodings()
{
Encoding[] supported = TextEncoderDefaults.SupportedEncodings;
Encoding[] enc = new Encoding[supported.Length];
Array.Copy(supported, enc, supported.Length);
return enc;
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _messageEncoder.ReaderQuotas;
}
}
internal static string GetMediaType(MessageVersion version)
{
string mediaType = null;
if (version.Envelope == EnvelopeVersion.Soap12)
{
mediaType = TextMessageEncoderFactory.Soap12MediaType;
}
else if (version.Envelope == EnvelopeVersion.Soap11)
{
mediaType = TextMessageEncoderFactory.Soap11MediaType;
}
else if (version.Envelope == EnvelopeVersion.None)
{
mediaType = TextMessageEncoderFactory.XmlMediaType;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.EnvelopeVersionNotSupported, version.Envelope)));
}
return mediaType;
}
internal static string GetContentType(string mediaType, Encoding encoding)
{
return String.Format(CultureInfo.InvariantCulture, "{0}; charset={1}", mediaType, TextEncoderDefaults.EncodingToCharSet(encoding));
}
private static ContentEncoding[] GetContentEncodingMap(MessageVersion version)
{
Encoding[] readEncodings = TextMessageEncoderFactory.GetSupportedEncodings();
string media = GetMediaType(version);
ContentEncoding[] map = new ContentEncoding[readEncodings.Length];
for (int i = 0; i < readEncodings.Length; i++)
{
ContentEncoding contentEncoding = new ContentEncoding();
contentEncoding.contentType = GetContentType(media, readEncodings[i]);
contentEncoding.encoding = readEncodings[i];
map[i] = contentEncoding;
}
return map;
}
internal static Encoding GetEncodingFromContentType(string contentType, ContentEncoding[] contentMap)
{
if (contentType == null)
{
return null;
}
// Check for known/expected content types
for (int i = 0; i < contentMap.Length; i++)
{
if (contentMap[i].contentType == contentType)
{
return contentMap[i].encoding;
}
}
// then some heuristic matches (since System.Mime.ContentType is a performance hit)
// start by looking for a parameter.
// If none exists, we don't have an encoding
int semiColonIndex = contentType.IndexOf(';');
if (semiColonIndex == -1)
{
return null;
}
// optimize for charset being the first parameter
int charsetValueIndex = -1;
// for Indigo scenarios, we'll have "; charset=", so check for the c
if ((contentType.Length > semiColonIndex + 11) // need room for parameter + charset + '='
&& contentType[semiColonIndex + 2] == 'c'
&& string.Compare("charset=", 0, contentType, semiColonIndex + 2, 8, StringComparison.OrdinalIgnoreCase) == 0)
{
charsetValueIndex = semiColonIndex + 10;
}
else
{
// look for charset= somewhere else in the message
int paramIndex = contentType.IndexOf("charset=", semiColonIndex + 1, StringComparison.OrdinalIgnoreCase);
if (paramIndex != -1)
{
// validate there's only whitespace or semi-colons beforehand
for (int i = paramIndex - 1; i >= semiColonIndex; i--)
{
if (contentType[i] == ';')
{
charsetValueIndex = paramIndex + 8;
break;
}
if (contentType[i] == '\n')
{
if (i == semiColonIndex || contentType[i - 1] != '\r')
{
break;
}
i--;
continue;
}
if (contentType[i] != ' '
&& contentType[i] != '\t')
{
break;
}
}
}
}
string charSet;
Encoding enc;
// we have a possible charset value. If it's easy to parse, do so
if (charsetValueIndex != -1)
{
// get the next semicolon
semiColonIndex = contentType.IndexOf(';', charsetValueIndex);
if (semiColonIndex == -1)
{
charSet = contentType.Substring(charsetValueIndex);
}
else
{
charSet = contentType.Substring(charsetValueIndex, semiColonIndex - charsetValueIndex);
}
// and some minimal quote stripping
if (charSet.Length > 2 && charSet[0] == '"' && charSet[charSet.Length - 1] == '"')
{
charSet = charSet.Substring(1, charSet.Length - 2);
}
if (TryGetEncodingFromCharSet(charSet, out enc))
{
return enc;
}
}
// our quick heuristics failed. fall back to System.Net
try
{
MediaTypeHeaderValue parsedContentType = MediaTypeHeaderValue.Parse(contentType);
charSet = parsedContentType.CharSet;
}
catch (FormatException e)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.EncoderBadContentType, e));
}
if (TryGetEncodingFromCharSet(charSet, out enc))
return enc;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(SR.Format(SR.EncoderUnrecognizedCharSet, charSet)));
}
internal static bool TryGetEncodingFromCharSet(string charSet, out Encoding encoding)
{
encoding = null;
if (charSet == null || charSet.Length == 0)
return true;
return TextEncoderDefaults.TryGetEncoding(charSet, out encoding);
}
internal class ContentEncoding
{
internal string contentType;
internal Encoding encoding;
}
internal class TextMessageEncoder : MessageEncoder
{
private int _maxReadPoolSize;
private int _maxWritePoolSize;
// Double-checked locking pattern requires volatile for read/write synchronization
private volatile SynchronizedPool<UTF8BufferedMessageData> _bufferedReaderPool;
private volatile SynchronizedPool<TextBufferedMessageWriter> _bufferedWriterPool;
private volatile SynchronizedPool<RecycledMessageState> _recycledStatePool;
private object _thisLock;
private string _contentType;
private string _mediaType;
private Encoding _writeEncoding;
private MessageVersion _version;
private bool _optimizeWriteForUTF8;
private const int maxPooledXmlReadersPerMessage = 2;
private XmlDictionaryReaderQuotas _readerQuotas;
private XmlDictionaryReaderQuotas _bufferedReadReaderQuotas;
private ContentEncoding[] _contentEncodingMap;
public TextMessageEncoder(MessageVersion version, Encoding writeEncoding, int maxReadPoolSize, int maxWritePoolSize, XmlDictionaryReaderQuotas quotas)
{
if (version == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("version");
if (writeEncoding == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writeEncoding");
TextEncoderDefaults.ValidateEncoding(writeEncoding);
_writeEncoding = writeEncoding;
_optimizeWriteForUTF8 = IsUTF8Encoding(writeEncoding);
_thisLock = new object();
_version = version;
_maxReadPoolSize = maxReadPoolSize;
_maxWritePoolSize = maxWritePoolSize;
_readerQuotas = new XmlDictionaryReaderQuotas();
quotas.CopyTo(_readerQuotas);
_bufferedReadReaderQuotas = EncoderHelpers.GetBufferedReadQuotas(_readerQuotas);
_mediaType = TextMessageEncoderFactory.GetMediaType(version);
_contentType = TextMessageEncoderFactory.GetContentType(_mediaType, writeEncoding);
if (version.Envelope == EnvelopeVersion.Soap12)
{
_contentEncodingMap = TextMessageEncoderFactory.Soap12Content;
}
else if (version.Envelope == EnvelopeVersion.Soap11)
{
// public profile does not allow SOAP1.1/WSA1.0. However, the EnvelopeVersion 1.1 is supported. Need to know what the implications are here
// but I think that it's not necessary to have here since we're a sender in N only.
_contentEncodingMap = TextMessageEncoderFactory.Soap11Content;
}
else if (version.Envelope == EnvelopeVersion.None)
{
_contentEncodingMap = TextMessageEncoderFactory.SoapNoneContent;
}
else
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
SR.Format(SR.EnvelopeVersionNotSupported, version.Envelope)));
}
}
private static bool IsUTF8Encoding(Encoding encoding)
{
return encoding.WebName == "utf-8";
}
public override string ContentType
{
get { return _contentType; }
}
public int MaxWritePoolSize
{
get { return _maxWritePoolSize; }
}
public int MaxReadPoolSize
{
get { return _maxReadPoolSize; }
}
public XmlDictionaryReaderQuotas ReaderQuotas
{
get
{
return _readerQuotas;
}
}
public override string MediaType
{
get { return _mediaType; }
}
public override MessageVersion MessageVersion
{
get { return _version; }
}
private object ThisLock
{
get { return _thisLock; }
}
internal override bool IsCharSetSupported(string charSet)
{
Encoding tmp;
return TextEncoderDefaults.TryGetEncoding(charSet, out tmp);
}
public override bool IsContentTypeSupported(string contentType)
{
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
if (base.IsContentTypeSupported(contentType))
{
return true;
}
// we support a few extra content types for "none"
if (MessageVersion == MessageVersion.None)
{
const string rss1MediaType = "text/xml";
const string rss2MediaType = "application/rss+xml";
const string atomMediaType = "application/atom+xml";
const string htmlMediaType = "text/html";
if (IsContentTypeSupported(contentType, rss1MediaType, rss1MediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, rss2MediaType, rss2MediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, htmlMediaType, atomMediaType))
{
return true;
}
if (IsContentTypeSupported(contentType, atomMediaType, atomMediaType))
{
return true;
}
// application/xml checked by base method
}
return false;
}
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
{
if (bufferManager == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("bufferManager"));
if (TD.TextMessageDecodingStartIsEnabled())
{
TD.TextMessageDecodingStart();
}
Message message;
UTF8BufferedMessageData messageData = TakeBufferedReader();
messageData.Encoding = GetEncodingFromContentType(contentType, _contentEncodingMap);
messageData.Open(buffer, bufferManager);
RecycledMessageState messageState = messageData.TakeMessageState();
if (messageState == null)
messageState = new RecycledMessageState();
message = new BufferedMessage(messageData, messageState);
message.Properties.Encoder = this;
if (TD.MessageReadByEncoderIsEnabled())
{
TD.MessageReadByEncoder(
EventTraceActivityHelper.TryExtractActivity(message, true),
buffer.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
return message;
}
public override Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType)
{
if (stream == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("stream"));
if (TD.TextMessageDecodingStartIsEnabled())
{
TD.TextMessageDecodingStart();
}
XmlReader reader = TakeStreamedReader(stream, GetEncodingFromContentType(contentType, _contentEncodingMap));
Message message = Message.CreateMessage(reader, maxSizeOfHeaders, _version);
message.Properties.Encoder = this;
if (TD.StreamedMessageReadByEncoderIsEnabled())
{
TD.StreamedMessageReadByEncoder(EventTraceActivityHelper.TryExtractActivity(message, true));
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportReceive);
return message;
}
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
return WriteMessageAsync(message, maxMessageSize, bufferManager, messageOffset).WaitForCompletion();
}
public override void WriteMessage(Message message, Stream stream)
{
WriteMessageAsyncInternal(message, stream).WaitForCompletion();
}
public override Task<ArraySegment<byte>> WriteMessageAsync(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (bufferManager == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("bufferManager"), message);
if (maxMessageSize < 0)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("maxMessageSize", maxMessageSize,
SR.ValueMustBeNonNegative), message);
if (messageOffset < 0 || messageOffset > maxMessageSize)
throw TraceUtility.ThrowHelperError(new ArgumentOutOfRangeException("messageOffset", messageOffset,
SR.Format(SR.ValueMustBeInRange, 0, maxMessageSize)), message);
ThrowIfMismatchedMessageVersion(message);
EventTraceActivity eventTraceActivity = null;
if (TD.TextMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.TextMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
TextBufferedMessageWriter messageWriter = TakeBufferedWriter();
ArraySegment<byte> messageData = messageWriter.WriteMessage(message, bufferManager, messageOffset, maxMessageSize);
ReturnMessageWriter(messageWriter);
if (TD.MessageWrittenByEncoderIsEnabled())
{
TD.MessageWrittenByEncoder(
eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message),
messageData.Count,
this);
}
if (MessageLogger.LogMessagesAtTransportLevel)
{
XmlDictionaryReader xmlDictionaryReader = XmlDictionaryReader.CreateTextReader(messageData.Array, messageData.Offset, messageData.Count, XmlDictionaryReaderQuotas.Max);
MessageLogger.LogMessage(ref message, xmlDictionaryReader, MessageLoggingSource.TransportSend);
}
return Task.FromResult(messageData);
}
private async Task WriteMessageAsyncInternal(Message message, Stream stream)
{
await TaskHelpers.EnsureDefaultTaskScheduler();
await WriteMessageAsync(message, stream);
}
public override async Task WriteMessageAsync(Message message, Stream stream)
{
if (message == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("message"));
if (stream == null)
throw TraceUtility.ThrowHelperError(new ArgumentNullException("stream"), message);
ThrowIfMismatchedMessageVersion(message);
EventTraceActivity eventTraceActivity = null;
if (TD.TextMessageEncodingStartIsEnabled())
{
eventTraceActivity = EventTraceActivityHelper.TryExtractActivity(message);
TD.TextMessageEncodingStart(eventTraceActivity);
}
message.Properties.Encoder = this;
XmlDictionaryWriter xmlWriter = TakeStreamedWriter(stream);
if (_optimizeWriteForUTF8)
{
await message.WriteMessageAsync(xmlWriter);
}
else
{
xmlWriter.WriteStartDocument();
await message.WriteMessageAsync(xmlWriter);
xmlWriter.WriteEndDocument();
}
await xmlWriter.FlushAsync();
ReturnStreamedWriter(xmlWriter);
if (TD.StreamedMessageWrittenByEncoderIsEnabled())
{
TD.StreamedMessageWrittenByEncoder(eventTraceActivity ?? EventTraceActivityHelper.TryExtractActivity(message));
}
if (MessageLogger.LogMessagesAtTransportLevel)
MessageLogger.LogMessage(ref message, MessageLoggingSource.TransportSend);
}
public override IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state)
{
return this.WriteMessageAsync(message, stream).ToApm(callback, state);
}
public override void EndWriteMessage(IAsyncResult result)
{
result.ToApmEnd();
}
private XmlDictionaryWriter TakeStreamedWriter(Stream stream)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _writeEncoding, false);
}
private void ReturnStreamedWriter(XmlWriter xmlWriter)
{
Contract.Assert(xmlWriter != null, "xmlWriter MUST NOT be null");
xmlWriter.Flush();
xmlWriter.Dispose();
}
private TextBufferedMessageWriter TakeBufferedWriter()
{
if (_bufferedWriterPool == null)
{
lock (ThisLock)
{
if (_bufferedWriterPool == null)
{
_bufferedWriterPool = new SynchronizedPool<TextBufferedMessageWriter>(_maxWritePoolSize);
}
}
}
TextBufferedMessageWriter messageWriter = _bufferedWriterPool.Take();
if (messageWriter == null)
{
messageWriter = new TextBufferedMessageWriter(this);
if (TD.WritePoolMissIsEnabled())
{
TD.WritePoolMiss(messageWriter.GetType().Name);
}
}
return messageWriter;
}
private void ReturnMessageWriter(TextBufferedMessageWriter messageWriter)
{
_bufferedWriterPool.Return(messageWriter);
}
private XmlReader TakeStreamedReader(Stream stream, Encoding enc)
{
return XmlDictionaryReader.CreateTextReader(stream, _readerQuotas);
}
private XmlDictionaryWriter CreateWriter(Stream stream)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _writeEncoding, false);
}
private UTF8BufferedMessageData TakeBufferedReader()
{
if (_bufferedReaderPool == null)
{
lock (ThisLock)
{
if (_bufferedReaderPool == null)
{
_bufferedReaderPool = new SynchronizedPool<UTF8BufferedMessageData>(_maxReadPoolSize);
}
}
}
UTF8BufferedMessageData messageData = _bufferedReaderPool.Take();
if (messageData == null)
{
messageData = new UTF8BufferedMessageData(this, maxPooledXmlReadersPerMessage);
if (TD.ReadPoolMissIsEnabled())
{
TD.ReadPoolMiss(messageData.GetType().Name);
}
}
return messageData;
}
private void ReturnBufferedData(UTF8BufferedMessageData messageData)
{
_bufferedReaderPool.Return(messageData);
}
private SynchronizedPool<RecycledMessageState> RecycledStatePool
{
get
{
if (_recycledStatePool == null)
{
lock (ThisLock)
{
if (_recycledStatePool == null)
{
_recycledStatePool = new SynchronizedPool<RecycledMessageState>(_maxReadPoolSize);
}
}
}
return _recycledStatePool;
}
}
private static readonly byte[] s_xmlDeclarationStartText = { (byte)'<', (byte)'?', (byte)'x', (byte)'m', (byte)'l' };
private static readonly byte[] s_version10Text = { (byte)'v', (byte)'e', (byte)'r', (byte)'s', (byte)'i', (byte)'o', (byte)'n', (byte)'=', (byte)'"', (byte)'1', (byte)'.', (byte)'0', (byte)'"' };
private static readonly byte[] s_encodingText = { (byte)'e', (byte)'n', (byte)'c', (byte)'o', (byte)'d', (byte)'i', (byte)'n', (byte)'g', (byte)'=' };
internal class UTF8BufferedMessageData : BufferedMessageData
{
private TextMessageEncoder _messageEncoder;
private Encoding _encoding;
private const int additionalNodeSpace = 1024;
public UTF8BufferedMessageData(TextMessageEncoder messageEncoder, int maxReaderPoolSize)
: base(messageEncoder.RecycledStatePool)
{
_messageEncoder = messageEncoder;
}
internal Encoding Encoding
{
set
{
_encoding = value;
}
}
public override MessageEncoder MessageEncoder
{
get { return _messageEncoder; }
}
public override XmlDictionaryReaderQuotas Quotas
{
get { return _messageEncoder._bufferedReadReaderQuotas; }
}
protected override void OnClosed()
{
_messageEncoder.ReturnBufferedData(this);
}
protected override XmlDictionaryReader TakeXmlReader()
{
ArraySegment<byte> buffer = this.Buffer;
return XmlDictionaryReader.CreateTextReader(buffer.Array, buffer.Offset, buffer.Count, this.Quotas);
}
protected override void ReturnXmlReader(XmlDictionaryReader xmlReader)
{
Contract.Assert(xmlReader != null, "xmlReader MUST NOT be null");
xmlReader.Dispose();
}
}
internal class TextBufferedMessageWriter : BufferedMessageWriter
{
private TextMessageEncoder _messageEncoder;
public TextBufferedMessageWriter(TextMessageEncoder messageEncoder)
{
_messageEncoder = messageEncoder;
}
protected override void OnWriteStartMessage(XmlDictionaryWriter writer)
{
if (!_messageEncoder._optimizeWriteForUTF8)
writer.WriteStartDocument();
}
protected override void OnWriteEndMessage(XmlDictionaryWriter writer)
{
if (!_messageEncoder._optimizeWriteForUTF8)
writer.WriteEndDocument();
}
protected override XmlDictionaryWriter TakeXmlWriter(Stream stream)
{
if (_messageEncoder._optimizeWriteForUTF8)
{
return XmlDictionaryWriter.CreateTextWriter(stream, _messageEncoder._writeEncoding, false);
}
else
{
return _messageEncoder.CreateWriter(stream);
}
}
protected override void ReturnXmlWriter(XmlDictionaryWriter writer)
{
Contract.Assert(writer != null, "writer MUST NOT be null");
writer.Flush();
writer.Dispose();
}
}
}
}
}
| |
namespace iTin.Export.Model
{
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.UI;
using System.Xml.Serialization;
using AspNet;
using ComponentModel.Writer;
using Helpers;
/// <inheritdoc />
/// <summary>
/// A Specialization of <see cref="T:iTin.Export.Model.BaseBehaviorModel" /> class.<br />
/// Which Represents a email behavior.
/// </summary>
/// <remarks>
/// <para>Belongs to: <strong><c>Behaviors</c></strong>. For more information, please see <see cref="T:iTin.Export.Model.BehaviorsModel" />.<br />
/// <code lang="xml" title="ITEE Object Element Usage">
/// <Mail .../>
/// <Server/>
/// <Messages/>
/// </Mail>
/// </code>
/// </para>
/// <para><strong>Attributes</strong></para>
/// <table>
/// <thead>
/// <tr>
/// <th>Attribute</th>
/// <th>Optional</th>
/// <th>Description</th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td><see cref="P:iTin.Export.Model.BaseBehaviorModel.CanExecute" /></td>
/// <td align="center">Yes</td>
/// <td>Determines whether executes behavior. The default is <see cref="F:iTin.Export.Model.YesNo.Yes" />.</td>
/// </tr>
/// <tr>
/// <td><see cref="P:iTin.Export.Model.MailBehaviorModel.Async" /></td>
/// <td align="center">Yes</td>
/// <td>Determines whether to execute asynchronously the behavior. The default is <see cref="F:iTin.Export.Model.YesNo.Yes" />.</td>
/// </tr>
/// </tbody>
/// </table>
/// <para><strong>Elements</strong></para>
/// <list type="table">
/// <listheader>
/// <term>Element</term>
/// <description>Description</description>
/// </listheader>
/// <item>
/// <term><see cref="P:iTin.Export.Model.MailBehaviorModel.Server" /></term>
/// <description>Mail server configuration.</description>
/// </item>
/// <item>
/// <term><see cref="P:iTin.Export.Model.MailBehaviorModel.Messages" /></term>
/// <description>Collection of e-mail messages. Each element represents an e-mail message.</description>
/// </item>
/// </list>
/// <para>
/// <para><strong>Compatibility table with native writers.</strong></para>
/// <table>
/// <thead>
/// <tr>
/// <th>Comma-Separated Values<br /><see cref="T:iTin.Export.Writers.CsvWriter" /></th>
/// <th>Tab-Separated Values<br /><see cref="T:iTin.Export.Writers.TsvWriter" /></th>
/// <th>SQL Script<br /><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th>
/// <th>XML Spreadsheet 2003<br /><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// </tr>
/// </tbody>
/// </table>
/// A <strong><c>X</c></strong> value indicates that the writer supports this element.
/// </para>
/// </remarks>
/// <example>
/// <code lang="xml">
/// <Behaviors>
/// <Downdload LocalCopy="Yes"/>
/// <TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/>
/// <Mail Execute="Yes" Async="Yes" >
/// <Server>
/// <Credentials>
/// <Credential SSL="Yes" Name="one" UserName="address@gmail.com" password="pwd" Host="smtp.gmail.com"/>
/// </Credentials>
/// </Server>
/// <Messages>
/// <Message Credential="one" Send="Yes">
/// <From Address="emailaddress-one@gmail.com"/>
/// <To Addresses="emailaddress-two@hotmail.com emailaddress-three@hotmail.com"/>
/// <CC Addresses="emailaddress-four@hotmail.com emailaddress-five@hotmail.com"/>
/// <Subject>New report</Subject>
/// <Body>Hello, this is your report, sending from iTin.Export</Body>
/// <Attachments>
/// <Attachment Path="C:\Users\somefile.txt"/>
/// <Attachment Path="C:\Users\Downloads\Photos Sample.zip"/>
/// </Attachments>
/// </Message>
/// </Messages>
/// </Mail>
/// </Behaviors>
/// </code>
/// </example>
public partial class MailBehaviorModel
{
#region private constants
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private const YesNo DefaultAsync = YesNo.Yes;
#endregion
#region field members
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private YesNo _async;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private BehaviorsModel _parent;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private MailServerModel _server;
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private MailMessagesModel _messages;
#endregion
#region constructor/s
#region [public] MailBehaviorModel(): Initializes a new instance of this class
/// <inheritdoc />
/// <summary>
/// Initializes a new instance of the <see cref="T:iTin.Export.Model.MailBehaviorModel" /> class.
/// </summary>
public MailBehaviorModel()
{
Async = DefaultAsync;
}
#endregion
#endregion
#region public static properties
#region [public] {static} (MailBehaviorModel) Default: Gets a reference to default behavior
/// <summary>
/// Gets a reference to default behavior.
/// </summary>
/// <value>
/// Default behavior.
/// </value>
public static MailBehaviorModel Default => new MailBehaviorModel();
#endregion
#endregion
#region public properties
#region [public] (YesNo) Async: Gets or sets a value indicating whether to execute asynchronously the behavior
/// <summary>
/// Gets or sets a value indicating whether to execute asynchronously the behavior.
/// </summary>
/// <value>
/// <see cref="iTin.Export.Model.YesNo.Yes" /> if for execute asynchronously the behavior; otherwise, <see cref="iTin.Export.Model.YesNo.No" />. The default is <see cref="iTin.Export.Model.YesNo.Yes" />.
/// </value>
/// <remarks>
/// <code lang="xml" title="ITEE Object Element Usage">
/// <Mail Async="Yes|No" ...>
/// ...
/// </Mail>
/// </code>
/// <para>
/// <para><strong>Compatibility table with native writers.</strong></para>
/// <table>
/// <thead>
/// <tr>
/// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th>
/// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th>
/// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th>
/// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// </tr>
/// </tbody>
/// </table>
/// A <strong><c>X</c></strong> value indicates that the writer supports this element.
/// </para>
/// </remarks>
/// <example>
/// <code lang="xml">
/// <Behaviors>
/// <Downdload LocalCopy="Yes"/>
/// <TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/>
/// <Mail Execute="Yes" Async="Yes">
/// <Server>
/// <Credentials>
/// <Credential SSL="Yes" Name="one" UserName="address@gmail.com" password="pwd" Host="smtp.gmail.com"/>
/// </Credentials>
/// </Server>
/// <Messages>
/// <Message Credential="one" Send="Yes">
/// <From Address="emailaddress-one@gmail.com"/>
/// <To Addresses="emailaddress-two@hotmail.com emailaddress-three@hotmail.com"/>
/// <CC Addresses="emailaddress-four@hotmail.com emailaddress-five@hotmail.com"/>
/// <Subject>New report</Subject>
/// <Body>Hello, this is your report, sending from iTin.Export</Body>
/// <Attachments>
/// <Attachment Path="C:\Users\somefile.txt"/>
/// <Attachment Path="C:\Users\Downloads\Photos Sample.zip"/>
/// </Attachments>
/// </Message>
/// </Messages>
/// </Mail>
/// </Behaviors>
/// </code>
/// </example>
/// <exception cref="T:System.ComponentModel.InvalidEnumArgumentException">The value specified is outside the range of valid values.</exception>
[XmlAttribute]
[DefaultValue(DefaultAsync)]
public YesNo Async
{
get => GetStaticBindingValue(_async.ToString()).ToUpperInvariant() == "NO" ? YesNo.No : YesNo.Yes;
set
{
SentinelHelper.IsEnumValid(value);
_async = value;
}
}
#endregion
#region [public] (MailMessagesModel) Messages: Server: Gets or sets collection of mail messages
/// <summary>
/// Gets or sets collection of e-mail messages.
/// </summary>
/// <value>
/// Collection of e-mail messages. Each element represents an e-mail message
/// </value>
/// <remarks>
/// <code lang="xml" title="ITEE Object Element Usage">
/// <Mail ...>
/// <Messages/>
/// </Mail>
/// </code>
/// <para>
/// <para><strong>Compatibility table with native writers.</strong></para>
/// <table>
/// <thead>
/// <tr>
/// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th>
/// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th>
/// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th>
/// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// </tr>
/// </tbody>
/// </table>
/// A <strong><c>X</c></strong> value indicates that the writer supports this element.
/// </para>
/// </remarks>
/// <example>
/// <code lang="xml">
/// <Behaviors>
/// <Downdload LocalCopy="Yes"/>
/// <TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/>
/// <Mail Execute="Yes" Async="Yes">
/// <Server>
/// <Credentials>
/// <Credential SSL="Yes" Name="one" UserName="address@gmail.com" password="pwd" Host="smtp.gmail.com"/>
/// </Credentials>
/// </Server>
/// <Messages>
/// <Message Credential="one" Send="Yes">
/// <From Address="emailaddress-one@gmail.com"/>
/// <To Addresses="emailaddress-two@hotmail.com emailaddress-three@hotmail.com"/>
/// <CC Addresses="emailaddress-four@hotmail.com emailaddress-five@hotmail.com"/>
/// <Subject>New report</Subject>
/// <Body>Hello, this is your report, sending from iTin.Export</Body>
/// <Attachments>
/// <Attachment Path="C:\Users\somefile.txt"/>
/// <Attachment Path="C:\Users\Downloads\Photos Sample.zip"/>
/// </Attachments>
/// </Message>
/// </Messages>
/// </Mail>
/// </Behaviors>
/// </code>
/// </example>
[XmlArrayItem("Message", typeof(MailMessageModel))]
public MailMessagesModel Messages
{
get => _messages ?? (_messages = new MailMessagesModel(this));
set => _messages = value;
}
#endregion
#region [public] (BehaviorsModel) Parent: Gets the parent element of the element
/// <summary>
/// Gets the parent element of the element.
/// </summary>
/// <value>
/// The element that represents the container element of the element.
/// </value>
[Browsable(false)]
public BehaviorsModel Parent => _parent;
#endregion
#region [public] (MailServerModel) Server: Gets or sets a reference to mail server configuration
/// <summary>
/// Gets or sets a reference to mail server configuration.
/// </summary>
/// <value>
/// Reference to mail server configuration, contains collection for mail server credentials.
/// </value>
/// <remarks>
/// <code lang="xml" title="ITEE Object Element Usage">
/// <Mail ...>
/// <Server/>
/// </Mail>
/// </code>
/// <para>
/// <para><strong>Compatibility table with native writers.</strong></para>
/// <table>
/// <thead>
/// <tr>
/// <th>Comma-Separated Values<br/><see cref="T:iTin.Export.Writers.CsvWriter" /></th>
/// <th>Tab-Separated Values<br/><see cref="T:iTin.Export.Writers.TsvWriter" /></th>
/// <th>SQL Script<br/><see cref="T:iTin.Export.Writers.SqlScriptWriter" /></th>
/// <th>XML Spreadsheet 2003<br/><see cref="T:iTin.Export.Writers.Spreadsheet2003TabularWriter" /></th>
/// </tr>
/// </thead>
/// <tbody>
/// <tr>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// <td align="center">X</td>
/// </tr>
/// </tbody>
/// </table>
/// A <strong><c>X</c></strong> value indicates that the writer supports this element.
/// </para>
/// </remarks>
/// <example>
/// <code lang="xml">
/// <Behaviors>
/// <Downdload LocalCopy="Yes"/>
/// <TransformFile Execute="Yes" Indented="Yes" Save="Yes" Path="~\Output"/>
/// <Mail Execute="Yes" Async="Yes">
/// <Server>
/// <Credentials>
/// <Credential SSL="Yes" Name="one" UserName="address@gmail.com" password="pwd" Host="smtp.gmail.com"/>
/// </Credentials>
/// </Server>
/// <Messages>
/// <Message Credential="one" Send="Yes">
/// <From Address="emailaddress-one@gmail.com"/>
/// <To Addresses="emailaddress-two@hotmail.com emailaddress-three@hotmail.com"/>
/// <CC Addresses="emailaddress-four@hotmail.com emailaddress-five@hotmail.com"/>
/// <Subject>New report</Subject>
/// <Body>Hello, this is your report, sending from iTin.Export</Body>
/// <Attachments>
/// <Attachment Path="C:\Users\somefile.txt"/>
/// <Attachment Path="C:\Users\Downloads\Photos Sample.zip"/>
/// </Attachments>
/// </Message>
/// </Messages>
/// </Mail>
/// </Behaviors>
/// </code>
/// </example>
public MailServerModel Server
{
get
{
if (_server == null)
{
_server = new MailServerModel();
}
_server.SetParent(this);
return _server;
}
set => _server = value;
}
#endregion
#endregion
#region public override properties
#region [public] {overide} (bool) IsDefault: Gets a value indicating whether this instance is default
/// <inheritdoc />
/// <summary>
/// Gets a value indicating whether this instance is default.
/// </summary>
/// <value>
/// <strong>true</strong> if this instance contains the default; otherwise, <strong>false</strong>.
/// </value>
public override bool IsDefault => Server.IsDefault &&
Messages.IsDefault &&
Async.Equals(DefaultAsync);
#endregion
#endregion
#region internal methods
#region [internal] (void) SetParent(BehaviorsModel): Sets the parent element of the element
/// <summary>
/// Sets the parent element of the element.
/// </summary>
/// <param name="reference">Reference to parent.</param>
internal void SetParent(BehaviorsModel reference)
{
_parent = reference;
}
#endregion
#endregion
#region protected override methods
#region [protected] {override} (void) ExecuteBehavior(IWriter, ExportSettings): Code for execute download behavior
/// <inheritdoc />
/// <summary>
/// Code for execute download behavior.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="settings">Exporter settings.</param>
/// <exception cref="T:iTin.Export.Web.MissingPageAsyncAttributeException">Throw if web page not is async.</exception>
protected override void ExecuteBehavior(IWriter writer, ExportSettings settings)
{
var isBehaviorAsync = Async == YesNo.Yes;
var isWebContext = HttpContext.Current != null;
if (isWebContext)
{
if (isBehaviorAsync)
{
var page = (Page) HttpContext.Current.CurrentHandler;
var isPageAsync = page.IsAsync;
if (!isPageAsync)
{
throw new MissingPageAsyncAttributeException(page.AppRelativeVirtualPath);
}
}
}
var messagesToSend = from message in Messages
let canSend = message.Send
where canSend == YesNo.Yes
select message;
foreach (var messageModel in messagesToSend)
{
var message = new MailMessage
{
Body = messageModel.Body,
Subject = messageModel.Subject,
From = new MailAddress(messageModel.From.Address)
};
foreach (var to in messageModel.To.Addresses)
{
message.To.Add(new MailAddress(to));
}
foreach (var cc in messageModel.CC.Addresses)
{
message.CC.Add(new MailAddress(cc));
}
var filename = writer.ResponseEx.ExtractFileName();
var filenameFullPath = Path.Combine(FileHelper.TinExportTempDirectory, filename);
var exporterAttach = filenameFullPath;
var existFilename = File.Exists(filenameFullPath);
if (!existFilename)
{
exporterAttach = CreateZipFile(writer);
}
message.Attachments.Add(new Attachment(exporterAttach));
var attachments = from attachment in messageModel.Attachments
let exist = File.Exists(attachment.Path)
where exist
select attachment;
foreach (var attachment in attachments)
{
message.Attachments.Add(new Attachment(attachment.Path));
}
var mails = new MailHelper(Server);
mails.SendMail(messageModel.Credential, message, isBehaviorAsync);
}
if (!isWebContext)
{
return;
}
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
}
#endregion
#endregion
#region private static methods
#region [private] {static} (string) CreateZipFile(IWriter): Creates zip file
/// <summary>
/// Creates zip file.
/// </summary>
/// <param name="writer">Writer reference.</param>
/// <returns>
/// Returns zip filename.
/// </returns>
private static string CreateZipFile(IWriter writer)
{
var exporterType = writer.Provider.Input.Model.Table.Exporter.ExporterType;
if (exporterType != KnownExporter.Template)
{
if (!writer.IsTransformationFile)
{
return string.Empty;
}
}
var files = new Dictionary<string, byte[]>();
var tempDirectory = FileHelper.TinExportTempDirectory;
var extension = writer.IsTransformationFile ? "*" : writer.WriterMetadata.Extension;
var pattern = string.Format(CultureInfo.InvariantCulture, "*.{0}", extension);
var items = Directory.GetFiles(tempDirectory, pattern, SearchOption.TopDirectoryOnly);
foreach (var item in items)
{
var filename = Path.GetFileName(item);
files.Add(filename, StreamHelper.AsByteArrayFromFile(item));
}
return files.ToZip(writer);
}
#endregion
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.IO.Tests
{
public class FileStream_ctor_str_fm : FileSystemTest
{
protected virtual FileStream CreateFileStream(string path, FileMode mode)
{
return new FileStream(path, mode);
}
[Fact]
public void NullPathThrows()
{
Assert.Throws<ArgumentNullException>(() => CreateFileStream(null, FileMode.Open));
}
[Fact]
public void EmptyPathThrows()
{
Assert.Throws<ArgumentException>(() => CreateFileStream(string.Empty, FileMode.Open));
}
[Fact]
public void DirectoryThrows()
{
Assert.Throws<UnauthorizedAccessException>(() => CreateFileStream(".", FileMode.Open));
}
[Fact]
public void InvalidModeThrows()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("mode", () => CreateFileStream(GetTestFilePath(), ~FileMode.Open));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingFile_ThrowsFileNotFound(char trailingChar)
{
string path = GetTestFilePath() + trailingChar;
Assert.Throws<FileNotFoundException>(() => CreateFileStream(path, FileMode.Open));
}
[Theory, MemberData(nameof(TrailingCharacters))]
public void MissingDirectory_ThrowsDirectoryNotFound(char trailingChar)
{
string path = Path.Combine(GetTestFilePath(), "file" + trailingChar);
Assert.Throws<DirectoryNotFoundException>(() => CreateFileStream(path, FileMode.Open));
}
public static TheoryData<string> StreamSpecifiers
{
get
{
TheoryData<string> data = new TheoryData<string>();
data.Add("");
if (PlatformDetection.IsWindows && PlatformDetection.IsNetCore)
{
data.Add("::$DATA"); // Same as default stream (e.g. main file)
data.Add(":bar"); // $DATA isn't necessary
data.Add(":bar:$DATA"); // $DATA can be explicitly specified
}
return data;
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeCreate(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (CreateFileStream(fileName, FileMode.Create))
{
Assert.True(File.Exists(fileName));
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeCreateExisting(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
// Ensure that the file was re-created
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeCreateNew(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (CreateFileStream(fileName, FileMode.CreateNew))
{
Assert.True(File.Exists(fileName));
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeCreateNewExistingThrows(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.CreateNew))
{
fs.WriteByte(0);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
Assert.Throws<IOException>(() => CreateFileStream(fileName, FileMode.CreateNew));
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeOpenThrows(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Open));
Assert.Equal(fileName, fnfe.FileName);
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeOpenExisting(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Open))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeOpenOrCreate(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (CreateFileStream(fileName, FileMode.OpenOrCreate))
{
Assert.True(File.Exists(fileName));
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeOpenOrCreateExisting(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.OpenOrCreate))
{
// Ensure that the file was re-opened
Assert.Equal(1L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeTruncateThrows(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
FileNotFoundException fnfe = Assert.Throws<FileNotFoundException>(() => CreateFileStream(fileName, FileMode.Truncate));
Assert.Equal(fileName, fnfe.FileName);
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public void FileModeTruncateExisting(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Truncate))
{
// Ensure that the file was re-opened and truncated
Assert.Equal(0L, fs.Length);
Assert.Equal(0L, fs.Position);
Assert.True(fs.CanRead);
Assert.True(fs.CanWrite);
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public virtual void FileModeAppend(string streamSpecifier)
{
using (FileStream fs = CreateFileStream(GetTestFilePath() + streamSpecifier, FileMode.Append))
{
Assert.Equal(false, fs.CanRead);
Assert.Equal(true, fs.CanWrite);
}
}
[Theory, MemberData(nameof(StreamSpecifiers))]
public virtual void FileModeAppendExisting(string streamSpecifier)
{
string fileName = GetTestFilePath() + streamSpecifier;
using (FileStream fs = CreateFileStream(fileName, FileMode.Create))
{
fs.WriteByte(0);
}
using (FileStream fs = CreateFileStream(fileName, FileMode.Append))
{
// Ensure that the file was re-opened and position set to end
Assert.Equal(1L, fs.Length);
Assert.Equal(1L, fs.Position);
Assert.False(fs.CanRead);
Assert.True(fs.CanSeek);
Assert.True(fs.CanWrite);
Assert.Throws<IOException>(() => fs.Seek(-1, SeekOrigin.Current));
Assert.Throws<NotSupportedException>(() => fs.ReadByte());
}
}
}
}
| |
// 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 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Cdn
{
using System.Threading.Tasks;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Extension methods for CustomDomainsOperations.
/// </summary>
public static partial class CustomDomainsOperationsExtensions
{
/// <summary>
/// Lists the existing CDN custom domains within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
public static Microsoft.Rest.Azure.IPage<CustomDomain> ListByEndpoint(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).ListByEndpointAsync(resourceGroupName, profileName, endpointName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the existing CDN custom domains within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async Task<Microsoft.Rest.Azure.IPage<CustomDomain>> ListByEndpointAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListByEndpointWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Gets an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
public static CustomDomain Get(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).GetAsync(resourceGroupName, profileName, endpointName, customDomainName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Gets an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CustomDomain> GetAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
public static CustomDomain Create(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).CreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CustomDomain> CreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Creates a new CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
public static CustomDomain BeginCreate(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).BeginCreateAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Creates a new CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='hostName'>
/// The host name of the custom domain. Must be a domain name.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CustomDomain> BeginCreateAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, string hostName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, hostName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
public static CustomDomain Delete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).DeleteAsync(resourceGroupName, profileName, endpointName, customDomainName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CustomDomain> DeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.DeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Deletes an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
public static CustomDomain BeginDelete(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).BeginDeleteAsync(resourceGroupName, profileName, endpointName, customDomainName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Deletes an existing CDN custom domain within an endpoint.
/// </summary>
/// <param name='operations'>
/// The operations group for this extension method.
/// </param>
/// <param name='resourceGroupName'>
/// Name of the Resource group within the Azure subscription.
/// </param>
/// <param name='profileName'>
/// Name of the CDN profile which is unique within the resource group.
/// </param>
/// <param name='endpointName'>
/// Name of the endpoint under the profile which is unique globally.
/// </param>
/// <param name='customDomainName'>
/// Name of the custom domain within an endpoint.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public static async System.Threading.Tasks.Task<CustomDomain> BeginDeleteAsync(this ICustomDomainsOperations operations, string resourceGroupName, string profileName, string endpointName, string customDomainName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, profileName, endpointName, customDomainName, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
/// <summary>
/// Lists the existing CDN custom domains within an endpoint.
/// </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 Microsoft.Rest.Azure.IPage<CustomDomain> ListByEndpointNext(this ICustomDomainsOperations operations, string nextPageLink)
{
return System.Threading.Tasks.Task.Factory.StartNew(s => ((ICustomDomainsOperations)s).ListByEndpointNextAsync(nextPageLink), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult();
}
/// <summary>
/// Lists the existing CDN custom domains within an endpoint.
/// </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<Microsoft.Rest.Azure.IPage<CustomDomain>> ListByEndpointNextAsync(this ICustomDomainsOperations operations, string nextPageLink, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
using (var _result = await operations.ListByEndpointNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
{
return _result.Body;
}
}
}
}
| |
//
// SqlDateTimeTest.cs - NUnit Test Cases for System.Data.SqlTypes.SqlDateTime
//
// Authors:
// Ville Palo (vi64pa@koti.soon.fi)
// Martin Willemoes Hansen
//
// (C) 2002 Ville Palo
// (C) 2003 Martin Willemoes Hansen
//
//
// Copyright (C) 2004 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using NUnit.Framework;
using System;
using System.Data.SqlTypes;
using System.Threading;
using System.Globalization;
namespace MonoTests.System.Data.SqlTypes
{
[TestFixture]
public class SqlDateTimeTest : Assertion {
private long[] myTicks = {
631501920000000000L, // 25 Feb 2002 - 00:00:00
631502475130080000L, // 25 Feb 2002 - 15:25:13,8
631502115130080000L, // 25 Feb 2002 - 05:25:13,8
631502115000000000L, // 25 Feb 2002 - 05:25:00
631502115130000000L, // 25 Feb 2002 - 05:25:13
631502079130000000L, // 25 Feb 2002 - 04:25:13
629197085770000000L // 06 Nov 1994 - 08:49:37
};
private SqlDateTime Test1;
private SqlDateTime Test2;
private SqlDateTime Test3;
[SetUp]
public void GetReady()
{
Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US");
Test1 = new SqlDateTime (2002, 10, 19, 9, 40, 0);
Test2 = new SqlDateTime (2003, 11, 20,10, 50, 1);
Test3 = new SqlDateTime (2003, 11, 20, 10, 50, 1);
}
// Test constructor
[Test]
public void Create()
{
// SqlDateTime (DateTime)
SqlDateTime CTest = new SqlDateTime (
new DateTime (2002, 5, 19, 3, 34, 0));
AssertEquals ("#A01", 2002, CTest.Value.Year);
// SqlDateTime (int, int)
CTest = new SqlDateTime (0, 0);
// SqlDateTime (int, int, int)
AssertEquals ("#A02", 1900, CTest.Value.Year);
AssertEquals ("#A03", 1, CTest.Value.Month);
AssertEquals ("#A04", 1, CTest.Value.Day);
AssertEquals ("#A05", 0, CTest.Value.Hour);
// SqlDateTime (int, int, int, int, int, int)
CTest = new SqlDateTime (5000, 12, 31);
AssertEquals ("#A06", 5000, CTest.Value.Year);
AssertEquals ("#A07", 12, CTest.Value.Month);
AssertEquals ("#A08", 31, CTest.Value.Day);
// SqlDateTime (int, int, int, int, int, int, double)
CTest = new SqlDateTime (1978, 5, 19, 3, 34, 0);
AssertEquals ("#A09", 1978, CTest.Value.Year);
AssertEquals ("#A10", 5, CTest.Value.Month);
AssertEquals ("#A11", 19, CTest.Value.Day);
AssertEquals ("#A12", 3, CTest.Value.Hour);
AssertEquals ("#A13", 34, CTest.Value.Minute);
AssertEquals ("#A14", 0, CTest.Value.Second);
try {
CTest = new SqlDateTime (10000, 12, 31);
Fail ("#A15");
} catch (Exception e) {
AssertEquals ("#A16", typeof (SqlTypeException),
e.GetType ());
}
// SqlDateTime (int, int, int, int, int, int, int)
CTest = new SqlDateTime (1978, 5, 19, 3, 34, 0, 12);
AssertEquals ("#A17", 1978, CTest.Value.Year);
AssertEquals ("#A18", 5, CTest.Value.Month);
AssertEquals ("#A19", 19, CTest.Value.Day);
AssertEquals ("#A20", 3, CTest.Value.Hour);
AssertEquals ("#A21", 34, CTest.Value.Minute);
AssertEquals ("#A22", 0, CTest.Value.Second);
AssertEquals ("#A23", 0, CTest.Value.Millisecond);
}
// Test public fields
[Test]
public void PublicFields()
{
// MaxValue
AssertEquals ("#B01", 9999, SqlDateTime.MaxValue.Value.Year);
AssertEquals ("#B02", 12, SqlDateTime.MaxValue.Value.Month);
AssertEquals ("#B03", 31, SqlDateTime.MaxValue.Value.Day);
AssertEquals ("#B04", 23, SqlDateTime.MaxValue.Value.Hour);
AssertEquals ("#B05", 59, SqlDateTime.MaxValue.Value.Minute);
AssertEquals ("#B06", 59, SqlDateTime.MaxValue.Value.Second);
// MinValue
AssertEquals ("#B07", 1753, SqlDateTime.MinValue.Value.Year);
AssertEquals ("#B08", 1, SqlDateTime.MinValue.Value.Month);
AssertEquals ("#B09", 1, SqlDateTime.MinValue.Value.Day);
AssertEquals ("#B10", 0, SqlDateTime.MinValue.Value.Hour);
AssertEquals ("#B11", 0, SqlDateTime.MinValue.Value.Minute);
AssertEquals ("#B12", 0, SqlDateTime.MinValue.Value.Second);
// Null
Assert ("#B13", SqlDateTime.Null.IsNull);
// SQLTicksPerHour
AssertEquals ("#B14", 1080000, SqlDateTime.SQLTicksPerHour);
// SQLTicksPerMinute
AssertEquals ("#B15", 18000, SqlDateTime.SQLTicksPerMinute);
// SQLTicksPerSecond
AssertEquals ("#B16", 300, SqlDateTime.SQLTicksPerSecond);
}
// Test properties
[Test]
public void Properties()
{
// DayTicks
AssertEquals ("#C01", 37546, Test1.DayTicks);
try {
int test = SqlDateTime.Null.DayTicks;
Fail ("#C02");
} catch (Exception e) {
AssertEquals ("#C03", typeof (SqlNullValueException),
e.GetType ());
}
// IsNull
Assert ("#C04", SqlDateTime.Null.IsNull);
Assert ("#C05", !Test2.IsNull);
// TimeTicks
AssertEquals ("#C06", 10440000, Test1.TimeTicks);
try {
int test = SqlDateTime.Null.TimeTicks;
Fail ("#C07");
} catch (Exception e) {
AssertEquals ("#C08", typeof (SqlNullValueException),
e.GetType ());
}
// Value
AssertEquals ("#C09", 2003, Test2.Value.Year);
AssertEquals ("#C10", 2002, Test1.Value.Year);
}
// PUBLIC METHODS
[Test]
public void CompareTo()
{
SqlString TestString = new SqlString ("This is a test");
Assert ("#D01", Test1.CompareTo (Test3) < 0);
Assert ("#D02", Test2.CompareTo (Test1) > 0);
Assert ("#D03", Test2.CompareTo (Test3) == 0);
Assert ("#D04", Test1.CompareTo (SqlDateTime.Null) > 0);
try {
Test1.CompareTo (TestString);
Fail("#D05");
} catch(Exception e) {
AssertEquals ("#D06", typeof (ArgumentException), e.GetType ());
}
}
[Test]
public void EqualsMethods()
{
Assert ("#E01", !Test1.Equals (Test2));
Assert ("#E03", !Test2.Equals (new SqlString ("TEST")));
Assert ("#E04", Test2.Equals (Test3));
// Static Equals()-method
Assert ("#E05", SqlDateTime.Equals (Test2, Test3).Value);
Assert ("#E06", !SqlDateTime.Equals (Test1, Test2).Value);
}
[Test]
public void GetHashCodeTest()
{
// FIXME: Better way to test HashCode
AssertEquals ("#F01", Test1.GetHashCode (), Test1.GetHashCode ());
Assert ("#F02", Test2.GetHashCode () != Test1.GetHashCode ());
}
[Test]
public void GetTypeTest()
{
AssertEquals ("#G01", "System.Data.SqlTypes.SqlDateTime",
Test1.GetType ().ToString ());
AssertEquals ("#G02", "System.DateTime",
Test1.Value.GetType ().ToString ());
}
[Test]
public void Greaters()
{
// GreateThan ()
Assert ("#H01", !SqlDateTime.GreaterThan (Test1, Test2).Value);
Assert ("#H02", SqlDateTime.GreaterThan (Test2, Test1).Value);
Assert ("#H03", !SqlDateTime.GreaterThan (Test2, Test3).Value);
// GreaterTharOrEqual ()
Assert ("#H04", !SqlDateTime.GreaterThanOrEqual (Test1, Test2).Value);
Assert ("#H05", SqlDateTime.GreaterThanOrEqual (Test2, Test1).Value);
Assert ("#H06", SqlDateTime.GreaterThanOrEqual (Test2, Test3).Value);
}
[Test]
public void Lessers()
{
// LessThan()
Assert ("#I01", !SqlDateTime.LessThan (Test2, Test3).Value);
Assert ("#I02", !SqlDateTime.LessThan (Test2, Test1).Value);
Assert ("#I03", SqlDateTime.LessThan (Test1, Test3).Value);
// LessThanOrEqual ()
Assert ("#I04", SqlDateTime.LessThanOrEqual (Test1, Test2).Value);
Assert ("#I05", !SqlDateTime.LessThanOrEqual (Test2, Test1).Value);
Assert ("#I06", SqlDateTime.LessThanOrEqual (Test3, Test2).Value);
Assert ("#I07", SqlDateTime.LessThanOrEqual (Test1, SqlDateTime.Null).IsNull);
}
[Test]
public void NotEquals()
{
Assert ("#J01", SqlDateTime.NotEquals (Test1, Test2).Value);
Assert ("#J02", SqlDateTime.NotEquals (Test3, Test1).Value);
Assert ("#J03", !SqlDateTime.NotEquals (Test2, Test3).Value);
Assert ("#J04", SqlDateTime.NotEquals (SqlDateTime.Null, Test2).IsNull);
}
[Test]
public void Parse()
{
try {
SqlDateTime.Parse (null);
Fail ("#K01");
} catch (Exception e) {
AssertEquals ("#K02", typeof (ArgumentNullException),
e.GetType ());
}
try {
SqlDateTime.Parse ("not-a-number");
Fail ("#K03");
} catch (Exception e) {
AssertEquals ("#K04", typeof (FormatException),
e.GetType ());
}
SqlDateTime t1 = SqlDateTime.Parse ("02/25/2002");
AssertEquals ("#K05", myTicks[0], t1.Value.Ticks);
try {
t1 = SqlDateTime.Parse ("2002-02-25");
} catch (Exception e) {
Fail ("#K06 " + e);
}
// Thanks for Martin Baulig for these (DateTimeTest.cs)
AssertEquals ("#K07", myTicks[0], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("Monday, 25 February 2002");
AssertEquals ("#K08", myTicks[0], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("Monday, 25 February 2002 05:25");
AssertEquals ("#K09", myTicks[3], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("Monday, 25 February 2002 05:25:13");
AssertEquals ("#K10", myTicks[4], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("02/25/2002 05:25");
AssertEquals ("#K11", myTicks[3], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("02/25/2002 05:25:13");
AssertEquals ("#K12", myTicks[4], t1.Value.Ticks);
t1 = SqlDateTime.Parse ("2002-02-25 04:25:13Z");
t1 = TimeZone.CurrentTimeZone.ToUniversalTime(t1.Value);
AssertEquals ("#K13", 2002, t1.Value.Year);
AssertEquals ("#K14", 02, t1.Value.Month);
AssertEquals ("#K15", 25, t1.Value.Day);
AssertEquals ("#K16", 04, t1.Value.Hour);
AssertEquals ("#K17", 25, t1.Value.Minute);
AssertEquals ("#K18", 13, t1.Value.Second);
SqlDateTime t2 = new SqlDateTime (DateTime.Today.Year, 2, 25);
t1 = SqlDateTime.Parse ("February 25");
AssertEquals ("#K19", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (DateTime.Today.Year, 2, 8);
t1 = SqlDateTime.Parse ("February 08");
AssertEquals ("#K20", t2.Value.Ticks, t1.Value.Ticks);
t1 = SqlDateTime.Parse ("Mon, 25 Feb 2002 04:25:13 GMT");
t1 = TimeZone.CurrentTimeZone.ToUniversalTime(t1.Value);
AssertEquals ("#K21", 2002, t1.Value.Year);
AssertEquals ("#K22", 02, t1.Value.Month);
AssertEquals ("#K23", 25, t1.Value.Day);
AssertEquals ("#K24", 04, t1.Value.Hour);
AssertEquals ("#K25", 25, t1.Value.Minute);
AssertEquals ("#K26", 13, t1.Value.Second);
t1 = SqlDateTime.Parse ("2002-02-25T05:25:13");
AssertEquals ("#K27", myTicks[4], t1.Value.Ticks);
t2 = DateTime.Today + new TimeSpan (5,25,0);
t1 = SqlDateTime.Parse ("05:25");
AssertEquals("#K28", t2.Value.Ticks, t1.Value.Ticks);
t2 = DateTime.Today + new TimeSpan (5,25,13);
t1 = SqlDateTime.Parse ("05:25:13");
AssertEquals("#K29", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (2002, 2, 1);
t1 = SqlDateTime.Parse ("2002 February");
AssertEquals ("#K30", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (2002, 2, 1);
t1 = SqlDateTime.Parse ("2002 February");
AssertEquals ("#K31", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (DateTime.Today.Year, 2, 8);
t1 = SqlDateTime.Parse ("February 8");
AssertEquals ("#K32", t2.Value.Ticks, t1.Value.Ticks);
}
[Test]
[Ignore ("This test is locale dependent.")]
public void ToStringTest()
{
//
// Thanks for Marting Baulig for these (DateTimeTest.cs)
//
SqlDateTime t1 = new SqlDateTime (2002, 2, 25, 5, 25, 13);
SqlDateTime t2 = new SqlDateTime (2002, 2, 25, 15, 25, 13);
// Standard patterns
AssertEquals("L01", "2/25/2002 5:25:13 AM", t1.ToString ());
AssertEquals("L02", (SqlString)"2/25/2002 5:25:13 AM", t1.ToSqlString ());
}
// OPERATORS
[Test]
public void ArithmeticOperators()
{
TimeSpan TestSpan = new TimeSpan (20, 1, 20, 20);
SqlDateTime ResultDateTime;
// "+"-operator
ResultDateTime = Test1 + TestSpan;
AssertEquals ("#M01", 2002, ResultDateTime.Value.Year);
AssertEquals ("#M02", 8, ResultDateTime.Value.Day);
AssertEquals ("#M03", 11, ResultDateTime.Value.Hour);
AssertEquals ("#M04", 0, ResultDateTime.Value.Minute);
AssertEquals ("#M05", 20, ResultDateTime.Value.Second);
Assert ("#M06", (SqlDateTime.Null + TestSpan).IsNull);
try {
ResultDateTime = SqlDateTime.MaxValue + TestSpan;
Fail ("#M07");
} catch (Exception e) {
AssertEquals ("#M08", typeof (ArgumentOutOfRangeException), e.GetType ());
}
// "-"-operator
ResultDateTime = Test1 - TestSpan;
AssertEquals ("#M09", 2002, ResultDateTime.Value.Year);
AssertEquals ("#M10", 29, ResultDateTime.Value.Day);
AssertEquals ("#M11", 8, ResultDateTime.Value.Hour);
AssertEquals ("#M12", 19, ResultDateTime.Value.Minute);
AssertEquals ("#M13", 40, ResultDateTime.Value.Second);
Assert ("#M14", (SqlDateTime.Null - TestSpan).IsNull);
try {
ResultDateTime = SqlDateTime.MinValue - TestSpan;
Fail ("#M15");
} catch (Exception e) {
AssertEquals ("#M16", typeof (SqlTypeException), e.GetType ());
}
}
[Test]
public void ThanOrEqualOperators()
{
// == -operator
Assert ("#N01", (Test2 == Test3).Value);
Assert ("#N02", !(Test1 == Test2).Value);
Assert ("#N03", (Test1 == SqlDateTime.Null).IsNull);
// != -operator
Assert ("#N04", !(Test2 != Test3).Value);
Assert ("#N05", (Test1 != Test3).Value);
Assert ("#N06", (Test1 != SqlDateTime.Null).IsNull);
// > -operator
Assert ("#N07", (Test2 > Test1).Value);
Assert ("#N08", !(Test3 > Test2).Value);
Assert ("#N09", (Test1 > SqlDateTime.Null).IsNull);
// >= -operator
Assert ("#N10", !(Test1 >= Test3).Value);
Assert ("#N11", (Test3 >= Test1).Value);
Assert ("#N12", (Test2 >= Test3).Value);
Assert ("#N13", (Test1 >= SqlDateTime.Null).IsNull);
// < -operator
Assert ("#N14", !(Test2 < Test1).Value);
Assert ("#N15", (Test1 < Test3).Value);
Assert ("#N16", !(Test2 < Test3).Value);
Assert ("#N17", (Test1 < SqlDateTime.Null).IsNull);
// <= -operator
Assert ("#N18", (Test1 <= Test3).Value);
Assert ("#N19", !(Test3 <= Test1).Value);
Assert ("#N20", (Test2 <= Test3).Value);
Assert ("#N21", (Test1 <= SqlDateTime.Null).IsNull);
}
[Test]
public void SqlDateTimeToDateTime()
{
AssertEquals ("O01", 2002, ((DateTime)Test1).Year);
AssertEquals ("O03", 2003, ((DateTime)Test2).Year);
AssertEquals ("O04", 10, ((DateTime)Test1).Month);
AssertEquals ("O05", 19, ((DateTime)Test1).Day);
AssertEquals ("O06", 9, ((DateTime)Test1).Hour);
AssertEquals ("O07", 40, ((DateTime)Test1).Minute);
AssertEquals ("O08", 0, ((DateTime)Test1).Second);
}
[Test]
public void SqlStringToSqlDateTime()
{
SqlString TestString = new SqlString ("02/25/2002");
SqlDateTime t1 = (SqlDateTime)TestString;
AssertEquals ("#P01", myTicks[0], t1.Value.Ticks);
// Thanks for Martin Baulig for these (DateTimeTest.cs)
AssertEquals ("#P02", myTicks[0], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("Monday, 25 February 2002");
AssertEquals ("#P04", myTicks[0], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("Monday, 25 February 2002 05:25");
AssertEquals ("#P05", myTicks[3], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("Monday, 25 February 2002 05:25:13");
AssertEquals ("#P05", myTicks[4], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("02/25/2002 05:25");
AssertEquals ("#P06", myTicks[3], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("02/25/2002 05:25:13");
AssertEquals ("#P07", myTicks[4], t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("2002-02-25 04:25:13Z");
t1 = TimeZone.CurrentTimeZone.ToUniversalTime(t1.Value);
AssertEquals ("#P08", 2002, t1.Value.Year);
AssertEquals ("#P09", 02, t1.Value.Month);
AssertEquals ("#P10", 25, t1.Value.Day);
AssertEquals ("#P11", 04, t1.Value.Hour);
AssertEquals ("#P12", 25, t1.Value.Minute);
AssertEquals ("#P13", 13, t1.Value.Second);
SqlDateTime t2 = new SqlDateTime (DateTime.Today.Year, 2, 25);
t1 = (SqlDateTime) new SqlString ("February 25");
AssertEquals ("#P14", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (DateTime.Today.Year, 2, 8);
t1 = (SqlDateTime) new SqlString ("February 08");
AssertEquals ("#P15", t2.Value.Ticks, t1.Value.Ticks);
t1 = (SqlDateTime) new SqlString ("Mon, 25 Feb 2002 04:25:13 GMT");
t1 = TimeZone.CurrentTimeZone.ToUniversalTime(t1.Value);
AssertEquals ("#P16", 2002, t1.Value.Year);
AssertEquals ("#P17", 02, t1.Value.Month);
AssertEquals ("#P18", 25, t1.Value.Day);
AssertEquals ("#P19", 04, t1.Value.Hour);
AssertEquals ("#P20", 25, t1.Value.Minute);
AssertEquals ("#P21", 13, t1.Value.Second);
t1 = (SqlDateTime) new SqlString ("2002-02-25T05:25:13");
AssertEquals ("#P22", myTicks[4], t1.Value.Ticks);
t2 = DateTime.Today + new TimeSpan (5,25,0);
t1 = (SqlDateTime) new SqlString ("05:25");
AssertEquals("#P23", t2.Value.Ticks, t1.Value.Ticks);
t2 = DateTime.Today + new TimeSpan (5,25,13);
t1 = (SqlDateTime) new SqlString ("05:25:13");
AssertEquals("#P24", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (2002, 2, 1);
t1 = (SqlDateTime) new SqlString ("2002 February");
AssertEquals ("#P25", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (2002, 2, 1);
t1 = (SqlDateTime) new SqlString ("2002 February");
AssertEquals ("#P26", t2.Value.Ticks, t1.Value.Ticks);
t2 = new SqlDateTime (DateTime.Today.Year, 2, 8);
t1 = (SqlDateTime) new SqlString ("February 8");
AssertEquals ("#P27", t2.Value.Ticks, t1.Value.Ticks);
}
[Test]
public void DateTimeToSqlDateTime()
{
DateTime DateTimeTest = new DateTime (2002, 10, 19, 11, 53, 4);
SqlDateTime Result = (SqlDateTime)DateTimeTest;
AssertEquals ("#Q01", 2002, Result.Value.Year);
AssertEquals ("#Q02", 10, Result.Value.Month);
AssertEquals ("#Q03", 19, Result.Value.Day);
AssertEquals ("#Q04", 11, Result.Value.Hour);
AssertEquals ("#Q05", 53, Result.Value.Minute);
AssertEquals ("#Q06", 4, Result.Value.Second);
}
}
}
| |
// 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.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests
{
public class InteractiveWindowTests : IDisposable
{
#region Helpers
private InteractiveWindowTestHost _testHost;
private List<InteractiveWindow.State> _states;
private readonly TestClipboard _testClipboard;
private readonly TaskFactory _factory = new TaskFactory(TaskScheduler.Default);
public InteractiveWindowTests()
{
_states = new List<InteractiveWindow.State>();
_testHost = new InteractiveWindowTestHost(_states.Add);
_testClipboard = new TestClipboard();
((InteractiveWindow)Window).InteractiveWindowClipboard = _testClipboard;
}
void IDisposable.Dispose()
{
_testHost.Dispose();
}
private IInteractiveWindow Window => _testHost.Window;
private Task TaskRun(Action action)
{
return _factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
}
private static IEnumerable<IInteractiveWindowCommand> MockCommands(params string[] commandNames)
{
foreach (var name in commandNames)
{
var mock = new Mock<IInteractiveWindowCommand>();
mock.Setup(m => m.Names).Returns(new[] { name });
yield return mock.Object;
}
}
private static ITextSnapshot MockSnapshot(string content)
{
var snapshotMock = new Mock<ITextSnapshot>();
snapshotMock.Setup(m => m[It.IsAny<int>()]).Returns<int>(index => content[index]);
snapshotMock.Setup(m => m.Length).Returns(content.Length);
snapshotMock.Setup(m => m.GetText()).Returns(content);
snapshotMock.Setup(m => m.GetText(It.IsAny<int>(), It.IsAny<int>())).Returns<int, int>((start, length) => content.Substring(start, length));
snapshotMock.Setup(m => m.GetText(It.IsAny<Span>())).Returns<Span>(span => content.Substring(span.Start, span.Length));
return snapshotMock.Object;
}
#endregion
[WpfFact]
public void InteractiveWindow__CommandParsing()
{
var commandList = MockCommands("foo", "bar", "bz", "command1").ToArray();
var commands = new Commands.Commands(null, "%", commandList);
AssertEx.Equal(commands.GetCommands(), commandList);
var cmdBar = commandList[1];
Assert.Equal("bar", cmdBar.Names.First());
Assert.Equal("%", commands.CommandPrefix);
commands.CommandPrefix = "#";
Assert.Equal("#", commands.CommandPrefix);
//// 111111
//// 0123456789012345
var s1 = MockSnapshot("#bar arg1 arg2 ");
SnapshotSpan prefixSpan, commandSpan, argsSpan;
IInteractiveWindowCommand cmd;
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 0)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 1)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 2)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(2, commandSpan.End);
Assert.Equal(2, argsSpan.Start);
Assert.Equal(2, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 3)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Null(cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(3, commandSpan.End);
Assert.Equal(3, argsSpan.Start);
Assert.Equal(3, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 4)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(4, argsSpan.Start);
Assert.Equal(4, argsSpan.End);
cmd = commands.TryParseCommand(new SnapshotSpan(s1, Span.FromBounds(0, 5)), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(5, argsSpan.End);
cmd = commands.TryParseCommand(s1.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(0, prefixSpan.Start);
Assert.Equal(1, prefixSpan.End);
Assert.Equal(1, commandSpan.Start);
Assert.Equal(4, commandSpan.End);
Assert.Equal(5, argsSpan.Start);
Assert.Equal(14, argsSpan.End);
////
//// 0123456789
var s2 = MockSnapshot(" #bar ");
cmd = commands.TryParseCommand(s2.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(3, commandSpan.Start);
Assert.Equal(6, commandSpan.End);
Assert.Equal(9, argsSpan.Start);
Assert.Equal(9, argsSpan.End);
//// 111111
//// 0123456789012345
var s3 = MockSnapshot(" # bar args");
cmd = commands.TryParseCommand(s3.GetExtent(), out prefixSpan, out commandSpan, out argsSpan);
Assert.Equal(cmdBar, cmd);
Assert.Equal(2, prefixSpan.Start);
Assert.Equal(3, prefixSpan.End);
Assert.Equal(6, commandSpan.Start);
Assert.Equal(9, commandSpan.End);
Assert.Equal(11, argsSpan.Start);
Assert.Equal(15, argsSpan.End);
}
[WpfFact]
public void InteractiveWindow_GetCommands()
{
var interactiveCommands = new InteractiveCommandsFactory(null, null).CreateInteractiveCommands(
Window,
"#",
_testHost.ExportProvider.GetExports<IInteractiveWindowCommand>().Select(x => x.Value).ToArray());
var commands = interactiveCommands.GetCommands();
Assert.NotEmpty(commands);
Assert.Equal(2, commands.Where(n => n.Names.First() == "cls").Count());
Assert.Equal(2, commands.Where(n => n.Names.Last() == "clear").Count());
Assert.NotNull(commands.Where(n => n.Names.First() == "help").SingleOrDefault());
Assert.NotNull(commands.Where(n => n.Names.First() == "reset").SingleOrDefault());
}
[WorkItem(3970, "https://github.com/dotnet/roslyn/issues/3970")]
[WpfFact]
public async Task ResetStateTransitions()
{
await Window.Operations.ResetAsync().ConfigureAwait(true);
Assert.Equal(_states, new[]
{
InteractiveWindow.State.Initializing,
InteractiveWindow.State.WaitingForInput,
InteractiveWindow.State.Resetting,
InteractiveWindow.State.WaitingForInput,
});
}
[WpfFact]
public async Task DoubleInitialize()
{
try
{
await Window.InitializeAsync().ConfigureAwait(true);
Assert.True(false);
}
catch (InvalidOperationException)
{
}
}
[WpfFact]
public void AccessPropertiesOnUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
property.GetMethod.Invoke(Window, Array.Empty<object>());
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
[WpfFact]
public async Task AccessPropertiesOnNonUIThread()
{
foreach (var property in typeof(IInteractiveWindow).GetProperties())
{
Assert.Null(property.SetMethod);
await TaskRun(() => property.GetMethod.Invoke(Window, Array.Empty<object>())).ConfigureAwait(true);
}
Assert.Empty(typeof(IInteractiveWindowOperations).GetProperties());
}
/// <remarks>
/// Confirm that we are, in fact, running on a non-UI thread.
/// </remarks>
[WpfFact]
public async Task NonUIThread()
{
await TaskRun(() => Assert.False(((InteractiveWindow)Window).OnUIThread())).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCloseOnNonUIThread()
{
await TaskRun(() => Window.Close()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallInsertCodeOnNonUIThread()
{
await TaskRun(() => Window.InsertCode("1")).ConfigureAwait(true);
}
[WpfFact]
public async Task CallSubmitAsyncOnNonUIThread()
{
await TaskRun(() => Window.SubmitAsync(Array.Empty<string>()).GetAwaiter().GetResult()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallWriteOnNonUIThread()
{
await TaskRun(() => Window.WriteLine("1")).ConfigureAwait(true);
await TaskRun(() => Window.Write("1")).ConfigureAwait(true);
await TaskRun(() => Window.WriteErrorLine("1")).ConfigureAwait(true);
await TaskRun(() => Window.WriteError("1")).ConfigureAwait(true);
}
[WpfFact]
public async Task CallFlushOutputOnNonUIThread()
{
Window.Write("1"); // Something to flush.
await TaskRun(() => Window.FlushOutput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallAddInputOnNonUIThread()
{
await TaskRun(() => Window.AddInput("1")).ConfigureAwait(true);
}
/// <remarks>
/// Call is blocking, so we can't write a simple non-failing test.
/// </remarks>
[WpfFact]
public void CallReadStandardInputOnUIThread()
{
Assert.Throws<InvalidOperationException>(() => Window.ReadStandardInput());
}
[WpfFact]
public async Task CallBackspaceOnNonUIThread()
{
Window.InsertCode("1"); // Something to backspace.
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallBreakLineOnNonUIThread()
{
await TaskRun(() => Window.Operations.BreakLine()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallClearHistoryOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.ClearHistory()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallClearViewOnNonUIThread()
{
Window.InsertCode("1"); // Something to clear.
await TaskRun(() => Window.Operations.ClearView()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistoryNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistoryNext()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistoryPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistoryPrevious()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistorySearchNextOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistorySearchNext()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHistorySearchPreviousOnNonUIThread()
{
Window.AddInput("1"); // Need a history entry.
await TaskRun(() => Window.Operations.HistorySearchPrevious()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallHomeOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
await TaskRun(() => Window.Operations.Home(true)).ConfigureAwait(true);
}
[WpfFact]
public async Task CallEndOnNonUIThread()
{
Window.Operations.BreakLine(); // Distinguish Home from End.
await TaskRun(() => Window.Operations.End(true)).ConfigureAwait(true);
}
[WpfFact]
public void ScrollToCursorOnHomeAndEndOnNonUIThread()
{
Window.InsertCode(new string('1', 512)); // a long input string
var textView = Window.TextView;
Window.Operations.Home(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
Window.Operations.End(false);
Assert.True(textView.TextViewModel.IsPointInVisualBuffer(textView.Caret.Position.BufferPosition,
textView.Caret.Position.Affinity));
}
[WpfFact]
public async Task CallSelectAllOnNonUIThread()
{
Window.InsertCode("1"); // Something to select.
await TaskRun(() => Window.Operations.SelectAll()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallPasteOnNonUIThread()
{
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCutOnNonUIThread()
{
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallDeleteOnNonUIThread()
{
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallReturnOnNonUIThread()
{
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallTrySubmitStandardInputOnNonUIThread()
{
await TaskRun(() => Window.Operations.TrySubmitStandardInput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallResetAsyncOnNonUIThread()
{
await TaskRun(() => Window.Operations.ResetAsync()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallExecuteInputOnNonUIThread()
{
await TaskRun(() => Window.Operations.ExecuteInput()).ConfigureAwait(true);
}
[WpfFact]
public async Task CallCancelOnNonUIThread()
{
await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation1()
{
TestIndentation(indentSize: 1);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation2()
{
TestIndentation(indentSize: 2);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation3()
{
TestIndentation(indentSize: 3);
}
[WorkItem(4235, "https://github.com/dotnet/roslyn/issues/4235")]
[WpfFact]
public void TestIndentation4()
{
TestIndentation(indentSize: 4);
}
private void TestIndentation(int indentSize)
{
const int promptWidth = 2;
_testHost.ExportProvider.GetExport<TestSmartIndentProvider>().Value.SmartIndent = new TestSmartIndent(
promptWidth,
promptWidth + indentSize,
promptWidth
);
AssertCaretVirtualPosition(0, promptWidth);
Window.InsertCode("{");
AssertCaretVirtualPosition(0, promptWidth + 1);
Window.Operations.BreakLine();
AssertCaretVirtualPosition(1, promptWidth + indentSize);
Window.InsertCode("Console.WriteLine();");
Window.Operations.BreakLine();
AssertCaretVirtualPosition(2, promptWidth);
Window.InsertCode("}");
AssertCaretVirtualPosition(2, promptWidth + 1);
}
private void AssertCaretVirtualPosition(int expectedLine, int expectedColumn)
{
ITextSnapshotLine actualLine;
int actualColumn;
Window.TextView.Caret.Position.VirtualBufferPosition.GetLineAndColumn(out actualLine, out actualColumn);
Assert.Equal(expectedLine, actualLine.LineNumber);
Assert.Equal(expectedColumn, actualColumn);
}
[WpfFact]
public void ResetCommandArgumentParsing_Success()
{
bool initialize;
Assert.True(ResetCommand.TryParseArguments("", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments(" ", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\n", out initialize));
Assert.True(initialize);
Assert.True(ResetCommand.TryParseArguments("noconfig", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments(" noconfig ", out initialize));
Assert.False(initialize);
Assert.True(ResetCommand.TryParseArguments("\r\nnoconfig\r\n", out initialize));
Assert.False(initialize);
}
[WpfFact]
public void ResetCommandArgumentParsing_Failure()
{
bool initialize;
Assert.False(ResetCommand.TryParseArguments("a", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfi", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig1", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig 1", out initialize));
Assert.False(ResetCommand.TryParseArguments("1 noconfig", out initialize));
Assert.False(ResetCommand.TryParseArguments("noconfig\r\na", out initialize));
Assert.False(ResetCommand.TryParseArguments("nOcOnfIg", out initialize));
}
[WpfFact]
public void ResetCommandNoConfigClassification()
{
Assert.Empty(ResetCommand.GetNoConfigPositions(""));
Assert.Empty(ResetCommand.GetNoConfigPositions("a"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfi"));
Assert.Empty(ResetCommand.GetNoConfigPositions("noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig"));
Assert.Empty(ResetCommand.GetNoConfigPositions("1noconfig1"));
Assert.Empty(ResetCommand.GetNoConfigPositions("nOcOnfIg"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig "));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig"));
Assert.Equal(new[] { 1 }, ResetCommand.GetNoConfigPositions(" noconfig "));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig"));
Assert.Equal(new[] { 0 }, ResetCommand.GetNoConfigPositions("noconfig\r\n"));
Assert.Equal(new[] { 2 }, ResetCommand.GetNoConfigPositions("\r\nnoconfig\r\n"));
Assert.Equal(new[] { 6 }, ResetCommand.GetNoConfigPositions("error noconfig"));
Assert.Equal(new[] { 0, 9 }, ResetCommand.GetNoConfigPositions("noconfig noconfig"));
Assert.Equal(new[] { 0, 15 }, ResetCommand.GetNoConfigPositions("noconfig error noconfig"));
}
[WorkItem(4755, "https://github.com/dotnet/roslyn/issues/4755")]
[WpfFact]
public void ReformatBraces()
{
var buffer = Window.CurrentLanguageBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal(0, snapshot.Length);
// Text before reformatting.
snapshot = ApplyChanges(
buffer,
new TextChange(0, 0, "{ {\r\n } }"));
// Text after reformatting.
Assert.Equal(9, snapshot.Length);
snapshot = ApplyChanges(
buffer,
new TextChange(1, 1, "\r\n "),
new TextChange(5, 1, " "),
new TextChange(7, 1, "\r\n"));
// Text from language buffer.
var actualText = snapshot.GetText();
Assert.Equal("{\r\n {\r\n }\r\n}", actualText);
// Text including prompts.
buffer = Window.TextView.TextBuffer;
snapshot = buffer.CurrentSnapshot;
actualText = snapshot.GetText();
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", actualText);
// Prompts should be read-only.
var regions = buffer.GetReadOnlyExtents(new Span(0, snapshot.Length));
AssertEx.SetEqual(regions,
new Span(0, 2),
new Span(5, 2),
new Span(14, 2),
new Span(23, 2));
}
[WpfFact]
public void CopyWithinInput()
{
_testClipboard.Clear();
Window.InsertCode("1 + 2");
Window.Operations.SelectAll();
Window.Operations.Copy();
VerifyClipboardData("1 + 2", "1 + 2", @"[{""content"":""1 + 2"",""kind"":2}]");
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 1, span.Length - 2), isReversed: false);
Window.Operations.Copy();
VerifyClipboardData(" + ", " + ", @"[{""content"":"" + "",""kind"":2}]");
}
[WpfFact]
public async Task CopyInputAndOutput()
{
_testClipboard.Clear();
await Submit(
@"foreach (var o in new[] { 1, 2, 3 })
System.Console.WriteLine();",
@"1
2
3
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.Copy();
VerifyClipboardData(@"> foreach (var o in new[] { 1, 2, 3 })
> System.Console.WriteLine();
1
2
3
> ",
@"> foreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3\par > ",
@"[{""content"":""> "",""kind"":0},{""content"":""foreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":0},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3\u000d\u000a"",""kind"":1},{""content"":""> "",""kind"":0}]");
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false);
Window.Operations.Copy();
VerifyClipboardData(@"oreach (var o in new[] { 1, 2, 3 })
> System.Console.WriteLine();
1
2
3",
@"oreach (var o in new[] \{ 1, 2, 3 \})\par > System.Console.WriteLine();\par 1\par 2\par 3",
@"[{""content"":""oreach (var o in new[] { 1, 2, 3 })\u000d\u000a"",""kind"":2},{""content"":""> "",""kind"":0},{""content"":""System.Console.WriteLine();\u000d\u000a"",""kind"":2},{""content"":""1\u000d\u000a2\u000d\u000a3"",""kind"":1}]");
}
[WpfFact]
public void CutWithinInput()
{
_testClipboard.Clear();
Window.InsertCode("foreach (var o in new[] { 1, 2, 3 })");
Window.Operations.BreakLine();
Window.InsertCode("System.Console.WriteLine();");
Window.Operations.BreakLine();
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
// Shrink the selection.
var selection = Window.TextView.Selection;
var span = selection.SelectedSpans[0];
selection.Select(new SnapshotSpan(span.Snapshot, span.Start + 3, span.Length - 6), isReversed: false);
Window.Operations.Cut();
VerifyClipboardData(
@"each (var o in new[] { 1, 2, 3 })
System.Console.WriteLine()",
expectedRtf: null,
expectedRepl: null);
}
[WpfFact]
public async Task CutInputAndOutput()
{
_testClipboard.Clear();
await Submit(
@"foreach (var o in new[] { 1, 2, 3 })
System.Console.WriteLine();",
@"1
2
3
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.Cut();
VerifyClipboardData(null, null, null);
}
/// <summary>
/// When there is no selection, copy
/// should copy the current line.
/// </summary>
[WpfFact]
public async Task CopyNoSelection()
{
await Submit(
@"s +
t",
@" 1
2 ").ConfigureAwait(true);
CopyNoSelectionAndVerify(0, 7, "> s +\r\n", @"> s +\par ", @"[{""content"":""> "",""kind"":0},{""content"":""s +\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(7, 11, "> \r\n", @"> \par ", @"[{""content"":""> "",""kind"":0},{""content"":""\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(11, 17, "> t\r\n", @"> t\par ", @"[{""content"":""> "",""kind"":0},{""content"":"" t\u000d\u000a"",""kind"":2}]");
CopyNoSelectionAndVerify(17, 21, " 1\r\n", @" 1\par ", @"[{""content"":"" 1\u000d\u000a"",""kind"":1}]");
CopyNoSelectionAndVerify(21, 23, "\r\n", @"\par ", @"[{""content"":""\u000d\u000a"",""kind"":1}]");
CopyNoSelectionAndVerify(23, 28, "2 > ", "2 > ", @"[{""content"":""2 "",""kind"":1},{""content"":""> "",""kind"":0}]");
}
private void CopyNoSelectionAndVerify(int start, int end, string expectedText, string expectedRtf, string expectedRepl)
{
var caret = Window.TextView.Caret;
var snapshot = Window.TextView.TextBuffer.CurrentSnapshot;
for (int i = start; i < end; i++)
{
_testClipboard.Clear();
caret.MoveTo(new SnapshotPoint(snapshot, i));
Window.Operations.Copy();
VerifyClipboardData(expectedText, expectedRtf, expectedRepl);
}
}
[WpfFact]
public void Paste()
{
var blocks = new[]
{
new BufferBlock(ReplSpanKind.Output, "a\r\nbc"),
new BufferBlock(ReplSpanKind.Prompt, "> "),
new BufferBlock(ReplSpanKind.Prompt, "< "),
new BufferBlock(ReplSpanKind.Input, "12"),
new BufferBlock(ReplSpanKind.StandardInput, "3"),
new BufferBlock((ReplSpanKind)10, "xyz")
};
// Paste from text clipboard format.
CopyToClipboard(blocks, includeRepl: false);
Window.Operations.Paste();
Assert.Equal("> a\r\n> bc> < 123xyz", GetTextFromCurrentSnapshot());
Window.Operations.ClearView();
Assert.Equal("> ", GetTextFromCurrentSnapshot());
// Paste from custom clipboard format.
CopyToClipboard(blocks, includeRepl: true);
Window.Operations.Paste();
Assert.Equal("> a\r\n> bc123", GetTextFromCurrentSnapshot());
}
[WpfFact]
public void JsonSerialization()
{
var expectedContent = new []
{
new BufferBlock(ReplSpanKind.Prompt, "> "),
new BufferBlock(ReplSpanKind.Input, "Hello"),
new BufferBlock(ReplSpanKind.Prompt, ". "),
new BufferBlock(ReplSpanKind.StandardInput, "world"),
new BufferBlock(ReplSpanKind.Output, "Hello world"),
};
var actualJson = BufferBlock.Serialize(expectedContent);
var expectedJson = @"[{""content"":""> "",""kind"":0},{""content"":""Hello"",""kind"":2},{""content"":"". "",""kind"":0},{""content"":""world"",""kind"":3},{""content"":""Hello world"",""kind"":1}]";
Assert.Equal(expectedJson, actualJson);
var actualContent = BufferBlock.Deserialize(actualJson);
Assert.Equal(expectedContent.Length, actualContent.Length);
for (int i = 0; i < expectedContent.Length; i++)
{
var expectedBuffer = expectedContent[i];
var actualBuffer = actualContent[i];
Assert.Equal(expectedBuffer.Kind, actualBuffer.Kind);
Assert.Equal(expectedBuffer.Content, actualBuffer.Content);
}
}
[WpfFact]
public async Task CancelMultiLineInput()
{
ApplyChanges(
Window.CurrentLanguageBuffer,
new TextChange(0, 0, "{\r\n {\r\n }\r\n}"));
// Text including prompts.
var buffer = Window.TextView.TextBuffer;
var snapshot = buffer.CurrentSnapshot;
Assert.Equal("> {\r\n> {\r\n> }\r\n> }", snapshot.GetText());
await TaskRun(() => Window.Operations.Cancel()).ConfigureAwait(true);
// Text after cancel.
snapshot = buffer.CurrentSnapshot;
Assert.Equal("> ", snapshot.GetText());
}
[WpfFact]
public void SelectAllInHeader()
{
Window.WriteLine("Header");
Window.FlushOutput();
var fullText = GetTextFromCurrentSnapshot();
Assert.Equal("Header\r\n> ", fullText);
Window.TextView.Caret.MoveTo(new SnapshotPoint(Window.TextView.TextBuffer.CurrentSnapshot, 1));
Window.Operations.SelectAll(); // Used to throw.
// Everything is selected.
Assert.Equal(new Span(0, fullText.Length), Window.TextView.Selection.SelectedSpans.Single().Span);
}
[WpfFact]
public async Task DeleteWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("2");
var caret = Window.TextView.Caret;
// with empty selection, Delete() only handles caret movement,
// so we can only test caret location.
// Delete() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
AssertCaretVirtualPosition(1, 1);
// Delete() with caret in active prompt, move caret to
// closest editable buffer
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task DeleteWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Delete() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Delete() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Delete() with selection overlaps with editable buffer,
// delete editable content and move caret to closest editable location
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Delete()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 3", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task BackspaceWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
// Backspace() with caret in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
AssertCaretVirtualPosition(1, 1);
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with caret in 2nd active prompt, move caret to
// closest editable buffer then delete previous character (breakline)
caret.MoveToNextCaretPosition();
Window.Operations.End(false);
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(3, 1);
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
AssertCaretVirtualPosition(2, 7);
Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot());
}
[WpfFact]
public async Task BackspaceWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Backspace() with selection in readonly area, no-op
Window.Operations.Home(false);
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.Home(false);
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> int x\r\n> ;", GetTextFromCurrentSnapshot());
// Backspace() with selection overlaps with editable buffer
selection.Clear();
Window.Operations.End(false);
start = caret.Position.VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(3, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Backspace()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> int x;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 7);
}
[WpfFact]
public async Task ReturnWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
// Return() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
AssertCaretVirtualPosition(1, 1);
// Return() with caret in active prompt, move caret to
// closest editable buffer first
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
AssertCaretVirtualPosition(3, 2);
}
[WpfFact]
public async Task ReturnWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// Return() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Return() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Delete() with selection overlaps with editable buffer,
// delete editable content and move caret to closest editable location and insert a return
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Return()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> \r\n> 3", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(3, 2);
}
[WpfFact]
public async Task CutWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("2");
var caret = Window.TextView.Caret;
_testClipboard.Clear();
// Cut() with caret in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 2", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(1, 1);
VerifyClipboardData(null, null, null);
// Cut() with caret in active prompt
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData("2", expectedRtf: null, expectedRepl: null);
}
[WpfFact]
public async Task CutWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
_testClipboard.Clear();
// Cut() with selection in readonly area, no-op
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
VerifyClipboardData(null, null, null);
// Cut() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
VerifyClipboardData(null, null, null);
// Cut() with selection overlaps with editable buffer,
// Cut editable content and move caret to closest editable location
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Cut()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 3", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData("2", expectedRtf: null, expectedRepl: null);
}
[WpfFact]
public async Task PasteWithOutSelectionInReadOnlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("2");
var caret = Window.TextView.Caret;
_testClipboard.Clear();
Window.Operations.Home(true);
Window.Operations.Copy();
VerifyClipboardData("2", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 2", @"[{""content"":""2"",""kind"":2}]");
// Paste() with caret in readonly area, no-op
Window.TextView.Selection.Clear();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 2", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(1, 1);
// Paste() with caret in active prompt
caret.MoveToNextCaretPosition();
AssertCaretVirtualPosition(2, 0);
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 22", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 3);
}
[WpfFact]
public async Task PasteWithSelectionInReadonlyArea()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
Window.InsertCode("23");
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
_testClipboard.Clear();
Window.Operations.Home(true);
Window.Operations.Copy();
VerifyClipboardData("23", @"\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue0;\red255\green255\blue255;}\f0 \fs24 \cf1 \cb2 \highlight2 23", @"[{""content"":""23"",""kind"":2}]");
// Paste() with selection in readonly area, no-op
selection.Clear();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.SelectAll();
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Paste() with selection in active prompt, no-op
selection.Clear();
var start = caret.MoveToNextCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
var end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 2);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 23", GetTextFromCurrentSnapshot());
// Paste() with selection overlaps with editable buffer,
// Cut editable content, move caret to closest editable location and insert text
selection.Clear();
caret.MoveToPreviousCaretPosition();
start = caret.MoveToPreviousCaretPosition().VirtualBufferPosition;
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
end = caret.MoveToNextCaretPosition().VirtualBufferPosition;
AssertCaretVirtualPosition(2, 3);
selection.Select(start, end);
await TaskRun(() => Window.Operations.Paste()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> 233", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 4);
}
[WpfFact]
public async Task DeleteLineWithOutSelection()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
// DeleteLine with caret in readonly area
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(1, 1);
// DeleteLine with caret in active prompt
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
for (int i = 0; i < 11; ++i)
{
caret.MoveToPreviousCaretPosition();
}
AssertCaretVirtualPosition(2, 0);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
// DeleteLine with caret in editable area
caret.MoveToNextCaretPosition();
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
}
[WpfFact]
public async Task DeleteLineWithSelection()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
// DeleteLine with selection in readonly area
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
await TaskRun(() => Window.Operations.SelectAll()).ConfigureAwait(true);
await TaskRun(() => Window.Operations.DeleteLine()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
// DeleteLine with selection in active prompt
selection.Clear();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
for (int i = 0; i < 11; ++i)
{
caret.MoveToPreviousCaretPosition();
}
selection.Select(caret.MoveToNextCaretPosition().VirtualBufferPosition, caret.MoveToNextCaretPosition().VirtualBufferPosition);
await TaskRun(() => Window.Operations.DeleteLine()).ConfigureAwait(true);
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
// DeleteLine with selection in editable area
Window.InsertCode("int x");
selection.Select(caret.MoveToPreviousCaretPosition().VirtualBufferPosition, caret.MoveToPreviousCaretPosition().VirtualBufferPosition);
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
// DeleteLine with selection spans all areas
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.DeleteLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
}
[WpfFact]
public async Task CutLineWithOutSelection()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
_testClipboard.Clear();
// CutLine with caret in readonly area
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
AssertCaretVirtualPosition(1, 1);
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(1, 1);
VerifyClipboardData(null, null, null);
// CutLine with caret in active prompt
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
for (int i = 0; i < 11; ++i)
{
caret.MoveToPreviousCaretPosition();
}
AssertCaretVirtualPosition(2, 0);
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData("int x\r\n", null, null);
// CutLine with caret in editable area
caret.MoveToNextCaretPosition();
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
VerifyClipboardData(";", null, null);
}
[WpfFact]
public async Task CutLineWithSelection()
{
await Submit(
@"1",
@"1
").ConfigureAwait(true);
var caret = Window.TextView.Caret;
var selection = Window.TextView.Selection;
_testClipboard.Clear();
// CutLine with selection in readonly area
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
caret.MoveToPreviousCaretPosition();
Window.Operations.SelectAll();
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
VerifyClipboardData(null, null, null);
// CutLine with selection in active prompt
selection.Clear();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
caret.MoveToNextCaretPosition();
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
for (int i = 0; i < 11; ++i)
{
caret.MoveToPreviousCaretPosition();
}
selection.Select(caret.MoveToNextCaretPosition().VirtualBufferPosition, caret.MoveToNextCaretPosition().VirtualBufferPosition);
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ;", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
VerifyClipboardData("int x\r\n", null, null);
// CutLine with selection in editable area
Window.InsertCode("int x");
selection.Select(caret.MoveToPreviousCaretPosition().VirtualBufferPosition, caret.MoveToPreviousCaretPosition().VirtualBufferPosition);
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
VerifyClipboardData("int x;", null, null);
// CutLine with selection spans all areas
Window.InsertCode("int x");
Window.Operations.BreakLine();
Window.InsertCode(";");
Window.Operations.SelectAll();
Window.Operations.SelectAll();
Window.Operations.CutLine();
Assert.Equal("> 1\r\n1\r\n> ", GetTextFromCurrentSnapshot());
AssertCaretVirtualPosition(2, 2);
Assert.True(selection.IsEmpty);
VerifyClipboardData("int x\r\n;", null, null);
}
[WpfFact]
public async Task SubmitAsyncNone()
{
await SubmitAsync().ConfigureAwait(true);
}
[WpfFact]
public async Task SubmitAsyncSingle()
{
await SubmitAsync("1").ConfigureAwait(true);
}
[WorkItem(5964)]
[WpfFact]
public async Task SubmitAsyncMultiple()
{
await SubmitAsync("1", "2", "1 + 2").ConfigureAwait(true);
}
[WorkItem(6054, "https://github.com/dotnet/roslyn/issues/6054")]
[WpfFact]
public void UndoMultiLinePaste()
{
CopyToClipboard(
@"1
2
3");
// paste multi-line text
Window.Operations.Paste();
Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot());
// undo paste
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> ", GetTextFromCurrentSnapshot());
// redo paste
((InteractiveWindow)Window).Redo_TestOnly(1);
Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot());
CopyToClipboard(
@"4
5
6");
// replace current text
Window.Operations.SelectAll();
Window.Operations.Paste();
Assert.Equal("> 4\r\n> 5\r\n> 6", GetTextFromCurrentSnapshot());
// undo replace
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> 1\r\n> 2\r\n> 3", GetTextFromCurrentSnapshot());
// undo paste
((InteractiveWindow)Window).Undo_TestOnly(1);
Assert.Equal("> ", GetTextFromCurrentSnapshot());
}
private void CopyToClipboard(string text)
{
_testClipboard.Clear();
var data = new DataObject();
data.SetData(DataFormats.UnicodeText, text);
data.SetData(DataFormats.StringFormat, text);
_testClipboard.SetDataObject(data, false);
}
private void CopyToClipboard(BufferBlock[] blocks, bool includeRepl)
{
_testClipboard.Clear();
var data = new DataObject();
var builder = new StringBuilder();
foreach (var block in blocks)
{
builder.Append(block.Content);
}
var text = builder.ToString();
data.SetData(DataFormats.UnicodeText, text);
data.SetData(DataFormats.StringFormat, text);
if (includeRepl)
{
data.SetData(InteractiveWindow.ClipboardFormat, BufferBlock.Serialize(blocks));
}
_testClipboard.SetDataObject(data, false);
}
private async Task SubmitAsync(params string[] submissions)
{
var actualSubmissions = new List<string>();
var evaluator = _testHost.Evaluator;
EventHandler<string> onExecute = (_, s) => actualSubmissions.Add(s.TrimEnd());
evaluator.OnExecute += onExecute;
await TaskRun(() => Window.SubmitAsync(submissions)).ConfigureAwait(true);
evaluator.OnExecute -= onExecute;
AssertEx.Equal(submissions, actualSubmissions);
}
private string GetTextFromCurrentSnapshot()
{
return Window.TextView.TextBuffer.CurrentSnapshot.GetText();
}
private async Task Submit(string submission, string output)
{
await TaskRun(() => Window.SubmitAsync(new[] { submission })).ConfigureAwait(true);
// TestInteractiveEngine.ExecuteCodeAsync() simply returns
// success rather than executing the submission, so add the
// expected output to the output buffer.
var buffer = Window.OutputBuffer;
using (var edit = buffer.CreateEdit())
{
edit.Replace(buffer.CurrentSnapshot.Length, 0, output);
edit.Apply();
}
}
private void VerifyClipboardData(string expectedText, string expectedRtf, string expectedRepl)
{
var data = _testClipboard.GetDataObject();
Assert.Equal(expectedText, data?.GetData(DataFormats.StringFormat));
Assert.Equal(expectedText, data?.GetData(DataFormats.Text));
Assert.Equal(expectedText, data?.GetData(DataFormats.UnicodeText));
Assert.Equal(expectedRepl, (string)data?.GetData(InteractiveWindow.ClipboardFormat));
var actualRtf = (string)data?.GetData(DataFormats.Rtf);
if (expectedRtf == null)
{
Assert.Null(actualRtf);
}
else
{
Assert.True(actualRtf.StartsWith(@"{\rtf"));
Assert.True(actualRtf.EndsWith(expectedRtf + "}"));
}
}
private struct TextChange
{
internal readonly int Start;
internal readonly int Length;
internal readonly string Text;
internal TextChange(int start, int length, string text)
{
Start = start;
Length = length;
Text = text;
}
}
private static ITextSnapshot ApplyChanges(ITextBuffer buffer, params TextChange[] changes)
{
using (var edit = buffer.CreateEdit())
{
foreach (var change in changes)
{
edit.Replace(change.Start, change.Length, change.Text);
}
return edit.Apply();
}
}
}
internal static class OperationsExtensions
{
internal static void Copy(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).Copy();
}
internal static void DeleteLine(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).DeleteLine();
}
internal static void CutLine(this IInteractiveWindowOperations operations)
{
((IInteractiveWindowOperations2)operations).CutLine();
}
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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.IO;
using System.Reflection;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using log4net;
using Caps = OpenSim.Framework.Communications.Capabilities.Caps;
namespace OpenSim.Region.CoreModules.Capabilities
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionConsoleModule")]
public class RegionConsoleModule : INonSharedRegionModule, IRegionConsole
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly Commands m_commands = new Commands();
private Scene m_scene;
public ICommands Commands
{
get { return m_commands; }
}
public void Initialize(IConfigSource source)
{
m_commands.AddCommand("Help", false, "help", "help [<item>]",
"Display help on a particular command or on a list of commands in a category", Help);
}
public void AddRegion(Scene s)
{
m_scene = s;
m_scene.RegisterModuleInterface<IRegionConsole>(this);
}
public void RemoveRegion(Scene s)
{
m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
m_scene = null;
}
public void RegionLoaded(Scene s)
{
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
}
public void Close()
{
}
public string Name
{
get { return "RegionConsoleModule"; }
}
public Type ReplaceableInterface
{
get { return null; }
}
public void SendConsoleOutput(UUID agentID, string message)
{
OSD osd = OSD.FromString(message);
IEventQueue eq = m_scene.RequestModuleInterface<IEventQueue>();
if (eq != null)
eq.Enqueue(EventQueueHelper.BuildEvent("SimConsoleResponse", osd), agentID);
}
public bool RunCommand(string command, UUID invokerID)
{
string[] parts = Parser.Parse(command);
Array.Resize(ref parts, parts.Length + 1);
parts[parts.Length - 1] = invokerID.ToString();
if (m_commands.Resolve(parts).Length == 0)
return false;
return true;
}
public void AddCommand(string module, bool shared, string command, string help, string longhelp,
CommandDelegate fn)
{
m_commands.AddCommand(module, shared, command, help, longhelp, fn);
}
public void PostInitialize()
{
}
public void RegisterCaps(UUID agentID, Caps caps)
{
if (!m_scene.RegionInfo.EstateSettings.IsEstateManager(agentID))
return;
UUID capID = UUID.Random();
// m_log.DebugFormat("[REGION CONSOLE]: /CAPS/{0} in region {1}", capID, m_scene.RegionInfo.RegionName);
caps.RegisterHandler(
"SimConsoleAsync",
new ConsoleHandler("/CAPS/" + capID + "/", "SimConsoleAsync", agentID, this, m_scene));
}
private void Help(string module, string[] cmd)
{
var agentID = new UUID(cmd[cmd.Length - 1]);
Array.Resize(ref cmd, cmd.Length - 1);
List<string> help = Commands.GetHelp(cmd);
string reply = String.Empty;
foreach (string s in help)
{
reply += s + "\n";
}
SendConsoleOutput(agentID, reply);
}
}
public class ConsoleHandler : BaseStreamHandler
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private readonly UUID m_agentID;
private readonly RegionConsoleModule m_consoleModule;
private readonly bool m_isGod;
private readonly Scene m_scene;
private bool m_consoleIsOn;
public ConsoleHandler(string path, string name, UUID agentID, RegionConsoleModule module, Scene scene)
: base("POST", path, name, agentID.ToString())
{
m_agentID = agentID;
m_consoleModule = module;
m_scene = scene;
m_isGod = m_scene.Permissions.IsGod(agentID);
}
public override byte[] Handle(string path, Stream request, OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
var reader = new StreamReader(request);
string message = reader.ReadToEnd();
OSD osd = OSDParser.DeserializeLLSDXml(message);
string cmd = osd.AsString();
if (cmd == "set console on")
{
if (m_isGod)
{
MainConsole.Instance.OnOutput += ConsoleSender;
m_consoleIsOn = true;
m_consoleModule.SendConsoleOutput(m_agentID, "Console is now on");
}
return new byte[0];
}
else if (cmd == "set console off")
{
MainConsole.Instance.OnOutput -= ConsoleSender;
m_consoleIsOn = false;
m_consoleModule.SendConsoleOutput(m_agentID, "Console is now off");
return new byte[0];
}
if (m_consoleIsOn == false && m_consoleModule.RunCommand(osd.AsString().Trim(), m_agentID))
return new byte[0];
if (m_isGod && m_consoleIsOn)
{
MainConsole.Instance.RunCommand(osd.AsString().Trim());
}
else
{
m_consoleModule.SendConsoleOutput(m_agentID, "Unknown command");
}
return new byte[0];
}
private void ConsoleSender(string text)
{
m_consoleModule.SendConsoleOutput(m_agentID, text);
}
private void OnMakeChildAgent(ScenePresence presence)
{
if (presence.UUID == m_agentID)
{
MainConsole.Instance.OnOutput -= ConsoleSender;
m_consoleIsOn = false;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Text;
using ALinq.SqlClient;
namespace ALinq.SqlClient
{
internal class SqlColumnizer
{
// Fields
private ColumnDeclarer declarer;
private ColumnNominator nominator;
// Methods
internal SqlColumnizer(Func<SqlExpression, bool> fnCanBeColumn)
{
this.nominator = new ColumnNominator(fnCanBeColumn);
this.declarer = new ColumnDeclarer();
}
internal SqlExpression ColumnizeSelection(SqlExpression selection)
{
return this.declarer.Declare(selection, this.nominator.Nominate(selection));
}
// Nested Types
private class ColumnDeclarer : SqlVisitor
{
// Fields
private HashSet<SqlExpression> candidates;
// Methods
internal ColumnDeclarer()
{
}
internal SqlExpression Declare(SqlExpression expression, HashSet<SqlExpression> candidates)
{
this.candidates = candidates;
return (SqlExpression) this.Visit(expression);
}
internal override SqlNode Visit(SqlNode node)
{
SqlExpression item = node as SqlExpression;
if ((item == null) || !this.candidates.Contains(item))
{
return base.Visit(node);
}
if ((item.NodeType != SqlNodeType.Column) && (item.NodeType != SqlNodeType.ColumnRef))
{
return new SqlColumn(item.ClrType, item.SqlType, null, null, item, item.SourceExpression);
}
return item;
}
}
private class ColumnNominator : SqlVisitor
{
// Fields
private HashSet<SqlExpression> candidates;
private Func<SqlExpression, bool> fnCanBeColumn;
private bool isBlocked;
// Methods
internal ColumnNominator(Func<SqlExpression, bool> fnCanBeColumn)
{
this.fnCanBeColumn = fnCanBeColumn;
}
private static bool CanRecurseColumnize(SqlExpression expr)
{
switch (expr.NodeType)
{
case SqlNodeType.Element:
case SqlNodeType.Exists:
case SqlNodeType.ClientQuery:
case SqlNodeType.Column:
case SqlNodeType.ColumnRef:
case SqlNodeType.AliasRef:
case SqlNodeType.Link:
case SqlNodeType.Multiset:
case SqlNodeType.ScalarSubSelect:
case SqlNodeType.Select:
case SqlNodeType.SharedExpressionRef:
case SqlNodeType.Value:
case SqlNodeType.Nop:
return false;
}
return true;
}
private static bool IsClientOnly(SqlExpression expr)
{
switch (expr.NodeType)
{
case SqlNodeType.DiscriminatedType:
case SqlNodeType.Element:
case SqlNodeType.Link:
case SqlNodeType.ClientArray:
case SqlNodeType.ClientCase:
case SqlNodeType.ClientQuery:
case SqlNodeType.AliasRef:
case SqlNodeType.Grouping:
case SqlNodeType.Multiset:
case SqlNodeType.Nop:
case SqlNodeType.SharedExpression:
case SqlNodeType.SharedExpressionRef:
case SqlNodeType.SimpleExpression:
case SqlNodeType.TypeCase:
return true;
case SqlNodeType.OuterJoinedValue:
return IsClientOnly(((SqlUnary) expr).Operand);
}
return false;
}
internal HashSet<SqlExpression> Nominate(SqlExpression expression)
{
this.candidates = new HashSet<SqlExpression>();
this.isBlocked = false;
this.Visit(expression);
return this.candidates;
}
internal override SqlNode Visit(SqlNode node)
{
SqlExpression expr = node as SqlExpression;
if (expr != null)
{
bool isBlocked = this.isBlocked;
this.isBlocked = false;
if (CanRecurseColumnize(expr))
{
base.Visit(expr);
}
if (!this.isBlocked)
{
if (!IsClientOnly(expr) && (expr.NodeType != SqlNodeType.Column) && expr.SqlType.CanBeColumn &&
(this.fnCanBeColumn == null || this.fnCanBeColumn(expr)))
{
this.candidates.Add(expr);
}
else
{
this.isBlocked = true;
}
}
this.isBlocked |= isBlocked;
}
return node;
}
internal override SqlExpression VisitClientCase(SqlClientCase c)
{
c.Expression = this.VisitExpression(c.Expression);
int num = 0;
int count = c.Whens.Count;
while (num < count)
{
c.Whens[num].Value = this.VisitExpression(c.Whens[num].Value);
num++;
}
return c;
}
internal override SqlExpression VisitSimpleCase(SqlSimpleCase c)
{
c.Expression = this.VisitExpression(c.Expression);
int num = 0;
int count = c.Whens.Count;
while (num < count)
{
c.Whens[num].Value = this.VisitExpression(c.Whens[num].Value);
num++;
}
return c;
}
internal override SqlExpression VisitTypeCase(SqlTypeCase tc)
{
tc.Discriminator = this.VisitExpression(tc.Discriminator);
int num = 0;
int count = tc.Whens.Count;
while (num < count)
{
tc.Whens[num].TypeBinding = this.VisitExpression(tc.Whens[num].TypeBinding);
num++;
}
return tc;
}
}
private class ColumnAppendToTable : SqlVisitor
{
internal override SqlTable VisitTable(SqlTable tab)
{
return base.VisitTable(tab);
}
}
}
}
| |
// 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.Globalization;
using System.IO;
using System.Text;
namespace System.Net
{
internal enum CookieVariant
{
Unknown,
Plain,
Rfc2109,
Rfc2965,
Default = Rfc2109
}
// Cookie class
//
// Adheres to RFC 2965
//
// Currently, only represents client-side cookies. The cookie classes know
// how to parse a set-cookie format string, but not a cookie format string
// (e.g. "Cookie: $Version=1; name=value; $Path=/foo; $Secure")
[Serializable]
public sealed class Cookie
{
// NOTE: these two constants must change together.
internal const int MaxSupportedVersion = 1;
internal const string MaxSupportedVersionString = "1";
internal const string SeparatorLiteral = "; ";
internal const string EqualsLiteral = "=";
internal const string QuotesLiteral = "\"";
internal const string SpecialAttributeLiteral = "$";
internal static readonly char[] PortSplitDelimiters = new char[] { ' ', ',', '\"' };
internal static readonly char[] ReservedToName = new char[] { ' ', '\t', '\r', '\n', '=', ';', ',' };
internal static readonly char[] ReservedToValue = new char[] { ';', ',' };
private string _comment = string.Empty;
private Uri _commentUri = null;
private CookieVariant _cookieVariant = CookieVariant.Plain;
private bool _discard = false;
private string _domain = string.Empty;
private bool _domainImplicit = true;
private DateTime _expires = DateTime.MinValue;
private string _name = string.Empty;
private string _path = string.Empty;
private bool _pathImplicit = true;
private string _port = string.Empty;
private bool _portImplicit = true;
private int[] _portList = null;
private bool _secure = false;
private bool _httpOnly = false;
private DateTime _timeStamp = DateTime.Now;
private string _value = string.Empty;
private int _version = 0;
private string _domainKey = string.Empty;
internal bool IsQuotedVersion = false;
internal bool IsQuotedDomain = false;
#if DEBUG
static Cookie()
{
Debug.Assert(MaxSupportedVersion.ToString(NumberFormatInfo.InvariantInfo).Equals(MaxSupportedVersionString, StringComparison.Ordinal));
}
#endif
public Cookie()
{
}
public Cookie(string name, string value)
{
Name = name;
Value = value;
}
public Cookie(string name, string value, string path)
: this(name, value)
{
Path = path;
}
public Cookie(string name, string value, string path, string domain)
: this(name, value, path)
{
Domain = domain;
}
public string Comment
{
get
{
return _comment;
}
set
{
_comment = value ?? string.Empty;
}
}
public Uri CommentUri
{
get
{
return _commentUri;
}
set
{
_commentUri = value;
}
}
public bool HttpOnly
{
get
{
return _httpOnly;
}
set
{
_httpOnly = value;
}
}
public bool Discard
{
get
{
return _discard;
}
set
{
_discard = value;
}
}
public string Domain
{
get
{
return _domain;
}
set
{
_domain = value ?? string.Empty;
_domainImplicit = false;
_domainKey = string.Empty; // _domainKey will be set when adding this cookie to a container.
}
}
internal bool DomainImplicit
{
get
{
return _domainImplicit;
}
set
{
_domainImplicit = value;
}
}
public bool Expired
{
get
{
return (_expires != DateTime.MinValue) && (_expires.ToLocalTime() <= DateTime.Now);
}
set
{
if (value == true)
{
_expires = DateTime.Now;
}
}
}
public DateTime Expires
{
get
{
return _expires;
}
set
{
_expires = value;
}
}
public string Name
{
get
{
return _name;
}
set
{
if (String.IsNullOrEmpty(value) || !InternalSetName(value))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", value == null ? "<null>" : value));
}
}
}
internal bool InternalSetName(string value)
{
if (String.IsNullOrEmpty(value) || value[0] == '$' || value.IndexOfAny(ReservedToName) != -1)
{
_name = string.Empty;
return false;
}
_name = value;
return true;
}
public string Path
{
get
{
return _path;
}
set
{
_path = value ?? string.Empty;
_pathImplicit = false;
}
}
internal bool Plain
{
get
{
return Variant == CookieVariant.Plain;
}
}
internal Cookie Clone()
{
Cookie clonedCookie = new Cookie(_name, _value);
// Copy over all the properties from the original cookie
if (!_portImplicit)
{
clonedCookie.Port = _port;
}
if (!_pathImplicit)
{
clonedCookie.Path = _path;
}
clonedCookie.Domain = _domain;
// If the domain in the original cookie was implicit, we should preserve that property
clonedCookie.DomainImplicit = _domainImplicit;
clonedCookie._timeStamp = _timeStamp;
clonedCookie.Comment = _comment;
clonedCookie.CommentUri = _commentUri;
clonedCookie.HttpOnly = _httpOnly;
clonedCookie.Discard = _discard;
clonedCookie.Expires = _expires;
clonedCookie.Version = _version;
clonedCookie.Secure = _secure;
// The variant is set when we set properties like port/version. So,
// we should copy over the variant from the original cookie after
// we set all other properties
clonedCookie._cookieVariant = _cookieVariant;
return clonedCookie;
}
private static bool IsDomainEqualToHost(string domain, string host)
{
// +1 in the host length is to account for the leading dot in domain
return (host.Length + 1 == domain.Length) &&
(string.Compare(host, 0, domain, 1, host.Length, StringComparison.OrdinalIgnoreCase) == 0);
}
// According to spec we must assume default values for attributes but still
// keep in mind that we must not include them into the requests.
// We also check the validity of all attributes based on the version and variant (read RFC)
//
// To work properly this function must be called after cookie construction with
// default (response) URI AND setDefault == true
//
// Afterwards, the function can be called many times with other URIs and
// setDefault == false to check whether this cookie matches given uri
internal bool VerifySetDefaults(CookieVariant variant, Uri uri, bool isLocalDomain, string localDomain, bool setDefault, bool shouldThrow)
{
string host = uri.Host;
int port = uri.Port;
string path = uri.AbsolutePath;
bool valid = true;
if (setDefault)
{
// Set Variant. If version is zero => reset cookie to Version0 style
if (Version == 0)
{
variant = CookieVariant.Plain;
}
else if (Version == 1 && variant == CookieVariant.Unknown)
{
// Since we don't expose Variant to an app, set it to Default
variant = CookieVariant.Default;
}
_cookieVariant = variant;
}
// Check the name
if (_name == null || _name.Length == 0 || _name[0] == '$' || _name.IndexOfAny(ReservedToName) != -1)
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Name", _name == null ? "<null>" : _name));
}
return false;
}
// Check the value
if (_value == null ||
(!(_value.Length > 2 && _value[0] == '\"' && _value[_value.Length - 1] == '\"') && _value.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, "Value", _value == null ? "<null>" : _value));
}
return false;
}
// Check Comment syntax
if (Comment != null && !(Comment.Length > 2 && Comment[0] == '\"' && Comment[Comment.Length - 1] == '\"')
&& (Comment.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.CommentAttributeName, Comment));
}
return false;
}
// Check Path syntax
if (Path != null && !(Path.Length > 2 && Path[0] == '\"' && Path[Path.Length - 1] == '\"')
&& (Path.IndexOfAny(ReservedToValue) != -1))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, Path));
}
return false;
}
// Check/set domain
//
// If domain is implicit => assume a) uri is valid, b) just set domain to uri hostname.
if (setDefault && _domainImplicit == true)
{
_domain = host;
}
else
{
if (!_domainImplicit)
{
// Forwarding note: If Uri.Host is of IP address form then the only supported case
// is for IMPLICIT domain property of a cookie.
// The code below (explicit cookie.Domain value) will try to parse Uri.Host IP string
// as a fqdn and reject the cookie.
// Aliasing since we might need the KeyValue (but not the original one).
string domain = _domain;
// Syntax check for Domain charset plus empty string.
if (!DomainCharsTest(domain))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, domain == null ? "<null>" : domain));
}
return false;
}
// Domain must start with '.' if set explicitly.
if (domain[0] != '.')
{
if (!(variant == CookieVariant.Rfc2965 || variant == CookieVariant.Plain))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, _domain));
}
return false;
}
domain = '.' + domain;
}
int host_dot = host.IndexOf('.');
// First quick check is for pushing a cookie into the local domain.
if (isLocalDomain && string.Equals(localDomain, domain, StringComparison.OrdinalIgnoreCase))
{
valid = true;
}
else if (domain.IndexOf('.', 1, domain.Length - 2) == -1)
{
// A single label domain is valid only if the domain is exactly the same as the host specified in the URI.
if (!IsDomainEqualToHost(domain, host))
{
valid = false;
}
}
else if (variant == CookieVariant.Plain)
{
// We distinguish between Version0 cookie and other versions on domain issue.
// According to Version0 spec a domain must be just a substring of the hostname.
if (!IsDomainEqualToHost(domain, host))
{
if (host.Length <= domain.Length ||
(string.Compare(host, host.Length - domain.Length, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0))
{
valid = false;
}
}
}
else if (host_dot == -1 ||
domain.Length != host.Length - host_dot ||
(string.Compare(host, host_dot, domain, 0, domain.Length, StringComparison.OrdinalIgnoreCase) != 0))
{
// Starting from the first dot, the host must match the domain.
//
// For null hosts, the host must match the domain exactly.
if (!IsDomainEqualToHost(domain, host))
{
valid = false;
}
}
if (valid)
{
_domainKey = domain.ToLowerInvariant();
}
}
else
{
// For implicitly set domain AND at the set_default == false time
// we simply need to match uri.Host against m_domain.
if (!string.Equals(host, _domain, StringComparison.OrdinalIgnoreCase))
{
valid = false;
}
}
if (!valid)
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.DomainAttributeName, _domain));
}
return false;
}
}
// Check/Set Path
if (setDefault && _pathImplicit == true)
{
// This code assumes that the URI path is always valid and contains at least one '/'.
switch (_cookieVariant)
{
case CookieVariant.Plain:
_path = path;
break;
case CookieVariant.Rfc2109:
_path = path.Substring(0, path.LastIndexOf('/')); // May be empty
break;
case CookieVariant.Rfc2965:
default:
// NOTE: this code is not resilient against future versions with different 'Path' semantics.
_path = path.Substring(0, path.LastIndexOf('/') + 1);
break;
}
}
else
{
// Check current path (implicit/explicit) against given URI.
if (!path.StartsWith(CookieParser.CheckQuoted(_path)))
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PathAttributeName, _path));
}
return false;
}
}
// Set the default port if Port attribute was present but had no value.
if (setDefault && (_portImplicit == false && _port.Length == 0))
{
_portList = new int[1] { port };
}
if (_portImplicit == false)
{
// Port must match against the one from the uri.
valid = false;
foreach (int p in _portList)
{
if (p == port)
{
valid = true;
break;
}
}
if (!valid)
{
if (shouldThrow)
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, _port));
}
return false;
}
}
return true;
}
// Very primitive test to make sure that the name does not have illegal characters
// as per RFC 952 (relaxed on first char could be a digit and string can have '_').
private static bool DomainCharsTest(string name)
{
if (name == null || name.Length == 0)
{
return false;
}
for (int i = 0; i < name.Length; ++i)
{
char ch = name[i];
if (!((ch >= '0' && ch <= '9') ||
(ch == '.' || ch == '-') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= 'A' && ch <= 'Z') ||
(ch == '_')))
{
return false;
}
}
return true;
}
public string Port
{
get
{
return _port;
}
set
{
_portImplicit = false;
if (string.IsNullOrEmpty(value))
{
// "Port" is present but has no value.
_port = string.Empty;
}
else
{
// Parse port list
if (value[0] != '\"' || value[value.Length - 1] != '\"')
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
string[] ports = value.Split(PortSplitDelimiters);
List<int> portList = new List<int>();
int port;
for (int i = 0; i < ports.Length; ++i)
{
// Skip spaces
if (ports[i] != string.Empty)
{
if (!Int32.TryParse(ports[i], out port))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
// valid values for port 0 - 0xFFFF
if ((port < 0) || (port > 0xFFFF))
{
throw new CookieException(SR.Format(SR.net_cookie_attribute, CookieFields.PortAttributeName, value));
}
portList.Add(port);
}
}
_portList = portList.ToArray();
_port = value;
_version = MaxSupportedVersion;
_cookieVariant = CookieVariant.Rfc2965;
}
}
}
internal int[] PortList
{
get
{
// PortList will be null if Port Attribute was omitted in the response.
return _portList;
}
}
public bool Secure
{
get
{
return _secure;
}
set
{
_secure = value;
}
}
public DateTime TimeStamp
{
get
{
return _timeStamp;
}
}
public string Value
{
get
{
return _value;
}
set
{
_value = value ?? string.Empty;
}
}
internal CookieVariant Variant
{
get
{
return _cookieVariant;
}
set
{
// Only set by HttpListenerRequest::Cookies_get()
#if !uap
if (value != CookieVariant.Rfc2965)
{
NetEventSource.Fail(this, $"value != Rfc2965:{value}");
}
#endif
_cookieVariant = value;
}
}
// _domainKey member is set internally in VerifySetDefaults().
// If it is not set then verification function was not called;
// this should never happen.
internal string DomainKey
{
get
{
return _domainImplicit ? Domain : _domainKey;
}
}
public int Version
{
get
{
return _version;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_version = value;
if (value > 0 && _cookieVariant < CookieVariant.Rfc2109)
{
_cookieVariant = CookieVariant.Rfc2109;
}
}
}
public override bool Equals(object comparand)
{
Cookie other = comparand as Cookie;
return other != null
&& string.Equals(Name, other.Name, StringComparison.OrdinalIgnoreCase)
&& string.Equals(Value, other.Value, StringComparison.Ordinal)
&& string.Equals(Path, other.Path, StringComparison.Ordinal)
&& string.Equals(Domain, other.Domain, StringComparison.OrdinalIgnoreCase)
&& (Version == other.Version);
}
public override int GetHashCode()
{
return (Name + "=" + Value + ";" + Path + "; " + Domain + "; " + Version).GetHashCode();
}
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
ToString(sb);
return StringBuilderCache.GetStringAndRelease(sb);
}
internal void ToString(StringBuilder sb)
{
int beforeLength = sb.Length;
// Add the Cookie version if necessary.
if (Version != 0)
{
sb.Append(SpecialAttributeLiteral + CookieFields.VersionAttributeName + EqualsLiteral); // const strings
if (IsQuotedVersion) sb.Append('"');
sb.Append(_version.ToString(NumberFormatInfo.InvariantInfo));
if (IsQuotedVersion) sb.Append('"');
sb.Append(SeparatorLiteral);
}
// Add the Cookie Name=Value pair.
sb.Append(Name).Append(EqualsLiteral).Append(Value);
if (!Plain)
{
// Add the Path if necessary.
if (!_pathImplicit && _path.Length > 0)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PathAttributeName + EqualsLiteral); // const strings
sb.Append(_path);
}
// Add the Domain if necessary.
if (!_domainImplicit && _domain.Length > 0)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.DomainAttributeName + EqualsLiteral); // const strings
if (IsQuotedDomain) sb.Append('"');
sb.Append(_domain);
if (IsQuotedDomain) sb.Append('"');
}
}
// Add the Port if necessary.
if (!_portImplicit)
{
sb.Append(SeparatorLiteral + SpecialAttributeLiteral + CookieFields.PortAttributeName); // const strings
if (_port.Length > 0)
{
sb.Append(EqualsLiteral);
sb.Append(_port);
}
}
// Check to see whether the only thing we added was "=", and if so,
// remove it so that we leave the StringBuilder unchanged in contents.
int afterLength = sb.Length;
if (afterLength == (1 + beforeLength) && sb[beforeLength] == '=')
{
sb.Length = beforeLength;
}
}
internal string ToServerString()
{
string result = Name + EqualsLiteral + Value;
if (_comment != null && _comment.Length > 0)
{
result += SeparatorLiteral + CookieFields.CommentAttributeName + EqualsLiteral + _comment;
}
if (_commentUri != null)
{
result += SeparatorLiteral + CookieFields.CommentUrlAttributeName + EqualsLiteral + QuotesLiteral + _commentUri.ToString() + QuotesLiteral;
}
if (_discard)
{
result += SeparatorLiteral + CookieFields.DiscardAttributeName;
}
if (!_domainImplicit && _domain != null && _domain.Length > 0)
{
result += SeparatorLiteral + CookieFields.DomainAttributeName + EqualsLiteral + _domain;
}
if (Expires != DateTime.MinValue)
{
int seconds = (int)(Expires.ToLocalTime() - DateTime.Now).TotalSeconds;
if (seconds < 0)
{
// This means that the cookie has already expired. Set Max-Age to 0
// so that the client will discard the cookie immediately.
seconds = 0;
}
result += SeparatorLiteral + CookieFields.MaxAgeAttributeName + EqualsLiteral + seconds.ToString(NumberFormatInfo.InvariantInfo);
}
if (!_pathImplicit && _path != null && _path.Length > 0)
{
result += SeparatorLiteral + CookieFields.PathAttributeName + EqualsLiteral + _path;
}
if (!Plain && !_portImplicit && _port != null && _port.Length > 0)
{
// QuotesLiteral are included in _port.
result += SeparatorLiteral + CookieFields.PortAttributeName + EqualsLiteral + _port;
}
if (_version > 0)
{
result += SeparatorLiteral + CookieFields.VersionAttributeName + EqualsLiteral + _version.ToString(NumberFormatInfo.InvariantInfo);
}
return result == EqualsLiteral ? null : result;
}
#if DEBUG
internal void Dump()
{
#if !uap
if (NetEventSource.IsEnabled)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this,
"Cookie: " + ToString() + "->\n"
+ "\tComment = " + Comment + "\n"
+ "\tCommentUri = " + CommentUri + "\n"
+ "\tDiscard = " + Discard + "\n"
+ "\tDomain = " + Domain + "\n"
+ "\tExpired = " + Expired + "\n"
+ "\tExpires = " + Expires + "\n"
+ "\tName = " + Name + "\n"
+ "\tPath = " + Path + "\n"
+ "\tPort = " + Port + "\n"
+ "\tSecure = " + Secure + "\n"
+ "\tTimeStamp = " + TimeStamp + "\n"
+ "\tValue = " + Value + "\n"
+ "\tVariant = " + Variant + "\n"
+ "\tVersion = " + Version + "\n"
+ "\tHttpOnly = " + HttpOnly + "\n"
);
}
#endif
}
#endif
}
}
| |
/*
| Version 10.1.84
| Copyright 2013 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using ESRI.ArcLogistics.Geometry;
using ESRI.ArcLogistics.Routing.Json;
namespace ESRI.ArcLogistics.Routing
{
/// <summary>
/// Direction route data keeper.
/// </summary>
internal sealed class DirRouteData
{
/// <summary>
/// ID of route.
/// </summary>
public Guid RouteId { get; set; }
/// <summary>
/// Start time of route.
/// </summary>
public DateTime? StartTime { get; set; }
/// <summary>
/// Stops.
/// </summary>
public IList<StopData> Stops { get; set; }
}
/// <summary>
/// Route solve request data keeper.
/// </summary>
internal sealed class RouteSolveRequestData
{
/// <summary>
/// Direction's route data.
/// </summary>
public DirRouteData Route { get; set; }
/// <summary>
/// Point Barriers features.
/// </summary>
public GPFeature[] PointBarriers { get; set; }
/// <summary>
/// Polygon barriers features.
/// </summary>
public GPFeature[] PolygonBarriers { get; set; }
/// <summary>
/// Polyline barriers features.
/// </summary>
public GPFeature[] PolylineBarriers { get; set; }
}
/// <summary>
/// Route request builder class.
/// </summary>
internal sealed class RouteRequestBuilder
{
#region Constructors
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Initializes a new instance of the <c>RouteRequestBuilder</c> class.
/// </summary>
/// <param name="context">Solver context.</param>
public RouteRequestBuilder(SolverContext context)
{
_context = context;
}
#endregion Constructors
#region Public properties
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Json types.
/// </summary>
public static IEnumerable<Type> JsonTypes
{
get { return jsonTypes; }
}
#endregion // Public properties
#region Public methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Builds request.
/// </summary>
/// <param name="reqData">Route solve request data.</param>
/// <returns>Created route solve request.</returns>
public RouteSolveRequest BuildRequest(RouteSolveRequestData reqData)
{
Debug.Assert(reqData != null);
var req = new RouteSolveRequest();
// stops
req.Stops = _BuildStopFeatures(reqData.Route.Stops);
// Point barriers.
if (reqData.PointBarriers != null)
{
req.PointBarriers = new RouteRecordSet();
req.PointBarriers.Features = reqData.PointBarriers;
}
// Polygon barriers.
if (reqData.PolygonBarriers != null)
{
req.PolygonBarriers = new RouteRecordSet();
req.PolygonBarriers.Features = reqData.PolygonBarriers;
}
// Polyline barriers.
if (reqData.PolylineBarriers != null)
{
req.PolylineBarriers = new RouteRecordSet();
req.PolylineBarriers.Features = reqData.PolylineBarriers;
}
// start time
req.StartTime = (reqData.Route.StartTime == null) ?
NONE_TIME_VALUE : _FormatEpochTime(reqData.Route.StartTime.Value);
req.ReturnDirections = true;
req.ReturnRoutes = false;
req.ReturnStops = false;
req.ReturnBarriers = false;
req.OutSR = GeometryConst.WKID_WGS84;
req.IgnoreInvalidLocations = _context.SolverSettings.ExcludeRestrictedStreets;
req.OutputLines = Enum.GetName(typeof(NAOutputLineType),
NAOutputLineType.esriNAOutputLineTrueShapeWithMeasure);
req.FindBestSequence = false;
req.PreserveFirstStop = true;
req.PreserveLastStop = true;
req.UseTimeWindows = true;
req.AccumulateAttributeNames = null;
req.ImpedanceAttributeName = _context.NetworkDescription.ImpedanceAttributeName;
req.RestrictionAttributeNames = _FormatRestrictions();
req.AttributeParameters = _FormatAttrParameters();
req.RestrictUTurns = _GetUTurnPolicy();
req.UseHierarchy = true;
req.DirectionsLanguage = _GetDirLanguage();
req.OutputGeometryPrecision = null;
req.OutputGeometryPrecisionUnits = null;
NANetworkAttributeUnits unit = RequestBuildingHelper.GetDirectionsLengthUnits();
req.DirectionsLengthUnits = unit.ToString();
req.DirectionsTimeAttributeName = null;
req.OutputFormat = NAOutputFormat.JSON;
return req;
}
#endregion // Public methods
#region Private static methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Gets direction language name for sending to ArcGIS server.
/// </summary>
/// <returns>Current direction language name.</returns>
/// <remarks>ArcGIS expects underscore as languagecode/regioncode delimiter.</remarks>
private static string _GetDirLanguage()
{
return RequestBuildingHelper.GetDirectionsLanguage().Replace('-', '_');
}
/// <summary>
/// Gets effective TimeWindow.
/// </summary>
/// <param name="stop">Stop data.</param>
/// <param name="twStart">Start timewindow (can be null).</param>
/// <param name="twEnd">End timewindow (can be null).</param>
/// <returns>TRUE if twStart and twEnd not null.</returns>
private static bool _GetEffectiveTW(StopData stop,
out DateTime? twStart,
out DateTime? twEnd)
{
Debug.Assert(stop != null);
twStart = null;
twEnd = null;
bool hasTW1 = (stop.TimeWindowStart1 != null && stop.TimeWindowEnd1 != null);
bool hasTW2 = (stop.TimeWindowStart2 != null && stop.TimeWindowEnd2 != null);
DateTime? start = null;
DateTime? end = null;
bool result = false;
if (stop.StopType == StopType.Order || stop.StopType == StopType.Location)
{
// Orders and locations have 2 time windows, need to choose appropriate one.
if (hasTW1 && hasTW2)
{
// Find and set time window, where time of arrival falls within the range.
if (stop.ArriveTime <= (DateTime)stop.TimeWindowEnd1)
{
start = stop.TimeWindowStart1;
end = stop.TimeWindowEnd1;
}
else
{
start = stop.TimeWindowStart2;
end = stop.TimeWindowEnd2;
}
}
else
{
// Set one of existed time windows.
if (hasTW1)
{
start = stop.TimeWindowStart1;
end = stop.TimeWindowEnd1;
}
else if (hasTW2)
{
start = stop.TimeWindowStart2;
end = stop.TimeWindowEnd2;
}
}
}
else if (stop.StopType == StopType.Lunch)
{
if (hasTW1)
{
// Breaks have only one time window.
start = stop.TimeWindowStart1;
end = stop.TimeWindowEnd1;
}
}
if (start != null && end != null)
{
twStart = start;
twEnd = end;
result = true;
}
return result;
}
/// <summary>
/// Converts the specified date/time into string suitable.
/// </summary>
/// <param name="date">Date/time to conversion</param>
/// <returns></returns>
/// <remarks>Should be specified as a numeric value representing the
/// milliseconds since midnight January 1, 1970.</remarks>
private static string _FormatEpochTime(DateTime date)
{
long epoch = (long)(date - new DateTime(1970, 1, 1)).TotalMilliseconds;
return Convert.ToString(epoch, fmtProvider);
}
/// <summary>
/// Converts the specified date/time into string suitable for sending
/// to ArcGIS server.
/// </summary>
/// <param name="date">The date/time value to be formatted.</param>
/// <returns>The reference to the string representing <paramref name="date"/>
/// or null reference if <paramref name="date"/> is null.</returns>
private static string _FormatStopTime(DateTime? date)
{
return (date.HasValue) ? Convert.ToString(date.Value, fmtProvider) : null;
}
/// <summary>
/// Converts network attributes to route attribute parameters.
/// </summary>
/// <param name="attrs">Network attributes.</param>
/// <param name="settings">Solver settings.</param>
/// <returns>Route attribute parameters.</returns>
private static RouteAttrParameters _ConvertAttrParameters(
ICollection<NetworkAttribute> attrs,
SolverSettings settings)
{
Debug.Assert(attrs != null);
Debug.Assert(settings != null);
var list = new List<RouteAttrParameter>();
foreach (NetworkAttribute attr in attrs)
{
foreach (NetworkAttributeParameter param in attr.Parameters)
{
object value = null;
if (settings.GetNetworkAttributeParameterValue(attr.Name, param.Name, out value))
{
// skip null value overrides, let the service to use defaults
if (value != null)
{
var p = new RouteAttrParameter();
p.AttrName = attr.Name;
p.ParamName = param.Name;
p.Value = value;
list.Add(p);
}
}
}
}
var res = new RouteAttrParameters();
res.Parameters = list.ToArray();
return res;
}
#endregion // Private static methods
#region Private methods
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Builds stop features.
/// </summary>
/// <param name="stops">Stops.</param>
/// <returns>Created route stops recordset for stops.</returns>
private RouteStopsRecordSet _BuildStopFeatures(IList<StopData> stops)
{
Debug.Assert(stops != null);
// Sort stops respecting sequence.
var sortedStops = new List<StopData>(stops);
SolveHelper.SortBySequence(sortedStops);
Debug.Assert(_context != null);
SolveHelper.ConsiderArrivalDelayInStops(
_context.SolverSettings.ArriveDepartDelay, sortedStops);
// Format impedance attribute name.
string impedanceAttrName = null;
if (!string.IsNullOrEmpty(_context.NetworkDescription.ImpedanceAttributeName))
{
impedanceAttrName = string.Format(IMPEDANCE_ATTR_FORMAT,
_context.NetworkDescription.ImpedanceAttributeName);
}
var features = new List<GPFeature>();
for (int index = 0; index < sortedStops.Count; ++index)
{
var feature = new GPFeature();
// Attributes.
feature.Attributes = new AttrDictionary();
StopData sd = sortedStops[index];
Guid objectId = Guid.Empty;
if (sd.AssociatedObject != null)
objectId = sd.AssociatedObject.Id;
feature.Attributes.Add(NAAttribute.NAME, objectId.ToString());
feature.Attributes.Add(NAAttribute.ROUTE_NAME, sd.RouteId.ToString());
// Effective time window.
DateTime? twStart = null;
DateTime? twEnd = null;
_GetEffectiveTW(sd, out twStart, out twEnd); // NOTE: ignore result
feature.Attributes.Add(NAAttribute.TW_START, _FormatStopTime(twStart));
feature.Attributes.Add(NAAttribute.TW_END, _FormatStopTime(twEnd));
// Service time.
if (impedanceAttrName != null)
feature.Attributes.Add(impedanceAttrName, sd.TimeAtStop);
var geometry = new GeometryHolder();
geometry.Value = sd.Geometry;
if (sd.StopType == StopType.Lunch)
{
var actualStop = SolveHelper.GetActualLunchStop(sortedStops, index);
geometry.Value = actualStop.Geometry;
}
// Set curb approach.
var curbApproach = CurbApproachConverter.ToNACurbApproach(
_context.SolverSettings.GetOrderCurbApproach());
if (sd.StopType == StopType.Location)
{
curbApproach = CurbApproachConverter.ToNACurbApproach(
_context.SolverSettings.GetDepotCurbApproach());
}
feature.Attributes.Add(NAAttribute.CURB_APPROACH, (int)curbApproach);
feature.Geometry = geometry;
features.Add(feature);
}
var rs = new RouteStopsRecordSet();
rs.Features = features.ToArray();
// TODO: will be changed later when support custom AddLocations tool
rs.DoNotLocateOnRestrictedElements = _context.SolverSettings.ExcludeRestrictedStreets;
return rs;
}
/// <summary>
/// Converts restrictions to text.
/// </summary>
/// <returns>Restrictions string.</returns>
private string _FormatRestrictions()
{
ICollection<string> restrictions = SolveHelper.GetEnabledRestrictionNames(
_context.SolverSettings.Restrictions);
string resStr = string.Empty;
if (restrictions != null && restrictions.Count > 0)
{
var list = new List<string>(restrictions);
resStr = string.Join(RESTRICTIONS_DELIMITER, list.ToArray());
}
return resStr;
}
/// <summary>
/// Converts attribute parameters to text.
/// </summary>
/// <returns>Attribute parameters string.</returns>
private string _FormatAttrParameters()
{
string result = null;
RouteAttrParameters parameters = _ConvertAttrParameters(
_context.NetworkDescription.NetworkAttributes,
_context.SolverSettings);
if (parameters.Parameters.Length > 0)
{
string value = JsonSerializeHelper.Serialize(parameters);
Match match = Regex.Match(value, "\\[.+\\]");
if (!match.Success || string.IsNullOrEmpty(match.Value))
throw new RouteException(Properties.Messages.Error_AttrParametersFormat); // exception
result = match.Value;
}
return result;
}
/// <summary>
/// Gets NARoute U-Turn policy.
/// </summary>
/// <returns>NARoute U-Turn policy according by UTurn policy from SolverSettings.</returns>
private string _GetUTurnPolicy()
{
UTurnPolicy policy = _context.SolverSettings.GetUTurnPolicy();
string value = NARouteUTurnPolicy.NoUTurns;
switch (policy)
{
case UTurnPolicy.Nowhere:
value = NARouteUTurnPolicy.NoUTurns;
break;
case UTurnPolicy.AtDeadEnds:
value = NARouteUTurnPolicy.AllowDeadEndsOnly;
break;
case UTurnPolicy.AtDeadEndsAndIntersections:
value = NARouteUTurnPolicy.AllowDeadEndsAndIntersectionsOnly;
break;
default:
// Not supported.
Debug.Assert(false);
break;
}
return value;
}
#endregion Private methods
#region Constants
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Restriction list delimiter.
/// </summary>
private const string RESTRICTIONS_DELIMITER = ",";
/// <summary>
/// Impedance attribute name format.
/// </summary>
private const string IMPEDANCE_ATTR_FORMAT = "Attr_{0}";
/// <summary>
/// A value to indicate that a start time should not be used,
/// </summary>
private const string NONE_TIME_VALUE = "none";
/// <summary>
/// Data contract custom types.
/// </summary>
private static readonly Type[] jsonTypes = new Type[]
{
typeof(GPDate),
typeof(double[][][])
};
/// <summary>
/// Predifined culture-specific formatting information.
/// </summary>
private static readonly CultureInfo fmtProvider = new CultureInfo("en-US");
#endregion // Constants
#region Private fields
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Solver context.
/// </summary>
private SolverContext _context;
#endregion // Private fields
}
}
| |
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.IdentityModel.Selectors
{
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Runtime.ConstrainedExecution;
using System.Runtime.CompilerServices;
using System.Security.Cryptography;
using IDT = Microsoft.InfoCards.Diagnostics.InfoCardTrace;
using DiagnosticUtility = Microsoft.InfoCards.Diagnostics.DiagnosticUtility;
//
// For common & resources
//
using Microsoft.InfoCards;
//
// Summary:
// This class provides indirect access to the private key associated with a released token via InfoCard
// native crypto functions.
//
internal class InfoCardRSACryptoProvider : RSA
{
AsymmetricCryptoHandle m_cryptoHandle;
RpcAsymmetricCryptoParameters m_params;
//
// Summary:
// Given a pointer to a CryptoHandle create a new instance of this class.
//
public InfoCardRSACryptoProvider(AsymmetricCryptoHandle cryptoHandle)
: base()
{
m_cryptoHandle = (AsymmetricCryptoHandle)cryptoHandle.Duplicate();
try
{
m_params = (RpcAsymmetricCryptoParameters)m_cryptoHandle.Parameters;
int keySize = m_params.keySize;
LegalKeySizesValue = new KeySizes[1];
KeySizeValue = keySize;
LegalKeySizesValue[0] = new KeySizes(keySize, keySize, 0);
}
catch
{
m_cryptoHandle.Dispose();
m_cryptoHandle = null;
throw;
}
}
public override String SignatureAlgorithm
{
get { return m_params.signatureAlgorithm; }
}
public override String KeyExchangeAlgorithm
{
get { return m_params.keyExchangeAlgorithm; }
}
public override byte[] EncryptValue(byte[] rgb)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override byte[] DecryptValue(byte[] rgb)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public byte[] Decrypt(byte[] inData, bool fAOEP)
{
GlobalAllocSafeHandle pOutData = null;
int cbOutData = 0;
byte[] outData;
IDT.ThrowInvalidArgumentConditional(null == inData, "indata");
using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inData.Length))
{
Marshal.Copy(inData, 0, pInData.DangerousGetHandle(), inData.Length);
int status = CardSpaceSelector.GetShim().m_csShimDecrypt(m_cryptoHandle.InternalHandle,
fAOEP,
inData.Length,
pInData,
out cbOutData,
out pOutData);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pOutData.Length = cbOutData;
outData = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
using (pOutData)
{
Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
}
}
return outData;
}
public byte[] Encrypt(byte[] inData, bool fAOEP)
{
GlobalAllocSafeHandle pOutData = null;
int cbOutData = 0;
byte[] outData;
IDT.ThrowInvalidArgumentConditional(null == inData, "indata");
using (HGlobalSafeHandle pInData = HGlobalSafeHandle.Construct(inData.Length))
{
Marshal.Copy(inData, 0, pInData.DangerousGetHandle(), inData.Length);
int status = CardSpaceSelector.GetShim().m_csShimEncrypt(m_cryptoHandle.InternalHandle,
fAOEP,
inData.Length,
pInData,
out cbOutData,
out pOutData);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pOutData.Length = cbOutData;
outData = DiagnosticUtility.Utility.AllocateByteArray(pOutData.Length);
Marshal.Copy(pOutData.DangerousGetHandle(), outData, 0, pOutData.Length);
}
return outData;
}
public byte[] SignHash(byte[] hash, string hashAlgOid)
{
IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
int cbSig = 0;
GlobalAllocSafeHandle pSig = null;
byte[] sig;
using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
{
using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
{
Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);
RuntimeHelpers.PrepareConstrainedRegions();
int status = CardSpaceSelector.GetShim().m_csShimSignHash(m_cryptoHandle.InternalHandle,
hash.Length,
pHash,
pHashAlgOid,
out cbSig,
out pSig);
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
pSig.Length = cbSig;
sig = DiagnosticUtility.Utility.AllocateByteArray(pSig.Length);
using (pSig)
{
Marshal.Copy(pSig.DangerousGetHandle(), sig, 0, pSig.Length);
}
}
}
return sig;
}
public bool VerifyHash(byte[] hash, string hashAlgOid, byte[] sig)
{
IDT.ThrowInvalidArgumentConditional(null == hash || 0 == hash.Length, "hash");
IDT.ThrowInvalidArgumentConditional(String.IsNullOrEmpty(hashAlgOid), "hashAlgOid");
IDT.ThrowInvalidArgumentConditional(null == sig || 0 == sig.Length, "sig");
bool verified = false;
using (HGlobalSafeHandle pHash = HGlobalSafeHandle.Construct(hash.Length))
{
using (HGlobalSafeHandle pHashAlgOid = HGlobalSafeHandle.Construct(hashAlgOid))
{
Marshal.Copy(hash, 0, pHash.DangerousGetHandle(), hash.Length);
int status = 0;
using (HGlobalSafeHandle pSig = HGlobalSafeHandle.Construct(sig.Length))
{
Marshal.Copy(sig, 0, pSig.DangerousGetHandle(), sig.Length);
status = CardSpaceSelector.GetShim().m_csShimVerifyHash(m_cryptoHandle.InternalHandle,
hash.Length,
pHash,
pHashAlgOid,
sig.Length,
pSig,
out verified);
}
if (0 != status)
{
ExceptionHelper.ThrowIfCardSpaceException(status);
throw IDT.ThrowHelperError(new Win32Exception(status));
}
}
}
return verified;
}
public override RSAParameters ExportParameters(bool includePrivateParameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override string ToXmlString(bool includePrivateParameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override void FromXmlString(string xmlString)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
public override void ImportParameters(System.Security.Cryptography.RSAParameters parameters)
{
throw IDT.ThrowHelperError(new NotSupportedException());
}
protected override void Dispose(bool disposing)
{
m_cryptoHandle.Dispose();
}
}
}
| |
/* **********************************************************************************************************
* The MIT License (MIT) *
* *
* Copyright (c) 2016 Hypermediasystems Ges. f. Software mbH *
* Web: http://www.hypermediasystems.de *
* This file is part of hmssp *
* *
* 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.Dynamic;
using System.Reflection;
using Newtonsoft.Json;
namespace HMS.SP{
/// <summary>
/// <para>https://msdn.microsoft.com/en-us/library/office/jj245920.aspx#properties</para>
/// </summary>
public class UserCustomAction : SPBase{
[JsonProperty("__HMSError")]
public HMS.Util.__HMSError __HMSError_ { set; get; }
[JsonProperty("__status")]
public SP.__status __status_ { set; get; }
[JsonProperty("__deferred")]
public SP.__deferred __deferred_ { set; get; }
[JsonProperty("__metadata")]
public SP.__metadata __metadata_ { set; get; }
public Dictionary<string, string> __rest;
/// <summary>
/// <para>Gets or sets a value that specifies an implementation specific XML fragment that determines user interface properties of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj244922.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("CommandUIExtension")]
public String CommandUIExtension_ { set; get; }
/// <summary>
/// <para>Gets or sets the description of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Description")]
public String Description_ { set; get; }
/// <summary>
/// <para>Gets or sets the description of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj246343.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("DescriptionResource")]
public SP.__deferred DescriptionResource_ { set; get; }
/// <summary>
/// <para>Gets or sets a value that specifies an implementation-specific value that determines the position of the custom action in the page.(s. https://msdn.microsoft.com/en-us/library/office/jj245924.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Group")]
public String Group_ { set; get; }
// undefined class Undefined : Object { }
/// <summary>
/// <para>Gets a value that specifies the identifier of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245809.aspx)[Undefined]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Id")]
public Object Id_ { set; get; }
/// <summary>
/// <para>Gets or sets the URL of the image associated with the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245413.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ImageUrl")]
public String ImageUrl_ { set; get; }
/// <summary>
/// <para>Gets or sets the location of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245731.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Location")]
public String Location_ { set; get; }
/// <summary>
/// <para>Gets or sets the name of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj247011.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Name")]
public String Name_ { set; get; }
/// <summary>
/// <para>Gets or sets the value that specifies the identifier of the object associated with the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj246754.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("RegistrationId")]
public String RegistrationId_ { set; get; }
// undefined class SP.UserCustomActionRegistrationType : Object { }
/// <summary>
/// <para>Gets or sets the value that specifies the type of object associated with the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj244938.aspx)[SP.UserCustomActionRegistrationType]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("RegistrationType")]
public Object RegistrationType_ { set; get; }
/// <summary>
/// <para>Gets or sets the value that specifies the permissions needed for the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245623.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Rights")]
public SP.BasePermissions Rights_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies the scope of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj247140.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Scope")]
public String Scope_ { set; get; }
/// <summary>
/// <para>Gets or sets the value that specifies the ECMAScript to be executed when the custom action is performed.(s. https://msdn.microsoft.com/en-us/library/office/jj246651.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ScriptBlock")]
public String ScriptBlock_ { set; get; }
/// <summary>
/// <para>Gets or sets a value that specifies the URI of a file which contains the ECMAScript to execute on the page.(s. https://msdn.microsoft.com/en-us/library/office/jj245179.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("ScriptSrc")]
public String ScriptSrc_ { set; get; }
/// <summary>
/// <para>Gets or sets the value that specifies an implementation-specific value that determines the order of the custom action that appears on the page.(s. https://msdn.microsoft.com/en-us/library/office/jj246287.aspx) [Number]</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Sequence")]
public Int32 Sequence_ { set; get; }
/// <summary>
/// <para>Gets or sets the display title of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245739.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Title")]
public String Title_ { set; get; }
/// <summary>
/// <para>Gets or sets the display title of the custom action.(s. https://msdn.microsoft.com/en-us/library/office/jj245739.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("TitleResource")]
public SP.__deferred TitleResource_ { set; get; }
/// <summary>
/// <para>Gets or sets the URL, URI, or ECMAScript (JScript, JavaScript) function associated with the action.(s. https://msdn.microsoft.com/en-us/library/office/jj247021.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("Url")]
public String Url_ { set; get; }
/// <summary>
/// <para>Gets a value that specifies an implementation specific version identifier.(s. https://msdn.microsoft.com/en-us/library/office/jj245883.aspx)</para>
/// <para>R/W: </para>
/// <para>Returned with resource:</para>
/// </summary>
[JsonProperty("VersionOfUserCustomAction")]
public String VersionOfUserCustomAction_ { set; get; }
/// <summary>
/// <para> Endpoints </para>
/// </summary>
static string[] endpoints = {
};
public UserCustomAction(ExpandoObject expObj)
{
try
{
var use_EO = ((dynamic)expObj).entry.content.properties;
HMS.SP.SPUtil.expando2obj(use_EO, this, typeof(UserCustomAction));
}
catch (Exception ex)
{
}
}
// used by Newtonsoft.JSON
public UserCustomAction()
{
}
public UserCustomAction(string json)
{
if( json == String.Empty )
return;
dynamic jobject = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
dynamic refObj = jobject;
if (jobject.d != null)
refObj = jobject.d;
string errInfo = "";
if (refObj.results != null)
{
if (refObj.results.Count > 1)
errInfo = "Result is Collection, only 1. entry displayed.";
refObj = refObj.results[0];
}
List<string> usedFields = new List<string>();
usedFields.Add("__HMSError");
HMS.SP.SPUtil.dyn_ValueSet("__HMSError", refObj, this);
usedFields.Add("__deferred");
this.__deferred_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.__deferred));
usedFields.Add("__metadata");
this.__metadata_ = new SP.__metadata(HMS.SP.SPUtil.dyn_toString(refObj.__metadata));
usedFields.Add("CommandUIExtension");
HMS.SP.SPUtil.dyn_ValueSet("CommandUIExtension", refObj, this);
usedFields.Add("Description");
HMS.SP.SPUtil.dyn_ValueSet("Description", refObj, this);
usedFields.Add("DescriptionResource");
this.DescriptionResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.DescriptionResource));
usedFields.Add("Group");
HMS.SP.SPUtil.dyn_ValueSet("Group", refObj, this);
usedFields.Add("Id");
HMS.SP.SPUtil.dyn_ValueSet("Id", refObj, this);
usedFields.Add("ImageUrl");
HMS.SP.SPUtil.dyn_ValueSet("ImageUrl", refObj, this);
usedFields.Add("Location");
HMS.SP.SPUtil.dyn_ValueSet("Location", refObj, this);
usedFields.Add("Name");
HMS.SP.SPUtil.dyn_ValueSet("Name", refObj, this);
usedFields.Add("RegistrationId");
HMS.SP.SPUtil.dyn_ValueSet("RegistrationId", refObj, this);
usedFields.Add("RegistrationType");
HMS.SP.SPUtil.dyn_ValueSet("RegistrationType", refObj, this);
usedFields.Add("Rights");
this.Rights_ = new SP.BasePermissions(HMS.SP.SPUtil.dyn_toString(refObj.Rights));
usedFields.Add("Scope");
HMS.SP.SPUtil.dyn_ValueSet("Scope", refObj, this);
usedFields.Add("ScriptBlock");
HMS.SP.SPUtil.dyn_ValueSet("ScriptBlock", refObj, this);
usedFields.Add("ScriptSrc");
HMS.SP.SPUtil.dyn_ValueSet("ScriptSrc", refObj, this);
usedFields.Add("Sequence");
HMS.SP.SPUtil.dyn_ValueSet("Sequence", refObj, this);
usedFields.Add("Title");
HMS.SP.SPUtil.dyn_ValueSet("Title", refObj, this);
usedFields.Add("TitleResource");
this.TitleResource_ = new SP.__deferred(HMS.SP.SPUtil.dyn_toString(refObj.TitleResource));
usedFields.Add("Url");
HMS.SP.SPUtil.dyn_ValueSet("Url", refObj, this);
usedFields.Add("VersionOfUserCustomAction");
HMS.SP.SPUtil.dyn_ValueSet("VersionOfUserCustomAction", refObj, this);
this.__rest = new Dictionary<string, string>();
var dyn = ((Newtonsoft.Json.Linq.JContainer)refObj).First;
while (dyn != null)
{
string Name = ((Newtonsoft.Json.Linq.JProperty)dyn).Name;
string Value = ((Newtonsoft.Json.Linq.JProperty)dyn).Value.ToString();
if ( !usedFields.Contains( Name ))
this.__rest.Add( Name, Value);
dyn = dyn.Next;
}
if( errInfo != "")
this.__HMSError_.info = errInfo;
}
}
}
| |
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 FrontRangeSystems.WebTechnologies.Web.Areas.HelpPage.ModelDescriptions;
using FrontRangeSystems.WebTechnologies.Web.Areas.HelpPage.Models;
namespace FrontRangeSystems.WebTechnologies.Web.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// Licensed to the .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.Reflection.Emit
{
using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Diagnostics.Contracts;
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class GenericTypeParameterBuilder: TypeInfo
{
public override bool IsAssignableFrom(System.Reflection.TypeInfo typeInfo){
if(typeInfo==null) return false;
return IsAssignableFrom(typeInfo.AsType());
}
#region Private Data Mebers
internal TypeBuilder m_type;
#endregion
#region Constructor
internal GenericTypeParameterBuilder(TypeBuilder type)
{
m_type = type;
}
#endregion
#region Object Overrides
public override String ToString()
{
return m_type.Name;
}
public override bool Equals(object o)
{
GenericTypeParameterBuilder g = o as GenericTypeParameterBuilder;
if (g == null)
return false;
return object.ReferenceEquals(g.m_type, m_type);
}
public override int GetHashCode() { return m_type.GetHashCode(); }
#endregion
#region MemberInfo Overrides
public override Type DeclaringType { get { return m_type.DeclaringType; } }
public override Type ReflectedType { get { return m_type.ReflectedType; } }
public override String Name { get { return m_type.Name; } }
public override Module Module { get { return m_type.Module; } }
internal int MetadataTokenInternal { get { return m_type.MetadataTokenInternal; } }
#endregion
#region Type Overrides
public override Type MakePointerType()
{
return SymbolType.FormCompoundType("*", this, 0);
}
public override Type MakeByRefType()
{
return SymbolType.FormCompoundType("&", this, 0);
}
public override Type MakeArrayType()
{
return SymbolType.FormCompoundType("[]", this, 0);
}
public override Type MakeArrayType(int rank)
{
if (rank <= 0)
throw new IndexOutOfRangeException();
Contract.EndContractBlock();
string szrank = "";
if (rank == 1)
{
szrank = "*";
}
else
{
for(int i = 1; i < rank; i++)
szrank += ",";
}
string s = String.Format(CultureInfo.InvariantCulture, "[{0}]", szrank); // [,,]
SymbolType st = SymbolType.FormCompoundType(s, this, 0) as SymbolType;
return st;
}
public override Guid GUID { get { throw new NotSupportedException(); } }
public override Object InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParameters) { throw new NotSupportedException(); }
public override Assembly Assembly { get { return m_type.Assembly; } }
public override RuntimeTypeHandle TypeHandle { get { throw new NotSupportedException(); } }
public override String FullName { get { return null; } }
public override String Namespace { get { return null; } }
public override String AssemblyQualifiedName { get { return null; } }
public override Type BaseType { get { return m_type.BaseType; } }
protected override ConstructorInfo GetConstructorImpl(BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override ConstructorInfo[] GetConstructors(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override MethodInfo GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConvention, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override MethodInfo[] GetMethods(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo GetField(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override FieldInfo[] GetFields(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetInterface(String name, bool ignoreCase) { throw new NotSupportedException(); }
public override Type[] GetInterfaces() { throw new NotSupportedException(); }
public override EventInfo GetEvent(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents() { throw new NotSupportedException(); }
protected override PropertyInfo GetPropertyImpl(String name, BindingFlags bindingAttr, Binder binder, Type returnType, Type[] types, ParameterModifier[] modifiers) { throw new NotSupportedException(); }
public override PropertyInfo[] GetProperties(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type[] GetNestedTypes(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override Type GetNestedType(String name, BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMember(String name, MemberTypes type, BindingFlags bindingAttr) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
public override InterfaceMapping GetInterfaceMap(Type interfaceType) { throw new NotSupportedException(); }
public override EventInfo[] GetEvents(BindingFlags bindingAttr) { throw new NotSupportedException(); }
public override MemberInfo[] GetMembers(BindingFlags bindingAttr) { throw new NotSupportedException(); }
protected override TypeAttributes GetAttributeFlagsImpl() { return TypeAttributes.Public; }
protected override bool IsArrayImpl() { return false; }
protected override bool IsByRefImpl() { return false; }
protected override bool IsPointerImpl() { return false; }
protected override bool IsPrimitiveImpl() { return false; }
protected override bool IsCOMObjectImpl() { return false; }
public override Type GetElementType() { throw new NotSupportedException(); }
protected override bool HasElementTypeImpl() { return false; }
public override Type UnderlyingSystemType { get { return this; } }
public override Type[] GetGenericArguments() { throw new InvalidOperationException(); }
public override bool IsGenericTypeDefinition { get { return false; } }
public override bool IsGenericType { get { return false; } }
public override bool IsGenericParameter { get { return true; } }
public override bool IsConstructedGenericType { get { return false; } }
public override int GenericParameterPosition { get { return m_type.GenericParameterPosition; } }
public override bool ContainsGenericParameters { get { return m_type.ContainsGenericParameters; } }
public override GenericParameterAttributes GenericParameterAttributes { get { return m_type.GenericParameterAttributes; } }
public override MethodBase DeclaringMethod { get { return m_type.DeclaringMethod; } }
public override Type GetGenericTypeDefinition() { throw new InvalidOperationException(); }
public override Type MakeGenericType(params Type[] typeArguments) { throw new InvalidOperationException(Environment.GetResourceString("Arg_NotGenericTypeDefinition")); }
protected override bool IsValueTypeImpl() { return false; }
public override bool IsAssignableFrom(Type c) { throw new NotSupportedException(); }
[System.Runtime.InteropServices.ComVisible(true)]
[Pure]
public override bool IsSubclassOf(Type c) { throw new NotSupportedException(); }
#endregion
#region ICustomAttributeProvider Implementation
public override Object[] GetCustomAttributes(bool inherit) { throw new NotSupportedException(); }
public override Object[] GetCustomAttributes(Type attributeType, bool inherit) { throw new NotSupportedException(); }
public override bool IsDefined(Type attributeType, bool inherit) { throw new NotSupportedException(); }
#endregion
#region Public Members
#if FEATURE_CORECLR
[System.Security.SecurityCritical] // auto-generated
#endif
public void SetCustomAttribute(ConstructorInfo con, byte[] binaryAttribute)
{
m_type.SetGenParamCustomAttribute(con, binaryAttribute);
}
public void SetCustomAttribute(CustomAttributeBuilder customBuilder)
{
m_type.SetGenParamCustomAttribute(customBuilder);
}
public void SetBaseTypeConstraint(Type baseTypeConstraint)
{
m_type.CheckContext(baseTypeConstraint);
m_type.SetParent(baseTypeConstraint);
}
[System.Runtime.InteropServices.ComVisible(true)]
public void SetInterfaceConstraints(params Type[] interfaceConstraints)
{
m_type.CheckContext(interfaceConstraints);
m_type.SetInterfaces(interfaceConstraints);
}
public void SetGenericParameterAttributes(GenericParameterAttributes genericParameterAttributes)
{
m_type.SetGenParamAttributes(genericParameterAttributes);
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.