context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
/// <summary>
/// This class collects runtime statistics for all silos in the current deployment for use by placement.
/// </summary>
internal class DeploymentLoadPublisher : SystemTarget, IDeploymentLoadPublisher, ISiloStatusListener
{
private readonly ILocalSiloDetails siloDetails;
private readonly ISiloPerformanceMetrics siloMetrics;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly IInternalGrainFactory grainFactory;
private readonly OrleansTaskScheduler scheduler;
private readonly ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> periodicStats;
private readonly TimeSpan statisticsRefreshTime;
private readonly IList<ISiloStatisticsChangeListener> siloStatisticsChangeListeners;
private readonly Logger logger = LogManager.GetLogger("DeploymentLoadPublisher", LoggerType.Runtime);
private IDisposable publishTimer;
public ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics> PeriodicStatistics { get { return periodicStats; } }
public DeploymentLoadPublisher(
ILocalSiloDetails siloDetails,
ISiloPerformanceMetrics siloMetrics,
ISiloStatusOracle siloStatusOracle,
GlobalConfiguration config,
IInternalGrainFactory grainFactory,
OrleansTaskScheduler scheduler)
: base(Constants.DeploymentLoadPublisherSystemTargetId, siloDetails.SiloAddress)
{
this.siloDetails = siloDetails;
this.siloMetrics = siloMetrics;
this.siloStatusOracle = siloStatusOracle;
this.grainFactory = grainFactory;
this.scheduler = scheduler;
statisticsRefreshTime = config.DeploymentLoadPublisherRefreshTime;
periodicStats = new ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>();
siloStatisticsChangeListeners = new List<ISiloStatisticsChangeListener>();
}
public async Task Start()
{
logger.Info("Starting DeploymentLoadPublisher.");
if (statisticsRefreshTime > TimeSpan.Zero)
{
var random = new SafeRandom();
// Randomize PublishStatistics timer,
// but also upon start publish my stats to everyone and take everyone's stats for me to start with something.
var randomTimerOffset = random.NextTimeSpan(statisticsRefreshTime);
this.publishTimer = this.RegisterTimer(PublishStatistics, null, randomTimerOffset, statisticsRefreshTime, "DeploymentLoadPublisher.PublishStatisticsTimer");
}
await RefreshStatistics();
await PublishStatistics(null);
logger.Info("Started DeploymentLoadPublisher.");
}
private async Task PublishStatistics(object _)
{
try
{
if(logger.IsVerbose) logger.Verbose("PublishStatistics.");
List<SiloAddress> members = this.siloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList();
var tasks = new List<Task>();
var myStats = new SiloRuntimeStatistics(this.siloMetrics, DateTime.UtcNow);
foreach (var siloAddress in members)
{
try
{
tasks.Add(this.grainFactory.GetSystemTarget<IDeploymentLoadPublisher>(
Constants.DeploymentLoadPublisherSystemTargetId, siloAddress)
.UpdateRuntimeStatistics(this.siloDetails.SiloAddress, myStats));
}
catch (Exception)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_1,
String.Format("An unexpected exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignored."));
}
}
await Task.WhenAll(tasks);
}
catch (Exception exc)
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_2,
String.Format("An exception was thrown by PublishStatistics.UpdateRuntimeStatistics(). Ignoring."), exc);
}
}
public Task UpdateRuntimeStatistics(SiloAddress siloAddress, SiloRuntimeStatistics siloStats)
{
if (logger.IsVerbose) logger.Verbose("UpdateRuntimeStatistics from {0}", siloAddress);
if (this.siloStatusOracle.GetApproximateSiloStatus(siloAddress) != SiloStatus.Active)
return Task.CompletedTask;
SiloRuntimeStatistics old;
// Take only if newer.
if (periodicStats.TryGetValue(siloAddress, out old) && old.DateTime > siloStats.DateTime)
return Task.CompletedTask;
periodicStats[siloAddress] = siloStats;
NotifyAllStatisticsChangeEventsSubscribers(siloAddress, siloStats);
return Task.CompletedTask;
}
internal async Task<ConcurrentDictionary<SiloAddress, SiloRuntimeStatistics>> RefreshStatistics()
{
if (logger.IsVerbose) logger.Verbose("RefreshStatistics.");
await this.scheduler.RunOrQueueTask( () =>
{
var tasks = new List<Task>();
List<SiloAddress> members = this.siloStatusOracle.GetApproximateSiloStatuses(true).Keys.ToList();
foreach (var siloAddress in members)
{
var capture = siloAddress;
Task task = this.grainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, capture)
.GetRuntimeStatistics()
.ContinueWith((Task<SiloRuntimeStatistics> statsTask) =>
{
if (statsTask.Status == TaskStatus.RanToCompletion)
{
UpdateRuntimeStatistics(capture, statsTask.Result);
}
else
{
logger.Warn(ErrorCode.Placement_RuntimeStatisticsUpdateFailure_3,
String.Format("An unexpected exception was thrown from RefreshStatistics by ISiloControl.GetRuntimeStatistics({0}). Will keep using stale statistics.", capture),
statsTask.Exception);
}
});
tasks.Add(task);
task.Ignore();
}
return Task.WhenAll(tasks);
}, SchedulingContext);
return periodicStats;
}
public bool SubscribeToStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
if (siloStatisticsChangeListeners.Contains(observer)) return false;
siloStatisticsChangeListeners.Add(observer);
return true;
}
}
public bool UnsubscribeStatisticsChangeEvents(ISiloStatisticsChangeListener observer)
{
lock (siloStatisticsChangeListeners)
{
return siloStatisticsChangeListeners.Contains(observer) &&
siloStatisticsChangeListeners.Remove(observer);
}
}
private void NotifyAllStatisticsChangeEventsSubscribers(SiloAddress silo, SiloRuntimeStatistics stats)
{
lock (siloStatisticsChangeListeners)
{
foreach (var subscriber in siloStatisticsChangeListeners)
{
if (stats==null)
{
subscriber.RemoveSilo(silo);
}
else
{
subscriber.SiloStatisticsChangeNotification(silo, stats);
}
}
}
}
public void SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
this.ScheduleTask(() => { Utils.SafeExecute(() => this.OnSiloStatusChange(updatedSilo, status), this.logger); }).Ignore();
}
private void OnSiloStatusChange(SiloAddress updatedSilo, SiloStatus status)
{
if (!status.IsTerminating()) return;
if (Equals(updatedSilo, this.Silo))
this.publishTimer.Dispose();
SiloRuntimeStatistics ignore;
periodicStats.TryRemove(updatedSilo, out ignore);
NotifyAllStatisticsChangeEventsSubscribers(updatedSilo, null);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using gcsv = Google.Cloud.SecurityCenter.V1P1Beta1;
using sys = System;
namespace Google.Cloud.SecurityCenter.V1P1Beta1
{
/// <summary>Resource name for the <c>SecurityMarks</c> resource.</summary>
public sealed partial class SecurityMarksName : gax::IResourceName, sys::IEquatable<SecurityMarksName>
{
/// <summary>The possible contents of <see cref="SecurityMarksName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </summary>
OrganizationAsset = 1,
/// <summary>
/// A resource name with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
OrganizationSourceFinding = 2,
/// <summary>A resource name with pattern <c>folders/{folder}/assets/{asset}/securityMarks</c>.</summary>
FolderAsset = 3,
/// <summary>A resource name with pattern <c>projects/{project}/assets/{asset}/securityMarks</c>.</summary>
ProjectAsset = 4,
/// <summary>
/// A resource name with pattern <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
FolderSourceFinding = 5,
/// <summary>
/// A resource name with pattern <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>
/// .
/// </summary>
ProjectSourceFinding = 6,
}
private static gax::PathTemplate s_organizationAsset = new gax::PathTemplate("organizations/{organization}/assets/{asset}/securityMarks");
private static gax::PathTemplate s_organizationSourceFinding = new gax::PathTemplate("organizations/{organization}/sources/{source}/findings/{finding}/securityMarks");
private static gax::PathTemplate s_folderAsset = new gax::PathTemplate("folders/{folder}/assets/{asset}/securityMarks");
private static gax::PathTemplate s_projectAsset = new gax::PathTemplate("projects/{project}/assets/{asset}/securityMarks");
private static gax::PathTemplate s_folderSourceFinding = new gax::PathTemplate("folders/{folder}/sources/{source}/findings/{finding}/securityMarks");
private static gax::PathTemplate s_projectSourceFinding = new gax::PathTemplate("projects/{project}/sources/{source}/findings/{finding}/securityMarks");
/// <summary>Creates a <see cref="SecurityMarksName"/> 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="SecurityMarksName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static SecurityMarksName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new SecurityMarksName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromOrganizationAsset(string organizationId, string assetId) =>
new SecurityMarksName(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromOrganizationSourceFinding(string organizationId, string sourceId, string findingId) =>
new SecurityMarksName(ResourceNameType.OrganizationSourceFinding, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern <c>folders/{folder}/assets/{asset}/securityMarks</c>
/// .
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromFolderAsset(string folderId, string assetId) =>
new SecurityMarksName(ResourceNameType.FolderAsset, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern
/// <c>projects/{project}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromProjectAsset(string projectId, string assetId) =>
new SecurityMarksName(ResourceNameType.ProjectAsset, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern
/// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromFolderSourceFinding(string folderId, string sourceId, string findingId) =>
new SecurityMarksName(ResourceNameType.FolderSourceFinding, folderId: gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Creates a <see cref="SecurityMarksName"/> with the pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="SecurityMarksName"/> constructed from the provided ids.</returns>
public static SecurityMarksName FromProjectSourceFinding(string projectId, string sourceId, string findingId) =>
new SecurityMarksName(ResourceNameType.ProjectSourceFinding, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), sourceId: gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), findingId: gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </returns>
public static string Format(string organizationId, string assetId) => FormatOrganizationAsset(organizationId, assetId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>.
/// </returns>
public static string FormatOrganizationAsset(string organizationId, string assetId) =>
s_organizationAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </returns>
public static string FormatOrganizationSourceFinding(string organizationId, string sourceId, string findingId) =>
s_organizationSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>folders/{folder}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>folders/{folder}/assets/{asset}/securityMarks</c>.
/// </returns>
public static string FormatFolderAsset(string folderId, string assetId) =>
s_folderAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>projects/{project}/assets/{asset}/securityMarks</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>projects/{project}/assets/{asset}/securityMarks</c>.
/// </returns>
public static string FormatProjectAsset(string projectId, string assetId) =>
s_projectAsset.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="folderId">The <c>Folder</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </returns>
public static string FormatFolderSourceFinding(string folderId, string sourceId, string findingId) =>
s_folderSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(folderId, nameof(folderId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="sourceId">The <c>Source</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="findingId">The <c>Finding</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="SecurityMarksName"/> with pattern
/// <c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c>.
/// </returns>
public static string FormatProjectSourceFinding(string projectId, string sourceId, string findingId) =>
s_projectSourceFinding.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(sourceId, nameof(sourceId)), gax::GaxPreconditions.CheckNotNullOrEmpty(findingId, nameof(findingId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="SecurityMarksName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description>
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>
/// </description>
/// </item>
/// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// <item>
/// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="SecurityMarksName"/> if successful.</returns>
public static SecurityMarksName Parse(string securityMarksName) => Parse(securityMarksName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="SecurityMarksName"/> 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>organizations/{organization}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description>
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>
/// </description>
/// </item>
/// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// <item>
/// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="securityMarksName">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="SecurityMarksName"/> if successful.</returns>
public static SecurityMarksName Parse(string securityMarksName, bool allowUnparsed) =>
TryParse(securityMarksName, allowUnparsed, out SecurityMarksName 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="SecurityMarksName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item><description><c>organizations/{organization}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description>
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>
/// </description>
/// </item>
/// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// <item>
/// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="securityMarksName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="SecurityMarksName"/>, 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 securityMarksName, out SecurityMarksName result) =>
TryParse(securityMarksName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="SecurityMarksName"/> 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>organizations/{organization}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description>
/// <c>organizations/{organization}/sources/{source}/findings/{finding}/securityMarks</c>
/// </description>
/// </item>
/// <item><description><c>folders/{folder}/assets/{asset}/securityMarks</c></description></item>
/// <item><description><c>projects/{project}/assets/{asset}/securityMarks</c></description></item>
/// <item>
/// <description><c>folders/{folder}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// <item>
/// <description><c>projects/{project}/sources/{source}/findings/{finding}/securityMarks</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="securityMarksName">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="SecurityMarksName"/>, 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 securityMarksName, bool allowUnparsed, out SecurityMarksName result)
{
gax::GaxPreconditions.CheckNotNull(securityMarksName, nameof(securityMarksName));
gax::TemplatedResourceName resourceName;
if (s_organizationAsset.TryParseName(securityMarksName, out resourceName))
{
result = FromOrganizationAsset(resourceName[0], resourceName[1]);
return true;
}
if (s_organizationSourceFinding.TryParseName(securityMarksName, out resourceName))
{
result = FromOrganizationSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_folderAsset.TryParseName(securityMarksName, out resourceName))
{
result = FromFolderAsset(resourceName[0], resourceName[1]);
return true;
}
if (s_projectAsset.TryParseName(securityMarksName, out resourceName))
{
result = FromProjectAsset(resourceName[0], resourceName[1]);
return true;
}
if (s_folderSourceFinding.TryParseName(securityMarksName, out resourceName))
{
result = FromFolderSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (s_projectSourceFinding.TryParseName(securityMarksName, out resourceName))
{
result = FromProjectSourceFinding(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(securityMarksName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private SecurityMarksName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string assetId = null, string findingId = null, string folderId = null, string organizationId = null, string projectId = null, string sourceId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
AssetId = assetId;
FindingId = findingId;
FolderId = folderId;
OrganizationId = organizationId;
ProjectId = projectId;
SourceId = sourceId;
}
/// <summary>
/// Constructs a new instance of a <see cref="SecurityMarksName"/> class from the component parts of pattern
/// <c>organizations/{organization}/assets/{asset}/securityMarks</c>
/// </summary>
/// <param name="organizationId">The <c>Organization</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="assetId">The <c>Asset</c> ID. Must not be <c>null</c> or empty.</param>
public SecurityMarksName(string organizationId, string assetId) : this(ResourceNameType.OrganizationAsset, organizationId: gax::GaxPreconditions.CheckNotNullOrEmpty(organizationId, nameof(organizationId)), assetId: gax::GaxPreconditions.CheckNotNullOrEmpty(assetId, nameof(assetId)))
{
}
/// <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>Asset</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string AssetId { get; }
/// <summary>
/// The <c>Finding</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FindingId { get; }
/// <summary>
/// The <c>Folder</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string FolderId { get; }
/// <summary>
/// The <c>Organization</c> ID. May be <c>null</c>, depending on which resource name is contained by this
/// instance.
/// </summary>
public string OrganizationId { get; }
/// <summary>
/// The <c>Project</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The <c>Source</c> ID. May be <c>null</c>, depending on which resource name is contained by this instance.
/// </summary>
public string SourceId { 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.OrganizationAsset: return s_organizationAsset.Expand(OrganizationId, AssetId);
case ResourceNameType.OrganizationSourceFinding: return s_organizationSourceFinding.Expand(OrganizationId, SourceId, FindingId);
case ResourceNameType.FolderAsset: return s_folderAsset.Expand(FolderId, AssetId);
case ResourceNameType.ProjectAsset: return s_projectAsset.Expand(ProjectId, AssetId);
case ResourceNameType.FolderSourceFinding: return s_folderSourceFinding.Expand(FolderId, SourceId, FindingId);
case ResourceNameType.ProjectSourceFinding: return s_projectSourceFinding.Expand(ProjectId, SourceId, FindingId);
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 SecurityMarksName);
/// <inheritdoc/>
public bool Equals(SecurityMarksName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(SecurityMarksName a, SecurityMarksName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(SecurityMarksName a, SecurityMarksName b) => !(a == b);
}
public partial class SecurityMarks
{
/// <summary>
/// <see cref="gcsv::SecurityMarksName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcsv::SecurityMarksName SecurityMarksName
{
get => string.IsNullOrEmpty(Name) ? null : gcsv::SecurityMarksName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
}
| |
#region License, Terms and Author(s)
//
// ELMAH - Error Logging Modules and Handlers for ASP.NET
// Copyright (c) 2004-9 Atif Aziz. All rights reserved.
//
// Author(s):
//
// Scott Wilson <sw@scratchstudio.net>
// Atif Aziz, http://www.raboof.com
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion
[assembly: Elmah.Scc("$Id: XmlFileErrorLog.cs 795 2011-02-16 22:29:34Z azizatif $")]
namespace Elmah
{
#region Imports
using System;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using IDictionary = System.Collections.IDictionary;
#endregion
/// <summary>
/// An <see cref="ErrorLog"/> implementation that uses XML files stored on
/// disk as its backing store.
/// </summary>
public class XmlFileErrorLog : ErrorLog
{
private readonly string _logPath;
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// using a dictionary of configured settings.
/// </summary>
public XmlFileErrorLog(IDictionary config)
{
if (config == null) throw new ArgumentNullException("config");
var logPath = config.Find("logPath", string.Empty);
if (logPath.Length == 0)
{
//
// For compatibility reasons with older version of this
// implementation, we also try "LogPath".
//
logPath = config.Find("LogPath", string.Empty);
if (logPath.Length == 0)
throw new ApplicationException("Log path is missing for the XML file-based error log.");
}
if (logPath.StartsWith("~/"))
logPath = MapPath(logPath);
_logPath = logPath;
}
/// <remarks>
/// This method is excluded from inlining so that if
/// HostingEnvironment does not need JIT-ing if it is not implicated
/// by the caller.
/// </remarks>
[ MethodImpl(MethodImplOptions.NoInlining) ]
private static string MapPath(string path)
{
return System.Web.Hosting.HostingEnvironment.MapPath(path);
}
/// <summary>
/// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class
/// to use a specific path to store/load XML files.
/// </summary>
public XmlFileErrorLog(string logPath)
{
if (logPath == null) throw new ArgumentNullException("logPath");
if (logPath.Length == 0) throw new ArgumentException(null, "logPath");
_logPath = logPath;
}
/// <summary>
/// Gets the path to where the log is stored.
/// </summary>
public virtual string LogPath
{
get { return _logPath; }
}
/// <summary>
/// Gets the name of this error log implementation.
/// </summary>
public override string Name
{
get { return "XML File-Based Error Log"; }
}
/// <summary>
/// Logs an error to the database.
/// </summary>
/// <remarks>
/// Logs an error as a single XML file stored in a folder. XML files are named with a
/// sortable date and a unique identifier. Currently the XML files are stored indefinately.
/// As they are stored as files, they may be managed using standard scheduled jobs.
/// </remarks>
public override string Log(Error error)
{
var logPath = LogPath;
if (!Directory.Exists(logPath))
Directory.CreateDirectory(logPath);
var errorId = Guid.NewGuid().ToString();
var timeStamp = (error.Time > DateTime.MinValue ? error.Time : DateTime.Now);
var fileName = string.Format(CultureInfo.InvariantCulture,
@"error-{0:yyyy-MM-ddHHmmssZ}-{1}.xml",
/* 0 */ timeStamp.ToUniversalTime(),
/* 1 */ errorId);
var path = Path.Combine(logPath, fileName);
using (var writer = new XmlTextWriter(path, Encoding.UTF8))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartElement("error");
writer.WriteAttributeString("errorId", errorId);
ErrorXml.Encode(error, writer);
writer.WriteEndElement();
writer.Flush();
}
return errorId;
}
/// <summary>
/// Returns a page of errors from the folder in descending order
/// of logged time as defined by the sortable filenames.
/// </summary>
public override int GetErrors(int pageIndex, int pageSize, ICollection<ErrorLogEntry> errorEntryList)
{
if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null);
if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null);
var logPath = LogPath;
var dir = new DirectoryInfo(logPath);
if (!dir.Exists)
return 0;
var infos = dir.GetFiles("error-*.xml");
if (!infos.Any())
return 0;
var files = infos.Where(info => IsUserFile(info.Attributes))
.OrderBy(info => info.Name, StringComparer.OrdinalIgnoreCase)
.Select(info => Path.Combine(logPath, info.Name))
.Reverse()
.ToArray();
if (errorEntryList != null)
{
var entries = files.Skip(pageIndex * pageSize)
.Take(pageSize)
.Select(LoadErrorLogEntry);
foreach (var entry in entries)
errorEntryList.Add(entry);
}
return files.Length; // Return total
}
private ErrorLogEntry LoadErrorLogEntry(string path)
{
using (var reader = XmlReader.Create(path))
{
if (!reader.IsStartElement("error"))
return null;
var id = reader.GetAttribute("errorId");
var error = ErrorXml.Decode(reader);
return new ErrorLogEntry(this, id, error);
}
}
/// <summary>
/// Returns the specified error from the filesystem, or throws an exception if it does not exist.
/// </summary>
public override ErrorLogEntry GetError(string id)
{
try
{
id = (new Guid(id)).ToString(); // validate GUID
}
catch (FormatException e)
{
throw new ArgumentException(e.Message, id, e);
}
var file = new DirectoryInfo(LogPath).GetFiles(string.Format("error-*-{0}.xml", id))
.FirstOrDefault();
if (file == null)
return null;
if (!IsUserFile(file.Attributes))
return null;
using (var reader = XmlReader.Create(file.FullName))
return new ErrorLogEntry(this, id, ErrorXml.Decode(reader));
}
private static bool IsUserFile(FileAttributes attributes)
{
return 0 == (attributes & (FileAttributes.Directory |
FileAttributes.Hidden |
FileAttributes.System));
}
}
}
| |
// 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Testing;
using Test.Utilities;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.UseLiteralsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines.CSharpUseLiteralsWhereAppropriateFixer>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.CodeQuality.Analyzers.QualityGuidelines.UseLiteralsWhereAppropriateAnalyzer,
Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines.BasicUseLiteralsWhereAppropriateFixer>;
namespace Microsoft.CodeQuality.Analyzers.QualityGuidelines.UnitTests
{
public class UseLiteralsWhereAppropriateTests
{
[Fact]
public async Task CA1802_Diagnostics_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
static readonly string f1 = """";
static readonly string f2 = ""Nothing"";
static readonly string f3,f4 = ""Message is shown only for f4"";
static readonly int f5 = 3;
const int f6 = 3;
static readonly int f7 = 8 + f6;
internal static readonly int f8 = 8 + f6;
}",
GetCSharpEmptyStringResultAt(line: 4, column: 28, symbolName: "f1"),
GetCSharpDefaultResultAt(line: 5, column: 28, symbolName: "f2"),
GetCSharpDefaultResultAt(line: 6, column: 31, symbolName: "f4"),
GetCSharpDefaultResultAt(line: 7, column: 25, symbolName: "f5"),
GetCSharpDefaultResultAt(line: 9, column: 25, symbolName: "f7"),
GetCSharpDefaultResultAt(line: 10, column: 34, symbolName: "f8"));
}
[Fact]
public async Task CA1802_NoDiagnostics_CSharp()
{
await VerifyCS.VerifyAnalyzerAsync(@"
public class Class1
{
public static readonly string f1 = """"; // Not private or Internal
static string f3, f4 = ""Message is shown only for f4""; // Not readonly
readonly int f5 = 3; // Not static
const int f6 = 3; // Is already const
static int f9 = getF9();
static readonly int f7 = 8 + f9; // f9 is not a const
static readonly string f8 = null; // null value
private static int getF9()
{
throw new System.NotImplementedException();
}
}");
}
[Fact]
public async Task CA1802_Diagnostics_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
Shared ReadOnly f1 As String = """"
Shared ReadOnly f2 As String = ""Nothing""
Shared ReadOnly f3 As String, f4 As String = ""Message is shown only for f4""
Shared ReadOnly f5 As Integer = 3
Const f6 As Integer = 3
Shared ReadOnly f7 As Integer = 8 + f6
Friend Shared ReadOnly f8 As Integer = 8 + f6
End Class",
GetBasicEmptyStringResultAt(line: 3, column: 21, symbolName: "f1"),
GetBasicDefaultResultAt(line: 4, column: 21, symbolName: "f2"),
GetBasicDefaultResultAt(line: 5, column: 35, symbolName: "f4"),
GetBasicDefaultResultAt(line: 6, column: 21, symbolName: "f5"),
GetBasicDefaultResultAt(line: 8, column: 21, symbolName: "f7"),
GetBasicDefaultResultAt(line: 9, column: 28, symbolName: "f8"));
}
[Fact]
public async Task CA1802_NoDiagnostics_VisualBasic()
{
await VerifyVB.VerifyAnalyzerAsync(@"
Public Class Class1
' Not Private or Friend
Public Shared ReadOnly f1 As String = """"
' Not Readonly
Shared f3 As String, f4 As String = ""Message is shown only for f4""
' Not Shared
ReadOnly f5 As Integer = 3
' Is already Const
Const f6 As Integer = 3
Shared f9 As Integer = getF9()
' f9 is not a Const
Shared ReadOnly f7 As Integer = 8 + f9
' null value
Shared ReadOnly f8 As String = Nothing
Private Shared Function getF9() As Integer
Throw New System.NotImplementedException()
End Function
End Class");
}
[Theory]
[WorkItem(2772, "https://github.com/dotnet/roslyn-analyzers/issues/2772")]
[InlineData("", false)]
[InlineData("dotnet_code_quality.required_modifiers = static", false)]
[InlineData("dotnet_code_quality.required_modifiers = none", true)]
[InlineData("dotnet_code_quality." + UseLiteralsWhereAppropriateAnalyzer.RuleId + ".required_modifiers = none", true)]
public async Task EditorConfigConfiguration_RequiredModifiersOption(string editorConfigText, bool reportDiagnostic)
{
var expected = Array.Empty<DiagnosticResult>();
if (reportDiagnostic)
{
expected = new[]
{
GetCSharpDefaultResultAt(4, 26, "field")
};
}
var csTest = new VerifyCS.Test
{
TestState =
{
Sources =
{
@"
public class Test
{
private readonly int field = 0;
}
"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
},
};
csTest.ExpectedDiagnostics.AddRange(expected);
await csTest.RunAsync();
expected = Array.Empty<DiagnosticResult>();
if (reportDiagnostic)
{
expected = new[]
{
GetBasicDefaultResultAt(3, 22, "field")
};
}
var vbTest = new VerifyVB.Test
{
TestState =
{
Sources =
{
@"
Public Class Test
Private ReadOnly field As Integer = 0
End Class
"
},
AnalyzerConfigFiles = { ("/.editorconfig", $@"root = true
[*]
{editorConfigText}
") }
}
};
vbTest.ExpectedDiagnostics.AddRange(expected);
await vbTest.RunAsync();
}
[Fact]
public async Task CA1802_CSharp_IntPtr_UIntPtr_NoDiagnostic()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
public class Class1
{
internal static readonly IntPtr field1 = (nint)0;
internal static readonly UIntPtr field2 = (nuint)0;
}",
}.RunAsync();
}
[Fact]
public async Task CA1802_CSharp_nint_Diagnostic()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
public class Class1
{
internal static readonly nint field = (nint)0;
}",
ExpectedDiagnostics =
{
GetCSharpDefaultResultAt(6, 35, "field"),
},
FixedCode = @"
using System;
public class Class1
{
internal const nint field = (nint)0;
}",
}.RunAsync();
}
[Fact]
public async Task CA1802_CSharp_nuint_Diagnostic()
{
await new VerifyCS.Test
{
LanguageVersion = CodeAnalysis.CSharp.LanguageVersion.CSharp9,
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
public class Class1
{
internal static readonly nuint field = (nuint)0;
}",
ExpectedDiagnostics =
{
GetCSharpDefaultResultAt(6, 36, "field"),
},
FixedCode = @"
using System;
public class Class1
{
internal const nuint field = (nuint)0;
}",
}.RunAsync();
}
private static DiagnosticResult GetCSharpDefaultResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(UseLiteralsWhereAppropriateAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
private static DiagnosticResult GetCSharpEmptyStringResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(UseLiteralsWhereAppropriateAnalyzer.EmptyStringRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
private static DiagnosticResult GetBasicDefaultResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(UseLiteralsWhereAppropriateAnalyzer.DefaultRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
private static DiagnosticResult GetBasicEmptyStringResultAt(int line, int column, string symbolName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(UseLiteralsWhereAppropriateAnalyzer.EmptyStringRule)
.WithLocation(line, column)
#pragma warning restore RS0030 // Do not used banned APIs
.WithArguments(symbolName);
}
}
| |
// 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.Batch.Fluent
{
using Models;
using ResourceManager.Fluent;
using ResourceManager.Fluent.Core.ResourceActions;
using Storage.Fluent;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using ResourceManager.Fluent.Core;
using System;
/// <summary>
/// Implementation for BatchAccount and its parent interfaces.
/// </summary>
///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50LmJhdGNoLmltcGxlbWVudGF0aW9uLkJhdGNoQWNjb3VudEltcGw=
internal partial class BatchAccountImpl :
GroupableResource<
IBatchAccount,
BatchAccountInner,
BatchAccountImpl,
IBatchManager,
BatchAccount.Definition.IWithGroup,
BatchAccount.Definition.IWithCreateAndApplication,
BatchAccount.Definition.IWithCreate,
BatchAccount.Update.IUpdate>,
IBatchAccount,
BatchAccount.Definition.IDefinition,
BatchAccount.Update.IUpdate
{
private IStorageManager storageManager;
private string creatableStorageAccountKey;
private IStorageAccount existingStorageAccountToAssociate;
private ApplicationsImpl applicationsImpl;
internal AutoStorageProperties autoStorage;
///GENMHASH:4A1C1CE1A5FD21C2D77E9D249E53B0FC:2CAC092B38BC608EA9EE02AF770A8C0D
internal BatchAccountImpl(
string name,
BatchAccountInner innerObject,
IBatchManager manager,
IStorageManager storageManager)
: base(name, innerObject, manager)
{
this.storageManager = storageManager;
applicationsImpl = new ApplicationsImpl(this);
}
///GENMHASH:4002186478A1CB0B59732EBFB18DEB3A:7CF0E4D2E689061F164F4E8CBEEE0032
public override async Task<IBatchAccount> RefreshAsync(CancellationToken cancellationToken = default(CancellationToken))
{
var inner = await GetInnerAsync(cancellationToken);
SetInner(inner);
applicationsImpl.Refresh();
return this;
}
///GENMHASH:0202A00A1DCF248D2647DBDBEF2CA865:8F640179247B56242D756EB9A20DC705
public async override Task<IBatchAccount> CreateResourceAsync(CancellationToken cancellationToken = default(CancellationToken))
{
HandleStorageSettings();
var batchAccountCreateParametersInner = new BatchAccountCreateParametersInner();
if (autoStorage != null)
{
batchAccountCreateParametersInner.AutoStorage = new AutoStorageBaseProperties
{
StorageAccountId = autoStorage.StorageAccountId
};
}
else
{
batchAccountCreateParametersInner.AutoStorage = null;
}
batchAccountCreateParametersInner.Location = Inner.Location;
batchAccountCreateParametersInner.Tags = Inner.Tags;
var batchAccountInner = await Manager.Inner.BatchAccount.CreateAsync(
ResourceGroupName,
Name,
batchAccountCreateParametersInner,
cancellationToken);
creatableStorageAccountKey = null;
SetInner(batchAccountInner);
await applicationsImpl.CommitAndGetAllAsync(cancellationToken);
return this;
}
///GENMHASH:99D5BF64EA8AA0E287C9B6F77AAD6FC4:220D4662AAC7DF3BEFAF2B253278E85C
internal Management.Batch.Fluent.Models.ProvisioningState ProvisioningState()
{
return Inner.ProvisioningState;
}
///GENMHASH:3FCA66079CE54B6624051AEEEA92C0A8:CD2239198F90BF2EF64E021F6D70308F
internal string AccountEndpoint()
{
return Inner.AccountEndpoint;
}
///GENMHASH:CDDA70CBBBCD12B0E5E922B6DE5C4E73:D188D673E338A86FF211CD3448D22B56
internal AutoStorageProperties AutoStorage()
{
return Inner.AutoStorage;
}
///GENMHASH:B9408D6B67E96EFD3D03881CF8649A9C:954939482CB158B1E2B509B48B09585C
internal int CoreQuota()
{
return Inner.DedicatedCoreQuota;
}
///GENMHASH:7909615C516BD4E70FB021746FE02F60:CF51957E04C09A383C5B34AB6DFDC9EB
internal int PoolQuota()
{
return Inner.PoolQuota;
}
///GENMHASH:016AA742D37BA9FE61D68507B4F6B530:31B3ECE969CEF408EACD27E4747DBA41
internal int ActiveJobAndJobScheduleQuota()
{
return Inner.ActiveJobAndJobScheduleQuota;
}
///GENMHASH:E4DFA7EA15F8324FB60C810D0C96D2FF:2C24EC1143CD8F8542845A9D3A0F116A
internal async Task<BatchAccountKeys> GetKeysAsync(CancellationToken cancellationToken = default(CancellationToken))
{
BatchAccountKeysInner keys = await Manager.Inner.BatchAccount.GetKeysAsync(ResourceGroupName, Name, cancellationToken);
return new BatchAccountKeys(keys.Primary, keys.Secondary);
}
///GENMHASH:837770291CB03D6C2AB9BDA889A5B07D:916D2188C6A5919A33DB6C700CE38C2A
internal async Task<BatchAccountKeys> RegenerateKeysAsync(AccountKeyType keyType, CancellationToken cancellationToken = default(CancellationToken))
{
BatchAccountKeysInner keys = await Manager.Inner.BatchAccount.RegenerateKeyAsync(ResourceGroupName, Name, keyType, cancellationToken);
return new BatchAccountKeys(keys.Primary, keys.Secondary);
}
///GENMHASH:F464067830773D729F2254E152F52E95:21A9F1295EB43C714008C5226DECA98E
internal async Task SynchronizeAutoStorageKeysAsync(CancellationToken cancellationToken = default(CancellationToken))
{
await Manager.Inner.BatchAccount.SynchronizeAutoStorageKeysAsync(ResourceGroupName, Name, cancellationToken);
}
///GENMHASH:672E69F72385496EBDF873EB27A7AA15:C0743C8E69844064A4120ADE2213CA5B
internal IReadOnlyDictionary<string, IApplication> Applications()
{
return applicationsImpl.AsMap();
}
///GENMHASH:8CB9B7EEE4A4226A6F5BBB2958CC5E81:86F388ADD8163A5736375494E42FD140
internal BatchAccountImpl WithExistingStorageAccount(IStorageAccount storageAccount)
{
existingStorageAccountToAssociate = storageAccount;
creatableStorageAccountKey = null;
return this;
}
///GENMHASH:2DC51FEC3C45675856B4AC1D97BECBFD:7DBF1A9A29FD54AF8FCA5A4E2F414F87
internal BatchAccountImpl WithNewStorageAccount(ICreatable<IStorageAccount> creatable)
{
// This method's effect is NOT additive.
if (creatableStorageAccountKey == null)
{
creatableStorageAccountKey = creatable.Key;
AddCreatableDependency(creatable as IResourceCreator<IHasId>);
}
existingStorageAccountToAssociate = null;
return this;
}
///GENMHASH:5880487AA9218E8DF536932A49A0ACDD:FB1BAD32BA28A79F5AF97AFA7ED0EE6E
internal BatchAccountImpl WithNewStorageAccount(string storageAccountName)
{
var definitionWithGroup = storageManager.
StorageAccounts.
Define(storageAccountName).
WithRegion(RegionName);
Storage.Fluent.StorageAccount.Definition.IWithCreate definitionAfterGroup;
if (newGroup != null)
{
definitionAfterGroup = definitionWithGroup.WithNewResourceGroup(newGroup);
}
else
{
definitionAfterGroup = definitionWithGroup.WithExistingResourceGroup(ResourceGroupName);
}
return WithNewStorageAccount(definitionAfterGroup);
}
///GENMHASH:15D36ECAB00E9FCCF84FA127687D0CE2:A6E982618362E7F801925E23A6B4B4C2
internal BatchAccountImpl WithoutStorageAccount()
{
existingStorageAccountToAssociate = null;
creatableStorageAccountKey = null;
this.autoStorage = null;
return this;
}
///GENMHASH:37FFE6BCAA81A22948354048E4226C80:39897EDD4A6BF2A85F51AA6E4ACCEFCF
internal ApplicationImpl DefineNewApplication(string applicationId)
{
return applicationsImpl.Define(applicationId);
}
///GENMHASH:AA28D9B344860923503977841560DF90:ECF6C949F03691F2AE2B18AA1E90F53D
internal ApplicationImpl UpdateApplication(string applicationId)
{
return applicationsImpl.Update(applicationId);
}
///GENMHASH:0BB4AB6DEA8235ECDBD2F532E365AC87:533E5AAA5CEA9D252A01CBDB74B3516C
internal BatchAccountImpl WithoutApplication(string applicationId)
{
applicationsImpl.Remove(applicationId);
return this;
}
///GENMHASH:C15DF8874364A70E09E929DF4B25106C:344A96E970807288B64F734F13C74B04
private void HandleStorageSettings()
{
IStorageAccount storageAccount;
if (!string.IsNullOrWhiteSpace(creatableStorageAccountKey))
{
storageAccount = (IStorageAccount)CreatedResource(creatableStorageAccountKey);
}
else if (existingStorageAccountToAssociate != null)
{
storageAccount = existingStorageAccountToAssociate;
}
else
{
return;
}
if (autoStorage == null)
{
autoStorage = new AutoStorageProperties();
}
autoStorage.StorageAccountId = storageAccount.Id;
}
///GENMHASH:901BF64732D40F1AFA2D615FD2C9EC6C:88A053E647AE5BA086B9195689F16CA9
internal BatchAccountImpl WithApplication(ApplicationImpl application)
{
applicationsImpl.AddApplication(application);
return this;
}
protected override async Task<BatchAccountInner> GetInnerAsync(CancellationToken cancellationToken)
{
return await Manager.Inner.BatchAccount.GetAsync(ResourceGroupName, Name, cancellationToken: cancellationToken);
}
}
}
| |
// 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.Collections.ObjectModel;
using System.ComponentModel.Composition.Factories;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Linq;
using System.UnitTesting;
using Xunit;
namespace System.ComponentModel.Composition
{
public class MetadataTests
{
#region Tests for metadata on exports
public enum SimpleEnum
{
First
}
[PartNotDiscoverable]
[Export]
[ExportMetadata("String", "42")]
[ExportMetadata("Int", 42)]
[ExportMetadata("Float", 42.0f)]
[ExportMetadata("Enum", SimpleEnum.First)]
[ExportMetadata("Type", typeof(string))]
[ExportMetadata("Object", 42)]
public class SimpleMetadataExporter
{
}
[PartNotDiscoverable]
[Export]
[ExportMetadata("String", null)] // null
[ExportMetadata("Int", 42)]
[ExportMetadata("Float", 42.0f)]
[ExportMetadata("Enum", SimpleEnum.First)]
[ExportMetadata("Type", typeof(string))]
[ExportMetadata("Object", 42)]
public class SimpleMetadataExporterWithNullReferenceValue
{
}
[PartNotDiscoverable]
[Export]
[ExportMetadata("String", "42")]
[ExportMetadata("Int", null)] //null
[ExportMetadata("Float", 42.0f)]
[ExportMetadata("Enum", SimpleEnum.First)]
[ExportMetadata("Type", typeof(string))]
[ExportMetadata("Object", 42)]
public class SimpleMetadataExporterWithNullNonReferenceValue
{
}
[PartNotDiscoverable]
[Export]
[ExportMetadata("String", "42")]
[ExportMetadata("Int", "42")] // wrong type
[ExportMetadata("Float", 42.0f)]
[ExportMetadata("Enum", SimpleEnum.First)]
[ExportMetadata("Type", typeof(string))]
[ExportMetadata("Object", 42)]
public class SimpleMetadataExporterWithTypeMismatch
{
}
public interface ISimpleMetadataView
{
string String { get; }
int Int { get; }
float Float { get; }
SimpleEnum Enum { get; }
Type Type { get; }
object Object { get; }
}
[Fact]
public void SimpleMetadataTest()
{
var container = ContainerFactory.Create();
container.ComposeParts(new SimpleMetadataExporter());
var export = container.GetExport<SimpleMetadataExporter, ISimpleMetadataView>();
Assert.Equal("42", export.Metadata.String);
Assert.Equal(42, export.Metadata.Int);
Assert.Equal(42.0f, export.Metadata.Float);
Assert.Equal(SimpleEnum.First, export.Metadata.Enum);
Assert.Equal(typeof(string), export.Metadata.Type);
Assert.Equal(42, export.Metadata.Object);
}
[Fact]
public void SimpleMetadataTestWithNullReferenceValue()
{
var container = ContainerFactory.Create();
container.ComposeParts(new SimpleMetadataExporterWithNullReferenceValue());
var export = container.GetExport<SimpleMetadataExporterWithNullReferenceValue, ISimpleMetadataView>();
Assert.Equal(null, export.Metadata.String);
Assert.Equal(42, export.Metadata.Int);
Assert.Equal(42.0f, export.Metadata.Float);
Assert.Equal(SimpleEnum.First, export.Metadata.Enum);
Assert.Equal(typeof(string), export.Metadata.Type);
Assert.Equal(42, export.Metadata.Object);
}
[Fact]
public void SimpleMetadataTestWithNullNonReferenceValue()
{
var container = ContainerFactory.Create();
container.ComposeParts(new SimpleMetadataExporterWithNullNonReferenceValue());
var exports = container.GetExports<SimpleMetadataExporterWithNullNonReferenceValue, ISimpleMetadataView>();
Assert.False(exports.Any());
}
[Fact]
public void SimpleMetadataTestWithTypeMismatch()
{
var container = ContainerFactory.Create();
container.ComposeParts(new SimpleMetadataExporterWithTypeMismatch());
var exports = container.GetExports<SimpleMetadataExporterWithTypeMismatch, ISimpleMetadataView>();
Assert.False(exports.Any());
}
[Fact]
public void ValidMetadataTest()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new MyExporterWithValidMetadata());
container.Compose(batch);
var typeVi = container.GetExport<MyExporterWithValidMetadata, IDictionary<string, object>>();
var metadataFoo = typeVi.Metadata["foo"] as IList<string>;
Assert.Equal(2, metadataFoo.Count());
Assert.True(metadataFoo.Contains("bar1"), "The metadata collection should include value 'bar1'");
Assert.True(metadataFoo.Contains("bar2"), "The metadata collection should include value 'bar2'");
Assert.Equal("world", typeVi.Metadata["hello"]);
Assert.Equal("GoodOneValue2", typeVi.Metadata["GoodOne2"]);
var metadataAcme = typeVi.Metadata["acme"] as IList<object>;
Assert.Equal(2, metadataAcme.Count());
Assert.True(metadataAcme.Contains("acmebar"), "The metadata collection should include value 'bar'");
Assert.True(metadataAcme.Contains(2.0), "The metadata collection should include value 2");
var memberVi = container.GetExport<Func<double>, IDictionary<string, object>>("ContractForValidMetadata");
var metadataBar = memberVi.Metadata["bar"] as IList<string>;
Assert.Equal(2, metadataBar.Count());
Assert.True(metadataBar.Contains("foo1"), "The metadata collection should include value 'foo1'");
Assert.True(metadataBar.Contains("foo2"), "The metadata collection should include value 'foo2'");
Assert.Equal("hello", memberVi.Metadata["world"]);
Assert.Equal("GoodOneValue2", memberVi.Metadata["GoodOne2"]);
var metadataStuff = memberVi.Metadata["stuff"] as IList<object>;
Assert.Equal(2, metadataAcme.Count());
Assert.True(metadataStuff.Contains("acmebar"), "The metadata collection should include value 'acmebar'");
Assert.True(metadataStuff.Contains(2.0), "The metadata collection should include value 2");
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void ValidMetadataDiscoveredByComponentCatalogTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
ValidMetadataDiscoveredByCatalog(container);
}
private void ValidMetadataDiscoveredByCatalog(CompositionContainer container)
{
var export1 = container.GetExport<MyExporterWithValidMetadata, IDictionary<string, object>>();
var metadataFoo = export1.Metadata["foo"] as IList<string>;
Assert.Equal(2, metadataFoo.Count());
Assert.True(metadataFoo.Contains("bar1"), "The metadata collection should include value 'bar1'");
Assert.True(metadataFoo.Contains("bar2"), "The metadata collection should include value 'bar2'");
Assert.Equal("world", export1.Metadata["hello"]);
Assert.Equal("GoodOneValue2", export1.Metadata["GoodOne2"]);
var metadataAcme = export1.Metadata["acme"] as IList<object>;
Assert.Equal(2, metadataAcme.Count());
Assert.True(metadataAcme.Contains("acmebar"), "The metadata collection should include value 'bar'");
Assert.True(metadataAcme.Contains(2.0), "The metadata collection should include value 2");
var export2 = container.GetExport<Func<double>, IDictionary<string, object>>("ContractForValidMetadata");
var metadataBar = export2.Metadata["bar"] as IList<string>;
Assert.Equal(2, metadataBar.Count());
Assert.True(metadataBar.Contains("foo1"), "The metadata collection should include value 'foo1'");
Assert.True(metadataBar.Contains("foo2"), "The metadata collection should include value 'foo2'");
Assert.Equal("hello", export2.Metadata["world"]);
Assert.Equal("GoodOneValue2", export2.Metadata["GoodOne2"]);
var metadataStuff = export2.Metadata["stuff"] as IList<object>;
Assert.Equal(2, metadataAcme.Count());
Assert.True(metadataStuff.Contains("acmebar"), "The metadata collection should include value 'acmebar'");
Assert.True(metadataStuff.Contains(2.0), "The metadata collection should include value 2");
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
[MetadataAttribute]
public class BadStrongMetadata : Attribute
{
public string SelfConflicted { get { return "SelfConflictedValue"; } }
}
[Export]
[BadStrongMetadata]
[ExportMetadata("InvalidCollection", "InvalidCollectionValue1")]
[ExportMetadata("InvalidCollection", "InvalidCollectionValue2", IsMultiple = true)]
[BadStrongMetadata]
[ExportMetadata("RepeatedMetadata", "RepeatedMetadataValue1")]
[ExportMetadata("RepeatedMetadata", "RepeatedMetadataValue2")]
[ExportMetadata("GoodOne1", "GoodOneValue1")]
[ExportMetadata("ConflictedOne1", "ConfilictedOneValue1")]
[GoodStrongMetadata]
[ExportMetadata("ConflictedOne2", "ConflictedOne2Value2")]
[PartNotDiscoverable]
public class MyExporterWithInvalidMetadata
{
[Export("ContractForInvalidMetadata")]
[ExportMetadata("ConflictedOne1", "ConfilictedOneValue1")]
[GoodStrongMetadata]
[ExportMetadata("ConflictedOne2", "ConflictedOne2Value2")]
[ExportMetadata("RepeatedMetadata", "RepeatedMetadataValue1")]
[ExportMetadata("RepeatedMetadata", "RepeatedMetadataValue2")]
[BadStrongMetadata]
[ExportMetadata("InvalidCollection", "InvalidCollectionValue1")]
[ExportMetadata("InvalidCollection", "InvalidCollectionValue2", IsMultiple = true)]
[BadStrongMetadata]
[ExportMetadata("GoodOne1", "GoodOneValue1")]
public double DoSomething() { return 0.618; }
}
[Export]
[ExportMetadata("DuplicateMetadataName", "My Name")]
[ExportMetadata("DuplicateMetadataName", "Your Name")]
[PartNotDiscoverable]
public class ClassWithInvalidDuplicateMetadataOnType
{
}
[Fact]
public void InvalidDuplicateMetadataOnType_ShouldThrow()
{
var part = AttributedModelServices.CreatePart(new ClassWithInvalidDuplicateMetadataOnType());
var export = part.ExportDefinitions.First();
var ex = ExceptionAssert.Throws<InvalidOperationException>(RetryMode.DoNotRetry, () =>
{
var metadata = export.Metadata;
});
Assert.True(ex.Message.Contains("DuplicateMetadataName"));
}
[PartNotDiscoverable]
public class ClassWithInvalidDuplicateMetadataOnMember
{
[Export]
[ExportMetadata("DuplicateMetadataName", "My Name")]
[ExportMetadata("DuplicateMetadataName", "Your Name")]
public ClassWithDuplicateMetadataOnMember Member { get; set; }
}
[Fact]
public void InvalidDuplicateMetadataOnMember_ShouldThrow()
{
var part = AttributedModelServices.CreatePart(new ClassWithInvalidDuplicateMetadataOnMember());
var export = part.ExportDefinitions.First();
var ex = ExceptionAssert.Throws<InvalidOperationException>(RetryMode.DoNotRetry, () =>
{
var metadata = export.Metadata;
});
Assert.True(ex.Message.Contains("DuplicateMetadataName"));
}
[Export]
[ExportMetadata("DuplicateMetadataName", "My Name", IsMultiple = true)]
[ExportMetadata("DuplicateMetadataName", "Your Name", IsMultiple = true)]
public class ClassWithValidDuplicateMetadataOnType
{
}
[Fact]
public void ValidDuplicateMetadataOnType_ShouldDiscoverAllMetadata()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new ClassWithValidDuplicateMetadataOnType());
container.Compose(batch);
var export = container.GetExport<ClassWithValidDuplicateMetadataOnType, IDictionary<string, object>>();
var names = export.Metadata["DuplicateMetadataName"] as string[];
Assert.Equal(2, names.Length);
}
public class ClassWithDuplicateMetadataOnMember
{
[Export]
[ExportMetadata("DuplicateMetadataName", "My Name", IsMultiple = true)]
[ExportMetadata("DuplicateMetadataName", "Your Name", IsMultiple = true)]
public ClassWithDuplicateMetadataOnMember Member { get; set; }
}
[Fact]
public void ValidDuplicateMetadataOnMember_ShouldDiscoverAllMetadata()
{
var container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new ClassWithDuplicateMetadataOnMember());
container.Compose(batch);
var export = container.GetExport<ClassWithDuplicateMetadataOnMember, IDictionary<string, object>>();
var names = export.Metadata["DuplicateMetadataName"] as string[];
Assert.Equal(2, names.Length);
}
[Export]
[ExportMetadata(CompositionConstants.PartCreationPolicyMetadataName, "My Policy")]
[PartNotDiscoverable]
public class ClassWithReservedMetadataValue
{
}
[Fact]
public void InvalidMetadata_UseOfReservedName_ShouldThrow()
{
var part = AttributedModelServices.CreatePart(new ClassWithReservedMetadataValue());
var export = part.ExportDefinitions.First();
var ex = ExceptionAssert.Throws<InvalidOperationException>(RetryMode.DoNotRetry, () =>
{
var metadata = export.Metadata;
});
Assert.True(ex.Message.Contains(CompositionConstants.PartCreationPolicyMetadataName));
}
#endregion
#region Tests for weakly supported metadata as part of contract
[Fact]
[ActiveIssue(468388)]
public void FailureImportForNoRequiredMetadatForExportCollection()
{
CompositionContainer container = ContainerFactory.Create();
MyImporterWithExportCollection importer;
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new MyExporterWithNoMetadata());
batch.AddPart(importer = new MyImporterWithExportCollection());
throw new NotImplementedException();
//var result = container.TryCompose();
//Assert.True(result.Succeeded, "Composition should be successful because collection import is not required");
//Assert.Equal(1, result.Issues.Count);
//Assert.True(result.Issues[0].Description.Contains("Foo"), "The missing required metadata is 'Foo'");
}
[Fact]
[ActiveIssue(472538)]
public void FailureImportForNoRequiredMetadataThroughComponentCatalogTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
FailureImportForNoRequiredMetadataThroughCatalog(container);
}
private void FailureImportForNoRequiredMetadataThroughCatalog(CompositionContainer container)
{
throw new NotImplementedException();
//var export1 = container.GetExport<MyImporterWithExport>();
//export1.TryGetExportedValue().VerifyFailure(CompositionIssueId.RequiredMetadataNotFound, CompositionIssueId.CardinalityMismatch);
//var export2 = container.GetExport<MyImporterWithExportCollection>();
//export2.TryGetExportedValue().VerifySuccess(CompositionIssueId.RequiredMetadataNotFound);
//container.TryGetExportedValue<MyImporterWithValue>().VerifyFailure(CompositionIssueId.RequiredMetadataNotFound, CompositionIssueId.CardinalityMismatch);
}
[Fact]
[ActiveIssue(468388)]
public void SelectiveImportBasedOnMetadataForExport()
{
CompositionContainer container = ContainerFactory.Create();
MyImporterWithExportForSelectiveImport importer;
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new MyExporterWithNoMetadata());
batch.AddPart(new MyExporterWithMetadata());
batch.AddPart(importer = new MyImporterWithExportForSelectiveImport());
throw new NotImplementedException();
//var result = container.TryCompose();
//Assert.True(result.Succeeded, "Composition should be successfull because one of two exports meets both the contract name and metadata requirement");
//Assert.Equal(1, result.Issues.Count);
//Assert.True(result.Issues[0].Description.Contains("Foo"), "The missing required metadata is 'Foo'");
//Assert.NotNull(importer.ValueInfo, "The import should really get bound");
}
[Fact]
[ActiveIssue(468388)]
public void SelectiveImportBasedOnMetadataForExportCollection()
{
CompositionContainer container = ContainerFactory.Create();
MyImporterWithExportCollectionForSelectiveImport importer;
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new MyExporterWithNoMetadata());
batch.AddPart(new MyExporterWithMetadata());
batch.AddPart(importer = new MyImporterWithExportCollectionForSelectiveImport());
throw new NotImplementedException();
//var result = container.TryCompose();
//Assert.True(result.Succeeded, "Composition should be successfull in anyway for collection import");
//Assert.Equal(1, result.Issues.Count);
//Assert.True(result.Issues[0].Description.Contains("Foo"), "The missing required metadata is 'Foo'");
//Assert.Equal(1, importer.ValueInfoCol.Count);
//Assert.NotNull(importer.ValueInfoCol[0], "The import should really get bound");
}
[Fact]
[ActiveIssue(472538)]
public void SelectiveImportBasedOnMetadataThruoughComponentCatalogTest()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
SelectiveImportBasedOnMetadataThruoughCatalog(container);
}
private void SelectiveImportBasedOnMetadataThruoughCatalog(CompositionContainer container)
{
throw new NotImplementedException();
//var export1 = container.GetExport<MyImporterWithExportForSelectiveImport>();
//export1.TryGetExportedValue().VerifySuccess(CompositionIssueId.RequiredMetadataNotFound);
//var export2 = container.GetExport<MyImporterWithExportCollectionForSelectiveImport>();
//export2.TryGetExportedValue().VerifySuccess(CompositionIssueId.RequiredMetadataNotFound);
}
[Fact]
public void ChildParentContainerTest1()
{
CompositionContainer parent = ContainerFactory.Create();
CompositionContainer child = new CompositionContainer(parent);
CompositionBatch childBatch = new CompositionBatch();
CompositionBatch parentBatch = new CompositionBatch();
parentBatch.AddPart(new MyExporterWithNoMetadata());
childBatch.AddPart(new MyExporterWithMetadata());
parent.Compose(parentBatch);
child.Compose(childBatch);
var exports = child.GetExports(CreateImportDefinition(typeof(IMyExporter), "Foo"));
Assert.Equal(1, exports.Count());
}
[Fact]
public void ChildParentContainerTest2()
{
CompositionContainer parent = ContainerFactory.Create();
CompositionContainer child = new CompositionContainer(parent);
CompositionBatch childBatch = new CompositionBatch();
CompositionBatch parentBatch = new CompositionBatch();
parentBatch.AddPart(new MyExporterWithMetadata());
childBatch.AddPart(new MyExporterWithNoMetadata());
parent.Compose(parentBatch);
var exports = child.GetExports(CreateImportDefinition(typeof(IMyExporter), "Foo"));
Assert.Equal(1, exports.Count());
}
[Fact]
public void ChildParentContainerTest3()
{
CompositionContainer parent = ContainerFactory.Create();
CompositionContainer child = new CompositionContainer(parent);
CompositionBatch childBatch = new CompositionBatch();
CompositionBatch parentBatch = new CompositionBatch();
parentBatch.AddPart(new MyExporterWithMetadata());
childBatch.AddPart(new MyExporterWithMetadata());
parent.Compose(parentBatch);
child.Compose(childBatch);
var exports = child.GetExports(CreateImportDefinition(typeof(IMyExporter), "Foo"));
Assert.Equal(2, exports.Count());
}
private static ImportDefinition CreateImportDefinition(Type type, string metadataKey)
{
return new ContractBasedImportDefinition(AttributedModelServices.GetContractName(typeof(IMyExporter)), null, new KeyValuePair<string, Type>[] { new KeyValuePair<string, Type>(metadataKey, typeof(object)) }, ImportCardinality.ZeroOrMore, true, true, CreationPolicy.Any);
}
#endregion
#region Tests for strongly typed metadata as part of contract
[Fact]
[ActiveIssue(468388)]
public void SelectiveImportBySTM_Export()
{
CompositionContainer container = ContainerFactory.Create();
CompositionBatch batch = new CompositionBatch();
MyImporterWithExportStronglyTypedMetadata importer;
batch.AddPart(new MyExporterWithNoMetadata());
batch.AddPart(new MyExporterWithMetadata());
batch.AddPart(importer = new MyImporterWithExportStronglyTypedMetadata());
throw new NotImplementedException();
//var result = container.TryCompose();
//Assert.True(result.Succeeded, "Composition should be successful becasue one of two exports does not have required metadata");
//Assert.Equal(1, result.Issues.Count);
//Assert.NotNull(importer.ValueInfo, "The valid export should really get bound");
//Assert.Equal("Bar", importer.ValueInfo.Metadata.Foo);
}
[Fact]
[ActiveIssue(468388)]
public void SelectiveImportBySTM_ExportCollection()
{
CompositionContainer container = ContainerFactory.Create();
MyImporterWithExportCollectionStronglyTypedMetadata importer;
CompositionBatch batch = new CompositionBatch();
batch.AddPart(new MyExporterWithNoMetadata());
batch.AddPart(new MyExporterWithMetadata());
batch.AddPart(importer = new MyImporterWithExportCollectionStronglyTypedMetadata());
throw new NotImplementedException();
//var result = container.TryCompose();
//Assert.True(result.Succeeded, "Collection import should be successful in anyway");
//Assert.Equal(1, result.Issues.Count);
//Assert.Equal(1, importer.ValueInfoCol.Count);
//Assert.Equal("Bar", importer.ValueInfoCol.First().Metadata.Foo);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void SelectiveImportBySTMThroughComponentCatalog1()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
SelectiveImportBySTMThroughCatalog1(container);
}
public void SelectiveImportBySTMThroughCatalog1(CompositionContainer container)
{
Assert.NotNull(container.GetExport<IMyExporter, IMetadataView>());
var result2 = container.GetExports<IMyExporter, IMetadataView>();
}
[Fact]
[ActiveIssue(468388)]
public void SelectiveImportBySTMThroughComponentCatalog2()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
SelectiveImportBySTMThroughCatalog2(container);
}
public void SelectiveImportBySTMThroughCatalog2(CompositionContainer container)
{
throw new NotImplementedException();
//var export1 = container.GetExport<MyImporterWithExportStronglyTypedMetadata>();
//var result1 = export1.TryGetExportedValue().VerifySuccess(CompositionIssueId.RequiredMetadataNotFound);
//Assert.NotNull(result1.Value.ValueInfo, "The valid export should really get bound");
//Assert.Equal("Bar", result1.Value.ValueInfo.Metadata.Foo);
//var export2 = container.GetExport<MyImporterWithExportCollectionStronglyTypedMetadata>();
//var result2 = export2.TryGetExportedValue().VerifySuccess(CompositionIssueId.RequiredMetadataNotFound);
//Assert.Equal(1, result2.Value.ValueInfoCol.Count);
//Assert.Equal("Bar", result2.Value.ValueInfoCol.First().Metadata.Foo);
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void TestMultipleStronglyTypedAttributes()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var export = container.GetExport<ExportMultiple, IMyOptions>();
EnumerableAssert.AreEqual(export.Metadata.OptionNames.OrderBy(s => s), "name1", "name2", "name3");
EnumerableAssert.AreEqual(export.Metadata.OptionValues.OrderBy(o => o.ToString()), "value1", "value2", "value3");
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void TestMultipleStronglyTypedAttributesAsIEnumerable()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var export = container.GetExport<ExportMultiple, IMyOptionsAsIEnumerable>();
EnumerableAssert.AreEqual(export.Metadata.OptionNames.OrderBy(s => s), "name1", "name2", "name3");
EnumerableAssert.AreEqual(export.Metadata.OptionValues.OrderBy(o => o.ToString()), "value1", "value2", "value3");
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void TestMultipleStronglyTypedAttributesAsArray()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
var export = container.GetExport<ExportMultiple, IMyOptionsAsArray>();
EnumerableAssert.AreEqual(export.Metadata.OptionNames.OrderBy(s => s), "name1", "name2", "name3");
EnumerableAssert.AreEqual(export.Metadata.OptionValues.OrderBy(o => o.ToString()), "value1", "value2", "value3");
}
[Fact]
[ActiveIssue(25498, TestPlatforms.AnyUnix)] // System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
public void TestMultipleStronglyTypedAttributesWithInvalidType()
{
var container = ContainerFactory.CreateWithDefaultAttributedCatalog();
// IMyOption2 actually contains all the correct properties but just the wrong types. This should cause us to not match the exports by metadata
var exports = container.GetExports<ExportMultiple, IMyOption2>();
Assert.Equal(0, exports.Count());
}
[Fact]
public void TestOptionalMetadataValueTypeMismatch()
{
var container = ContainerFactory.CreateWithAttributedCatalog(typeof(OptionalFooIsInt));
var exports = container.GetExports<OptionalFooIsInt, IMetadataView>();
Assert.Equal(1, exports.Count());
var export = exports.Single();
Assert.Equal(null, export.Metadata.OptionalFoo);
}
#endregion
[ExportMetadata("Name", "FromBaseType")]
public abstract class BaseClassWithMetadataButNoExport
{
}
[Export(typeof(BaseClassWithMetadataButNoExport))]
public class DerivedClassWithExportButNoMetadata : BaseClassWithMetadataButNoExport
{
}
[Fact]
public void Metadata_BaseClassWithMetadataButNoExport()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(BaseClassWithMetadataButNoExport),
typeof(DerivedClassWithExportButNoMetadata));
var export = container.GetExport<BaseClassWithMetadataButNoExport, IDictionary<string, object>>();
Assert.False(export.Metadata.ContainsKey("Name"), "Export should only contain metadata from the derived!");
}
[InheritedExport(typeof(BaseClassWithExportButNoMetadata))]
public abstract class BaseClassWithExportButNoMetadata
{
}
[ExportMetadata("Name", "FromDerivedType")]
public class DerivedClassMetadataButNoExport : BaseClassWithExportButNoMetadata
{
}
[Fact]
public void Metadata_BaseClassWithExportButNoMetadata()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(BaseClassWithExportButNoMetadata),
typeof(DerivedClassMetadataButNoExport));
var export = container.GetExport<BaseClassWithExportButNoMetadata, IDictionary<string, object>>();
Assert.False(export.Metadata.ContainsKey("Name"), "Export should only contain metadata from the base!");
}
[Export(typeof(BaseClassWithExportAndMetadata))]
[ExportMetadata("Name", "FromBaseType")]
public class BaseClassWithExportAndMetadata
{
}
[Export(typeof(DerivedClassWithExportAndMetadata))]
[ExportMetadata("Name", "FromDerivedType")]
public class DerivedClassWithExportAndMetadata : BaseClassWithExportAndMetadata
{
}
[Fact]
public void Metadata_BaseAndDerivedWithExportAndMetadata()
{
var container = ContainerFactory.CreateWithAttributedCatalog(
typeof(BaseClassWithExportAndMetadata),
typeof(DerivedClassWithExportAndMetadata));
var exportBase = container.GetExport<BaseClassWithExportAndMetadata, IDictionary<string, object>>();
Assert.Equal("FromBaseType", exportBase.Metadata["Name"]);
var exportDerived = container.GetExport<DerivedClassWithExportAndMetadata, IDictionary<string, object>>();
Assert.Equal("FromDerivedType", exportDerived.Metadata["Name"]);
}
[Export]
[ExportMetadata("Data", null, IsMultiple = true)]
[ExportMetadata("Data", false, IsMultiple = true)]
[ExportMetadata("Data", Int16.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", Int32.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", Int64.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", UInt16.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", UInt32.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", UInt64.MaxValue, IsMultiple = true)]
[ExportMetadata("Data", "String", IsMultiple = true)]
[ExportMetadata("Data", typeof(ClassWithLotsOfDifferentMetadataTypes), IsMultiple = true)]
[ExportMetadata("Data", CreationPolicy.NonShared, IsMultiple = true)]
[ExportMetadata("Data", new object[] { 1, 2, null }, IsMultiple = true)]
public class ClassWithLotsOfDifferentMetadataTypes
{
}
[Fact]
public void ExportWithValidCollectionOfMetadata_ShouldDiscoverAllMetadata()
{
var catalog = CatalogFactory.CreateAttributed(typeof(ClassWithLotsOfDifferentMetadataTypes));
var export = catalog.Parts.First().ExportDefinitions.First();
var data = (object[])export.Metadata["Data"];
Assert.Equal(12, data.Length);
}
[Export]
[ExportMetadata("Data", null, IsMultiple = true)]
[ExportMetadata("Data", 1, IsMultiple = true)]
[ExportMetadata("Data", 2, IsMultiple = true)]
[ExportMetadata("Data", 3, IsMultiple = true)]
public class ClassWithIntCollectionWithNullValue
{
}
[Fact]
public void ExportWithIntCollectionPlusNullValueOfMetadata_ShouldDiscoverAllMetadata()
{
var catalog = CatalogFactory.CreateAttributed(typeof(ClassWithIntCollectionWithNullValue));
var export = catalog.Parts.First().ExportDefinitions.First();
var data = (object[])export.Metadata["Data"];
Assert.IsNotType<int[]>(data);
Assert.Equal(4, data.Length);
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
[MetadataAttribute]
public class DataAttribute : Attribute
{
public object Object { get; set; }
}
[Export]
[Data(Object = "42")]
[Data(Object = "10")]
public class ExportWithMultipleMetadata_ExportStringsAsObjects
{
}
[Export]
[Data(Object = "42")]
[Data(Object = "10")]
[Data(Object = null)]
public class ExportWithMultipleMetadata_ExportStringsAsObjects_WithNull
{
}
[Export]
[Data(Object = 42)]
[Data(Object = 10)]
public class ExportWithMultipleMetadata_ExportIntsAsObjects
{
}
[Export]
[Data(Object = null)]
[Data(Object = 42)]
[Data(Object = 10)]
public class ExportWithMultipleMetadata_ExportIntsAsObjects_WithNull
{
}
public interface IObjectView_AsStrings
{
string[] Object { get; }
}
public interface IObjectView_AsInts
{
int[] Object { get; }
}
public interface IObjectView
{
object[] Object { get; }
}
[Fact]
public void ExportWithMultipleMetadata_ExportStringsAsObjects_ShouldDiscoverMetadataAsStrings()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ExportWithMultipleMetadata_ExportStringsAsObjects());
var export = container.GetExport<ExportWithMultipleMetadata_ExportStringsAsObjects, IObjectView_AsStrings>();
Assert.NotNull(export);
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Object);
Assert.Equal(2, export.Metadata.Object.Length);
}
[Fact]
public void ExportWithMultipleMetadata_ExportStringsAsObjects_With_Null_ShouldDiscoverMetadataAsStrings()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ExportWithMultipleMetadata_ExportStringsAsObjects_WithNull());
var export = container.GetExport<ExportWithMultipleMetadata_ExportStringsAsObjects_WithNull, IObjectView_AsStrings>();
Assert.NotNull(export);
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Object);
Assert.Equal(3, export.Metadata.Object.Length);
}
[Fact]
public void ExportWithMultipleMetadata_ExportIntsAsObjects_ShouldDiscoverMetadataAsInts()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ExportWithMultipleMetadata_ExportIntsAsObjects());
var export = container.GetExport<ExportWithMultipleMetadata_ExportIntsAsObjects, IObjectView_AsInts>();
Assert.NotNull(export);
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Object);
Assert.Equal(2, export.Metadata.Object.Length);
}
[Fact]
public void ExportWithMultipleMetadata_ExportIntsAsObjects_With_Null_ShouldDiscoverMetadataAsObjects()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ExportWithMultipleMetadata_ExportIntsAsObjects_WithNull());
var exports = container.GetExports<ExportWithMultipleMetadata_ExportIntsAsObjects_WithNull, IObjectView_AsInts>();
Assert.False(exports.Any());
var export = container.GetExport<ExportWithMultipleMetadata_ExportIntsAsObjects_WithNull, IObjectView>();
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Object);
Assert.Equal(3, export.Metadata.Object.Length);
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class OrderAttribute : Attribute
{
public string Before { get; set; }
public string After { get; set; }
}
public interface IOrderMetadataView
{
string[] Before { get; }
string[] After { get; }
}
[Export]
[Order(Before = "Step3")]
[Order(Before = "Step2")]
public class OrderedItemBeforesOnly
{
}
[Fact]
public void ExportWithMultipleMetadata_ExportStringsAndNulls_ThroughMetadataAttributes()
{
var container = ContainerFactory.Create();
container.ComposeParts(new OrderedItemBeforesOnly());
var export = container.GetExport<OrderedItemBeforesOnly, IOrderMetadataView>();
Assert.NotNull(export);
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Before);
Assert.NotNull(export.Metadata.After);
Assert.Equal(2, export.Metadata.Before.Length);
Assert.Equal(2, export.Metadata.After.Length);
Assert.NotNull(export.Metadata.Before[0]);
Assert.NotNull(export.Metadata.Before[1]);
Assert.Null(export.Metadata.After[0]);
Assert.Null(export.Metadata.After[1]);
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class DataTypeAttribute : Attribute
{
public Type Type { get; set; }
}
public interface ITypesMetadataView
{
Type[] Type { get; }
}
[Export]
[DataType(Type = typeof(int))]
[DataType(Type = typeof(string))]
public class ItemWithTypeExports
{
}
[Export]
[DataType(Type = typeof(int))]
[DataType(Type = typeof(string))]
[DataType(Type = null)]
public class ItemWithTypeExports_WithNulls
{
}
[Export]
[DataType(Type = null)]
[DataType(Type = null)]
[DataType(Type = null)]
public class ItemWithTypeExports_WithAllNulls
{
}
[Fact]
public void ExportWithMultipleMetadata_ExportTypes()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ItemWithTypeExports());
var export = container.GetExport<ItemWithTypeExports, ITypesMetadataView>();
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Type);
Assert.Equal(2, export.Metadata.Type.Length);
}
[Fact]
public void ExportWithMultipleMetadata_ExportTypes_WithNulls()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ItemWithTypeExports_WithNulls());
var export = container.GetExport<ItemWithTypeExports_WithNulls, ITypesMetadataView>();
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Type);
Assert.Equal(3, export.Metadata.Type.Length);
}
[Fact]
public void ExportWithMultipleMetadata_ExportTypes_WithAllNulls()
{
var container = ContainerFactory.Create();
container.ComposeParts(new ItemWithTypeExports_WithAllNulls());
var export = container.GetExport<ItemWithTypeExports_WithAllNulls, ITypesMetadataView>();
Assert.NotNull(export.Metadata);
Assert.NotNull(export.Metadata.Type);
Assert.Equal(3, export.Metadata.Type.Length);
Assert.Null(export.Metadata.Type[0]);
Assert.Null(export.Metadata.Type[1]);
Assert.Null(export.Metadata.Type[2]);
}
[Export]
[ExportMetadata(null, "ValueOfNullKey")]
public class ClassWithNullMetadataKey
{
}
[Fact]
public void ExportMetadataWithNullKey_ShouldUseEmptyString()
{
var nullMetadataCatalog = CatalogFactory.CreateAttributed(typeof(ClassWithNullMetadataKey));
var nullMetadataExport = nullMetadataCatalog.Parts.Single().ExportDefinitions.Single();
Assert.True(nullMetadataExport.Metadata.ContainsKey(string.Empty));
Assert.Equal("ValueOfNullKey", nullMetadataExport.Metadata[string.Empty]);
}
}
// Tests for metadata issues on export
[Export]
[ExportMetadata("foo", "bar1", IsMultiple = true)]
[ExportMetadata("foo", "bar2", IsMultiple = true)]
[ExportMetadata("acme", "acmebar", IsMultiple = true)]
[ExportMetadata("acme", 2.0, IsMultiple = true)]
[ExportMetadata("hello", "world")]
[GoodStrongMetadata]
public class MyExporterWithValidMetadata
{
[Export("ContractForValidMetadata")]
[ExportMetadata("bar", "foo1", IsMultiple = true)]
[ExportMetadata("bar", "foo2", IsMultiple = true)]
[ExportMetadata("stuff", "acmebar", IsMultiple = true)]
[ExportMetadata("stuff", 2.0, IsMultiple = true)]
[ExportMetadata("world", "hello")] // the order of the attribute should not affect the result
[GoodStrongMetadata]
public double DoSomething() { return 0.618; }
}
[AttributeUsage(AttributeTargets.All, AllowMultiple = false)]
[MetadataAttribute]
public class GoodStrongMetadata : Attribute
{
public string GoodOne2 { get { return "GoodOneValue2"; } }
public string ConflictedOne1 { get { return "ConflictedOneValue1"; } }
public string ConflictedOne2 { get { return "ConflictedOneValue2"; } }
}
// Tests for metadata as part of contract
public interface IMyExporter { }
[Export]
[Export(typeof(IMyExporter))]
public class MyExporterWithNoMetadata : IMyExporter
{
}
[Export]
[Export(typeof(IMyExporter))]
[ExportMetadata("Foo", "Bar")]
public class MyExporterWithMetadata : IMyExporter
{
}
public interface IMetadataFoo
{
string Foo { get; }
}
public interface IMetadataBar
{
string Bar { get; }
}
[Export]
public class MyImporterWithExport
{
[Import(typeof(MyExporterWithNoMetadata))]
public Lazy<MyExporterWithNoMetadata, IMetadataFoo> ValueInfo { get; set; }
}
[Export]
public class SingleImportWithAllowDefault
{
[Import("Import", AllowDefault = true)]
public Lazy<object> Import { get; set; }
}
[Export]
public class SingleImport
{
[Import("Import")]
public Lazy<object> Import { get; set; }
}
public interface IFooMetadataView
{
string Foo { get; }
}
[Export]
public class MyImporterWithExportCollection
{
[ImportMany(typeof(MyExporterWithNoMetadata))]
public IEnumerable<Lazy<MyExporterWithNoMetadata, IFooMetadataView>> ValueInfoCol { get; set; }
}
[Export]
public class MyImporterWithExportForSelectiveImport
{
[Import]
public Lazy<IMyExporter, IFooMetadataView> ValueInfo { get; set; }
}
[Export]
public class MyImporterWithExportCollectionForSelectiveImport
{
[ImportMany]
public Collection<Lazy<IMyExporter, IFooMetadataView>> ValueInfoCol { get; set; }
}
public interface IMetadataView
{
string Foo { get; }
[System.ComponentModel.DefaultValue(null)]
string OptionalFoo { get; }
}
[Export]
[ExportMetadata("Foo", "fooValue3")]
[ExportMetadata("OptionalFoo", 42)]
public class OptionalFooIsInt { }
[Export]
public class MyImporterWithExportStronglyTypedMetadata
{
[Import]
public Lazy<IMyExporter, IMetadataView> ValueInfo { get; set; }
}
[Export]
public class MyImporterWithExportCollectionStronglyTypedMetadata
{
[ImportMany]
public Collection<Lazy<IMyExporter, IMetadataView>> ValueInfoCol { get; set; }
}
public class MyExporterWithFullMetadata
{
[Export("MyStringContract")]
public string String1 { get { return "String1"; } }
[Export("MyStringContract")]
[ExportMetadata("Foo", "fooValue")]
public string String2 { get { return "String2"; } }
[Export("MyStringContract")]
[ExportMetadata("Bar", "barValue")]
public string String3 { get { return "String3"; } }
[Export("MyStringContract")]
[ExportMetadata("Foo", "fooValue")]
[ExportMetadata("Bar", "barValue")]
public string String4 { get { return "String4"; } }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class MyOption : Attribute
{
public MyOption(string name, object value)
{
OptionNames = name;
OptionValues = value;
}
public string OptionNames { get; set; }
public object OptionValues { get; set; }
}
public interface IMyOptions
{
IList<string> OptionNames { get; }
ICollection<string> OptionValues { get; }
}
public interface IMyOptionsAsIEnumerable
{
IEnumerable<string> OptionNames { get; }
IEnumerable<string> OptionValues { get; }
}
public interface IMyOptionsAsArray
{
string[] OptionNames { get; }
string[] OptionValues { get; }
}
[Export]
[MyOption("name1", "value1")]
[MyOption("name2", "value2")]
[ExportMetadata("OptionNames", "name3", IsMultiple = true)]
[ExportMetadata("OptionValues", "value3", IsMultiple = true)]
public class ExportMultiple
{
}
public interface IMyOption2
{
string OptionNames { get; }
string OptionValues { get; }
}
}
| |
// Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
namespace Google.Cloud.Tools.Analyzers
{
/// <summary>
/// Warns about deriving from or exposing types from namespaces which are not to be exposed as dependencies.
/// </summary>
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class PublicDependencyForbiddenAnalyzer : DiagnosticAnalyzer
{
private static readonly ImmutableArray<string> ForbiddenNamespacePrefixes = ImmutableArray.Create("Google.Apis.");
public const string DiagnosticId = "GCP0003";
private const string Category = "Usage";
private static readonly LocalizableString Title = "Publicly dependency to forbidden namespace";
private static readonly LocalizableString MessageFormat = "The type '{0}' directly or indirectly depends on the forbidden namespace '{1}'";
private static readonly LocalizableString Description = "Dependencies on certain namespaces should not be exposed publicly.";
private static DiagnosticDescriptor Rule =
new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Hidden, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } }
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics);
context.RegisterSymbolAction(AnalyzeEvent, SymbolKind.Event);
context.RegisterSymbolAction(AnalyzeField, SymbolKind.Field);
context.RegisterSymbolAction(AnalyzeMethod, SymbolKind.Method);
context.RegisterSymbolAction(AnalyzeNamedType, SymbolKind.NamedType);
context.RegisterSymbolAction(AnalyzeProperty, SymbolKind.Property);
}
private static void AnalyzeEvent(SymbolAnalysisContext context)
{
var eventSymbol = (IEventSymbol)context.Symbol;
var declNode = context.Symbol.DeclaringSyntaxReferences[0].GetSyntax(context.CancellationToken);
if (declNode.IsKind(SyntaxKind.EventDeclaration))
{
CheckType<EventDeclarationSyntax>(
context,
eventSymbol.Type,
eventNode => eventNode.Type.GetLocation());
}
else
{
CheckType<VariableDeclaratorSyntax>(
context,
eventSymbol.Type,
variableDeclaratorNode => (variableDeclaratorNode.Parent as VariableDeclarationSyntax)?.Type.GetLocation());
}
}
private static void AnalyzeField(SymbolAnalysisContext context)
{
var fieldSymbol = (IFieldSymbol)context.Symbol;
CheckType<VariableDeclaratorSyntax>(
context,
fieldSymbol.Type,
variableDeclaratorNode => (variableDeclaratorNode.Parent as VariableDeclarationSyntax)?.Type.GetLocation());
}
private static void AnalyzeMethod(SymbolAnalysisContext context)
{
var methodKind = ((IMethodSymbol)context.Symbol).MethodKind;
switch (methodKind)
{
case MethodKind.AnonymousFunction:
case MethodKind.DelegateInvoke:
case MethodKind.Destructor:
case MethodKind.EventAdd:
case MethodKind.EventRaise:
case MethodKind.EventRemove:
case MethodKind.ExplicitInterfaceImplementation:
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
case MethodKind.StaticConstructor:
case MethodKind.LocalFunction:
return;
}
var methodSymbol = (IMethodSymbol)context.Symbol;
if (methodKind != MethodKind.Constructor)
{
CheckType<MethodDeclarationSyntax>(
context,
methodSymbol.ReturnType,
methodNode => methodNode.ReturnType.GetLocation());
}
for (int i = 0; i < methodSymbol.Parameters.Length; ++i)
{
if (methodKind == MethodKind.Constructor)
{
CheckType<ConstructorDeclarationSyntax>(
context,
methodSymbol.Parameters[i].Type,
constructorNode => constructorNode.ParameterList.Parameters[i].Type.GetLocation());
}
else
{
CheckType<MethodDeclarationSyntax>(
context,
methodSymbol.Parameters[i].Type,
methodNode => methodNode.ParameterList.Parameters[i].Type.GetLocation());
}
}
}
private static void AnalyzeNamedType(SymbolAnalysisContext context)
{
var typeSymbol = (INamedTypeSymbol)context.Symbol;
CheckType<TypeDeclarationSyntax>(
context,
typeSymbol,
methodNode => methodNode.BaseList.GetLocation());
}
private static void AnalyzeProperty(SymbolAnalysisContext context)
{
var propertySymbol = (IPropertySymbol)context.Symbol;
CheckType<PropertyDeclarationSyntax>(
context,
propertySymbol.Type,
propertyNode => propertyNode.Type.GetLocation());
for (int i = 0; i < propertySymbol.Parameters.Length; ++i)
{
CheckType<IndexerDeclarationSyntax>(
context,
propertySymbol.Parameters[i].Type,
propertyNode => propertyNode.ParameterList.Parameters[i].Type.GetLocation());
}
}
private static void CheckType<T>(SymbolAnalysisContext context, ITypeSymbol type, Func<T, Location> getErrorLocation)
where T : CSharpSyntaxNode
{
if (!context.Symbol.IsExternallyVisible())
{
return;
}
if (ForbiddenNamespacePrefixes.Any(context.Symbol.ContainingSymbol.ToDisplayString().StartsWith))
{
// If a symbol is actually defined in a forbidden namespace, don't add an error to it.
return;
}
var checkedTypes = new Dictionary<ITypeSymbol, TypeCheckResult>();
var result = CheckType(type, checkedTypes);
if (!result.IsTypeForbidden)
{
return;
}
if (context.Symbol.DeclaringSyntaxReferences.IsEmpty)
{
return;
}
T declaringNode = (T)context.Symbol.DeclaringSyntaxReferences.FirstOrDefault().GetSyntax(context.CancellationToken);
context.ReportDiagnostic(
Diagnostic.Create(
Rule,
getErrorLocation(declaringNode),
type.ToDisplayString(),
result.ForbiddenNamespace));
}
private static TypeCheckResult CheckType(ITypeSymbol type, Dictionary<ITypeSymbol, TypeCheckResult> checkedTypes)
{
if (!checkedTypes.TryGetValue(type, out var result))
{
// Add a placeholder before we do anything else to prevent recursion issues.
checkedTypes.Add(type, TypeCheckResult.Allowed);
result = CheckTypeImpl(type);
checkedTypes[type] = result;
}
return result;
TypeCheckResult CheckTypeImpl(ITypeSymbol currentType)
{
if (currentType.TypeKind == TypeKind.Array)
{
return CheckType(((IArrayTypeSymbol)currentType).ElementType, checkedTypes);
}
if (currentType is INamedTypeSymbol namedType)
{
if (namedType.TypeKind == TypeKind.Delegate)
{
var delegateResult = CheckType(namedType.DelegateInvokeMethod.ReturnType, checkedTypes);
if (!delegateResult.IsTypeForbidden) {
delegateResult =
namedType.DelegateInvokeMethod.Parameters.
Select(p => CheckType(p.Type, checkedTypes)).
FirstOrDefault(c => c.IsTypeForbidden);
}
if (delegateResult?.IsTypeForbidden == true)
{
return TypeCheckResult.Forbidden(delegateResult.ForbiddenNamespace);
}
}
else
{
if (ForbiddenNamespacePrefixes.Any(namedType.ContainingNamespace.ToDisplayString().StartsWith))
{
return TypeCheckResult.Forbidden(namedType.ContainingNamespace.ToDisplayString());
}
var dependentTypeResult =
namedType.BaseType == null ? null : CheckType(namedType.BaseType, checkedTypes);
if (dependentTypeResult?.IsTypeForbidden != true)
{
dependentTypeResult =
namedType.Interfaces.Select(i => CheckType(i, checkedTypes)).FirstOrDefault(c => c.IsTypeForbidden);
}
if (dependentTypeResult?.IsTypeForbidden != true)
{
dependentTypeResult =
namedType.TypeArguments.Select(p => CheckType(p, checkedTypes)).FirstOrDefault(c => c.IsTypeForbidden);
}
if (dependentTypeResult?.IsTypeForbidden == true)
{
return TypeCheckResult.Forbidden(dependentTypeResult.ForbiddenNamespace);
}
}
}
return TypeCheckResult.Allowed;
}
}
private class TypeCheckResult
{
public static readonly TypeCheckResult Allowed = new TypeCheckResult();
public static TypeCheckResult Forbidden(string forbiddenNamespace) =>
new TypeCheckResult
{
IsTypeForbidden = true,
ForbiddenNamespace = forbiddenNamespace
};
private TypeCheckResult() { }
public bool IsTypeForbidden { get; private set; }
public string ForbiddenNamespace { get; private set; }
}
}
}
| |
using System.Collections;
using System.Data;
using Dapper;
using Newtonsoft.Json;
using Npgsql;
using Tools.Tools;
namespace EventStoreBasics;
public class EventStore: IDisposable, IEventStore
{
private readonly NpgsqlConnection databaseConnection;
private readonly IList<ISnapshot> snapshots = new List<ISnapshot>();
private readonly IList<IProjection> projections = new List<IProjection>();
private const string Apply = "Apply";
public EventStore(NpgsqlConnection databaseConnection)
{
this.databaseConnection = databaseConnection;
}
public void Init()
{
// See more in Greg Young's "Building an Event Storage" article https://cqrs.wordpress.com/documents/building-event-storage/
CreateStreamsTable();
CreateEventsTable();
CreateAppendEventFunction();
}
public void AddSnapshot(ISnapshot snapshot)
{
snapshots.Add(snapshot);
}
public void AddProjection(IProjection projection)
{
projections.Add(projection);
}
public bool Store<TStream>(TStream aggregate) where TStream : IAggregate
{
//TODO Add applying events for all projections
var events = aggregate.DequeueUncommittedEvents();
var initialVersion = aggregate.Version - events.Count();
foreach (var @event in events)
{
AppendEvent<TStream>(aggregate.Id, @event, initialVersion++);
}
snapshots
.FirstOrDefault(snapshot => snapshot.Handles == typeof(TStream))?
.Handle(aggregate);
return true;
}
public bool AppendEvent<TStream>(Guid streamId, object @event, long? expectedVersion = null)
{
return databaseConnection.QuerySingle<bool>(
"SELECT append_event(@Id, @Data::jsonb, @Type, @StreamId, @StreamType, @ExpectedVersion)",
new
{
Id = Guid.NewGuid(),
Data = JsonConvert.SerializeObject(@event),
Type = @event.GetType().AssemblyQualifiedName,
StreamId = streamId,
StreamType = typeof(TStream).AssemblyQualifiedName,
ExpectedVersion = expectedVersion
},
commandType: CommandType.Text
);
}
public T AggregateStream<T>(Guid streamId, long? atStreamVersion = null, DateTime? atTimestamp = null)
where T : notnull
{
var aggregate = (T)Activator.CreateInstance(typeof(T), true)!;
var events = GetEvents(streamId, atStreamVersion, atTimestamp);
var version = 0;
foreach (var @event in events)
{
aggregate.InvokeIfExists(Apply, @event);
aggregate.SetIfExists(nameof(IAggregate.Version), ++version);
}
return aggregate;
}
public StreamState? GetStreamState(Guid streamId)
{
const string getStreamSql =
@"SELECT id, type, version
FROM streams
WHERE id = @streamId";
return databaseConnection
.Query<dynamic>(getStreamSql, new {streamId})
.Select(streamData =>
new StreamState(
streamData.id,
Type.GetType(streamData.type),
streamData.version
))
.SingleOrDefault();
}
public IEnumerable GetEvents(Guid streamId, long? atStreamVersion = null, DateTime? atTimestamp = null)
{
const string getStreamSql =
@"SELECT id, data, stream_id, type, version, created
FROM events
WHERE stream_id = @streamId
AND (@atStreamVersion IS NULL OR version <= @atStreamVersion)
AND (@atTimestamp IS NULL OR created <= @atTimestamp)
ORDER BY version";
return databaseConnection
.Query<dynamic>(getStreamSql, new {streamId, atStreamVersion, atTimestamp})
.Select(@event =>
JsonConvert.DeserializeObject(
@event.data,
Type.GetType(@event.type)
))
.ToList();
}
private void CreateStreamsTable()
{
const string creatStreamsTableSql =
@"CREATE TABLE IF NOT EXISTS streams(
id UUID NOT NULL PRIMARY KEY,
type TEXT NOT NULL,
version BIGINT NOT NULL
);";
databaseConnection.Execute(creatStreamsTableSql);
}
private void CreateEventsTable()
{
const string creatEventsTableSql =
@"CREATE TABLE IF NOT EXISTS events(
id UUID NOT NULL PRIMARY KEY,
data JSONB NOT NULL,
stream_id UUID NOT NULL,
type TEXT NOT NULL,
version BIGINT NOT NULL,
created timestamp with time zone NOT NULL default (now()),
FOREIGN KEY(stream_id) REFERENCES streams(id),
CONSTRAINT events_stream_and_version UNIQUE(stream_id, version)
);";
databaseConnection.Execute(creatEventsTableSql);
}
private void CreateAppendEventFunction()
{
const string appendEventFunctionSql =
@"CREATE OR REPLACE FUNCTION append_event(id uuid, data jsonb, type text, stream_id uuid, stream_type text, expected_stream_version bigint default null) RETURNS boolean
LANGUAGE plpgsql
AS $$
DECLARE
stream_version int;
BEGIN
-- get stream version
SELECT
version INTO stream_version
FROM streams as s
WHERE
s.id = stream_id FOR UPDATE;
-- if stream doesn't exist - create new one with version 0
IF stream_version IS NULL THEN
stream_version := 0;
INSERT INTO streams
(id, type, version)
VALUES
(stream_id, stream_type, stream_version);
END IF;
-- check optimistic concurrency
IF expected_stream_version IS NOT NULL AND stream_version != expected_stream_version THEN
RETURN FALSE;
END IF;
-- increment event_version
stream_version := stream_version + 1;
-- append event
INSERT INTO events
(id, data, stream_id, type, version)
VALUES
(id, data, stream_id, type, stream_version);
-- update stream version
UPDATE streams as s
SET version = stream_version
WHERE
s.id = stream_id;
RETURN TRUE;
END;
$$;";
databaseConnection.Execute(appendEventFunctionSql);
}
public void Dispose()
{
databaseConnection.Dispose();
}
}
| |
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://fluentvalidation.codeplex.com
#endregion
namespace FluentValidation.Tests.Mvc5 {
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Internal;
using Moq;
using Mvc;
using Validators;
using Xunit;
public class ClientsideMessageTester {
InlineValidator<TestModel> validator;
ControllerContext controllerContext;
public ClientsideMessageTester() {
System.Threading.Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");
System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
validator = new InlineValidator<TestModel>();
controllerContext = CreateControllerContext();
}
[Fact]
public void NotNull_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).NotNull();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must not be empty.");
}
[Fact]
public void NotEmpty_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).NotEmpty();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' should not be empty.");
}
[Fact]
public void RegexValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Matches("\\d");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' is not in the correct format.");
}
[Fact]
public void EmailValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).EmailAddress();
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' is not a valid email address.");
}
[Fact]
public void LengthValidator_uses_simplified_message_for_clientside_validatation() {
validator.RuleFor(x => x.Name).Length(1, 10);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must be between 1 and 10 characters.");
}
[Fact]
public void InclusiveBetween_validator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Id).InclusiveBetween(1, 10);
var clientRules = GetClientRules(x => x.Id);
clientRules.Any(x => x.ErrorMessage == "'Id' must be between 1 and 10.").ShouldBeTrue();
}
[Fact]
public void GreaterThanOrEqualTo_validator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Id).GreaterThanOrEqualTo(5);
var clientRules = GetClientRules(x => x.Id);
clientRules.Any(x => x.ErrorMessage == "'Id' must be greater than or equal to '5'.").ShouldBeTrue();
}
[Fact]
public void LessThanOrEqualTo_validator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Id).LessThanOrEqualTo(50);
var clientRules = GetClientRules(x => x.Id);
clientRules.Any(x => x.ErrorMessage == "'Id' must be less than or equal to '50'.").ShouldBeTrue();
}
[Fact]
public void EqualValidator_with_property_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Equal(x => x.Name2);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' should be equal to 'Name2'.");
}
[Fact]
public void Should_not_munge_custom_message() {
validator.RuleFor(x => x.Name).Length(1, 10).WithMessage("Foo");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Foo");
}
[Fact]
public void ExactLengthValidator_uses_simplified_message_for_clientside_validation() {
validator.RuleFor(x => x.Name).Length(5);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' must be 5 characters in length.");
}
[Fact]
public void Custom_validation_message_with_placeholders() {
validator.RuleFor(x => x.Name).NotNull().WithMessage("{PropertyName} is null.");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Name is null.");
}
[Fact]
public void Custom_validation_message_for_length() {
validator.RuleFor(x => x.Name).Length(1, 5).WithMessage("Must be between {MinLength} and {MaxLength}.");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("Must be between 1 and 5.");
}
[Fact]
public void Supports_custom_clientside_rules_with_IClientValidatable() {
validator.RuleFor(x => x.Name).SetValidator(new TestPropertyValidator());
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("foo");
}
[Fact]
public void CreditCard_creates_clientside_message() {
validator.RuleFor(x => x.Name).CreditCard();
var clientrule = GetClientRule(x => x.Name);
clientrule.ErrorMessage.ShouldEqual("'Name' is not a valid credit card number.");
}
[Fact]
public void Overrides_property_name_for_clientside_rule() {
validator.RuleFor(x => x.Name).NotNull().WithName("Foo");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Foo' must not be empty.");
}
[Fact]
public void Overrides_property_name_for_clientside_rule_using_localized_name() {
validator.RuleFor(x => x.Name).NotNull().WithLocalizedName(() => TestMessages.notnull_error);
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Localised Error' must not be empty.");
}
[Fact]
public void Overrides_property_name_for_non_nullable_value_type() {
validator.RuleFor(x => x.Id).NotNull().WithName("Foo");
var clientRule = GetClientRule(x => x.Id);
clientRule.ErrorMessage.ShouldEqual("'Foo' must not be empty.");
}
[Fact]
public void Falls_back_to_default_message_when_no_context_available_to_custom_message_format() {
validator.RuleFor(x => x.Name).NotNull().WithMessage(x => $"Foo {x.Name}");
var clientRule = GetClientRule(x => x.Name);
clientRule.ErrorMessage.ShouldEqual("'Name' should not be empty.");
}
[Fact]
public void Should_only_use_rules_from_Default_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
// Client-side rules are only generated from the default ruleset
// unless explicitly specified.
// so in this case, only the second NotNull should make it through
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(1);
rules.Single().ErrorMessage.ShouldEqual("second");
}
[Fact]
public void Should_use_rules_from_specified_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
var filter = new RuleSetForClientSideMessagesAttribute("Foo");
filter.OnActionExecuting(new ActionExecutingContext { HttpContext = controllerContext.HttpContext });
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(1);
rules.Single().ErrorMessage.ShouldEqual("first");
}
[Fact]
public void Should_use_rules_from_multiple_rulesets() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleSet("Bar", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("third");
var filter = new RuleSetForClientSideMessagesAttribute("Foo", "Bar");
filter.OnActionExecuting(new ActionExecutingContext {HttpContext = controllerContext.HttpContext});
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(2);
}
[Fact]
public void Should_use_rules_from_default_ruleset_and_specified_ruleset() {
validator.RuleSet("Foo", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("first");
});
validator.RuleSet("Bar", () => {
validator.RuleFor(x => x.Name).NotNull().WithMessage("second");
});
validator.RuleFor(x => x.Name).NotNull().WithMessage("third");
var filter = new RuleSetForClientSideMessagesAttribute("Foo", "default");
filter.OnActionExecuting(new ActionExecutingContext { HttpContext = controllerContext.HttpContext });
var rules = GetClientRules(x => x.Name);
rules.Count().ShouldEqual(2);
}
private ModelClientValidationRule GetClientRule(Expression<Func<TestModel, object>> expression) {
var propertyName = expression.GetMember().Name;
var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);
var factory = new Mock<IValidatorFactory>();
factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);
var provider = new FluentValidationModelValidatorProvider(factory.Object);
var propertyValidator = provider.GetValidators(metadata, controllerContext).Single();
var clientRule = propertyValidator.GetClientValidationRules().Single();
return clientRule;
}
private IEnumerable<ModelClientValidationRule> GetClientRules(Expression<Func<TestModel, object>> expression ) {
var propertyName = expression.GetMember().Name;
var metadata = new DataAnnotationsModelMetadataProvider().GetMetadataForProperty(null, typeof(TestModel), propertyName);
var factory = new Mock<IValidatorFactory>();
factory.Setup(x => x.GetValidator(typeof(TestModel))).Returns(validator);
var provider = new FluentValidationModelValidatorProvider(factory.Object);
var propertyValidators = provider.GetValidators(metadata, controllerContext);
return (propertyValidators.SelectMany(x => x.GetClientValidationRules())).ToList();
}
private ControllerContext CreateControllerContext() {
var httpContext = new Mock<HttpContextBase>();
httpContext.Setup(x => x.Items).Returns(new Hashtable());
return new ControllerContext { HttpContext = httpContext.Object };
}
private class TestModel {
public string Name { get; set; }
public string Name2 { get; set; }
public int Id { get; set; }
}
private class TestPropertyValidator : PropertyValidator, IClientValidatable {
public TestPropertyValidator()
: base("foo") {
}
protected override bool IsValid(PropertyValidatorContext context) {
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
yield return new ModelClientValidationRule { ErrorMessage = this.ErrorMessageSource.GetString(null) };
}
}
}
}
| |
namespace EIDSS.Reports.Parameterized.Human.AJ.Reports
{
partial class FormVet1A
{
#region Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormVet1A));
DevExpress.XtraReports.UI.XRSummary xrSummary1 = new DevExpress.XtraReports.UI.XRSummary();
this.VetReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.VetDetail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable2 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow6 = new DevExpress.XtraReports.UI.XRTableRow();
this.RowNumberCell = new DevExpress.XtraReports.UI.XRTableCell();
this.NameInvestigationCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DiseaseCell = new DevExpress.XtraReports.UI.XRTableCell();
this.OIECell = new DevExpress.XtraReports.UI.XRTableCell();
this.SpeciesCell = new DevExpress.XtraReports.UI.XRTableCell();
this.NumberTested = new DevExpress.XtraReports.UI.XRTableCell();
this.NumberPositive = new DevExpress.XtraReports.UI.XRTableCell();
this.NoteCell = new DevExpress.XtraReports.UI.XRTableCell();
this.VetReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrLabel6 = new DevExpress.XtraReports.UI.XRLabel();
this.xrTable3 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow4 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell18 = new DevExpress.XtraReports.UI.XRTableCell();
this.Recipient = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow7 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell22 = new DevExpress.XtraReports.UI.XRTableCell();
this.SentBy = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow8 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell20 = new DevExpress.XtraReports.UI.XRTableCell();
this.ForReportPeriod = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel5 = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel4 = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel3 = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel();
this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel();
this.xrPictureBox1 = new DevExpress.XtraReports.UI.XRPictureBox();
this.HeaderLabel = new DevExpress.XtraReports.UI.XRLabel();
this.xrTable1 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow5 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell1 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell5 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell24 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell26 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow3 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell10 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell11 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell12 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell13 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell16 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell17 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell25 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell27 = new DevExpress.XtraReports.UI.XRTableCell();
this.GroupHeaderDiagnosis = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.GroupFooterDiagnosis = new DevExpress.XtraReports.UI.GroupFooterBand();
this.GroupHeaderLine = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.xrLine2 = new DevExpress.XtraReports.UI.XRLine();
this.GroupFooterLine = new DevExpress.XtraReports.UI.GroupFooterBand();
this.xrLine1 = new DevExpress.XtraReports.UI.XRLine();
this.m_DataAdapter1 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter();
this.m_DataSet = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetForm1ADataSet();
this.m_DataAdapter2 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1AVaccinationMeasuresAZTableAdapter();
this.m_DataAdapter3 = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ASanitaryMeasuresAZTableAdapter();
this.SanitaryMeasuresReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.SanitaryMeasuresDetail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable8 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow15 = new DevExpress.XtraReports.UI.XRTableRow();
this.RowNumberCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.NameActionCell = new DevExpress.XtraReports.UI.XRTableCell();
this.NumberFacilities = new DevExpress.XtraReports.UI.XRTableCell();
this.SquareCell = new DevExpress.XtraReports.UI.XRTableCell();
this.NoteCell3 = new DevExpress.XtraReports.UI.XRTableCell();
this.ReportFooter1 = new DevExpress.XtraReports.UI.ReportFooterBand();
this.xrTable5 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow10 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell21 = new DevExpress.XtraReports.UI.XRTableCell();
this.PerformerCell = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow11 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell19 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell53 = new DevExpress.XtraReports.UI.XRTableCell();
this.DateTimeCell = new DevExpress.XtraReports.UI.XRTableCell();
this.SanitaryMeasuresHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrTable6 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow13 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell31 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell40 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell43 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell44 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow9 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell41 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell42 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell46 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell48 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell49 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow12 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell50 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell51 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell58 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell45 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell60 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel8 = new DevExpress.XtraReports.UI.XRLabel();
this.GroupFooterLine3 = new DevExpress.XtraReports.UI.GroupFooterBand();
this.xrLine6 = new DevExpress.XtraReports.UI.XRLine();
this.VaccinationMeasuresReport = new DevExpress.XtraReports.UI.DetailReportBand();
this.VaccinationMeasuresDetail = new DevExpress.XtraReports.UI.DetailBand();
this.xrTable7 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow14 = new DevExpress.XtraReports.UI.XRTableRow();
this.RowNumberCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.NameMeasureCell = new DevExpress.XtraReports.UI.XRTableCell();
this.DiseaseCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.OIECell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.SpeciesCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.NumberTaken = new DevExpress.XtraReports.UI.XRTableCell();
this.NoteCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.VaccinationMeasuresHeader = new DevExpress.XtraReports.UI.ReportHeaderBand();
this.xrTable4 = new DevExpress.XtraReports.UI.XRTable();
this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell14 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell15 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell23 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell28 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell29 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell30 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow();
this.xrTableCell32 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell34 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell35 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell36 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell37 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell38 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrTableCell39 = new DevExpress.XtraReports.UI.XRTableCell();
this.xrLabel7 = new DevExpress.XtraReports.UI.XRLabel();
this.GroupHeaderLine2 = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.xrLine3 = new DevExpress.XtraReports.UI.XRLine();
this.GroupFooterLine2 = new DevExpress.XtraReports.UI.GroupFooterBand();
this.xrLine5 = new DevExpress.XtraReports.UI.XRLine();
this.GroupFooterDiagnosis2 = new DevExpress.XtraReports.UI.GroupFooterBand();
this.GroupHeaderDiagnosis2 = new DevExpress.XtraReports.UI.GroupHeaderBand();
this.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter = new EIDSS.Reports.Parameterized.Human.AJ.DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter();
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this)).BeginInit();
//
// cellLanguage
//
resources.ApplyResources(this.cellLanguage, "cellLanguage");
this.cellLanguage.StylePriority.UseTextAlignment = false;
//
// lblReportName
//
resources.ApplyResources(this.lblReportName, "lblReportName");
this.lblReportName.StylePriority.UseBorders = false;
this.lblReportName.StylePriority.UseBorderWidth = false;
this.lblReportName.StylePriority.UseFont = false;
this.lblReportName.StylePriority.UseTextAlignment = false;
//
// Detail
//
resources.ApplyResources(this.Detail, "Detail");
this.Detail.Expanded = false;
this.Detail.StylePriority.UseFont = false;
this.Detail.StylePriority.UsePadding = false;
//
// PageHeader
//
resources.ApplyResources(this.PageHeader, "PageHeader");
this.PageHeader.Expanded = false;
this.PageHeader.StylePriority.UseFont = false;
this.PageHeader.StylePriority.UsePadding = false;
//
// PageFooter
//
resources.ApplyResources(this.PageFooter, "PageFooter");
this.PageFooter.StylePriority.UseBorders = false;
//
// ReportHeader
//
resources.ApplyResources(this.ReportHeader, "ReportHeader");
this.ReportHeader.Expanded = false;
//
// xrPageInfo1
//
resources.ApplyResources(this.xrPageInfo1, "xrPageInfo1");
this.xrPageInfo1.StylePriority.UseBorders = false;
this.xrPageInfo1.StylePriority.UseFont = false;
this.xrPageInfo1.StylePriority.UseTextAlignment = false;
//
// cellReportHeader
//
resources.ApplyResources(this.cellReportHeader, "cellReportHeader");
this.cellReportHeader.StylePriority.UseBorders = false;
this.cellReportHeader.StylePriority.UseFont = false;
this.cellReportHeader.StylePriority.UseTextAlignment = false;
//
// cellBaseSite
//
resources.ApplyResources(this.cellBaseSite, "cellBaseSite");
this.cellBaseSite.StylePriority.UseBorders = false;
this.cellBaseSite.StylePriority.UseFont = false;
this.cellBaseSite.StylePriority.UseTextAlignment = false;
//
// cellBaseCountry
//
resources.ApplyResources(this.cellBaseCountry, "cellBaseCountry");
//
// cellBaseLeftHeader
//
resources.ApplyResources(this.cellBaseLeftHeader, "cellBaseLeftHeader");
//
// tableBaseHeader
//
resources.ApplyResources(this.tableBaseHeader, "tableBaseHeader");
this.tableBaseHeader.StylePriority.UseBorders = false;
this.tableBaseHeader.StylePriority.UseBorderWidth = false;
this.tableBaseHeader.StylePriority.UseFont = false;
this.tableBaseHeader.StylePriority.UsePadding = false;
this.tableBaseHeader.StylePriority.UseTextAlignment = false;
//
// VetReport
//
this.VetReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.VetDetail,
this.VetReportHeader,
this.GroupHeaderDiagnosis,
this.GroupFooterDiagnosis,
this.GroupHeaderLine,
this.GroupFooterLine});
this.VetReport.DataAdapter = this.m_DataAdapter1;
this.VetReport.DataMember = "spRepVetForm1ADiagnosticInvestigationsAZ";
this.VetReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.VetReport, "VetReport");
this.VetReport.Level = 0;
this.VetReport.Name = "VetReport";
//
// VetDetail
//
this.VetDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable2});
resources.ApplyResources(this.VetDetail, "VetDetail");
this.VetDetail.KeepTogether = true;
this.VetDetail.Name = "VetDetail";
this.VetDetail.StylePriority.UseFont = false;
//
// xrTable2
//
this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable2, "xrTable2");
this.xrTable2.Name = "xrTable2";
this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow6});
this.xrTable2.StylePriority.UseBorders = false;
this.xrTable2.StylePriority.UseTextAlignment = false;
//
// xrTableRow6
//
this.xrTableRow6.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.RowNumberCell,
this.NameInvestigationCell,
this.DiseaseCell,
this.OIECell,
this.SpeciesCell,
this.NumberTested,
this.NumberPositive,
this.NoteCell});
resources.ApplyResources(this.xrTableRow6, "xrTableRow6");
this.xrTableRow6.Name = "xrTableRow6";
this.xrTableRow6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTableRow6.StylePriority.UsePadding = false;
//
// RowNumberCell
//
resources.ApplyResources(this.RowNumberCell, "RowNumberCell");
this.RowNumberCell.Name = "RowNumberCell";
this.RowNumberCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.RowNumberCell_BeforePrint);
//
// NameInvestigationCell
//
this.NameInvestigationCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.strInvestigationName")});
resources.ApplyResources(this.NameInvestigationCell, "NameInvestigationCell");
this.NameInvestigationCell.Name = "NameInvestigationCell";
//
// DiseaseCell
//
this.DiseaseCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.strDiagnosisName")});
resources.ApplyResources(this.DiseaseCell, "DiseaseCell");
this.DiseaseCell.Name = "DiseaseCell";
//
// OIECell
//
this.OIECell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.strOIECode")});
resources.ApplyResources(this.OIECell, "OIECell");
this.OIECell.Name = "OIECell";
//
// SpeciesCell
//
this.SpeciesCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.strSpecies")});
resources.ApplyResources(this.SpeciesCell, "SpeciesCell");
this.SpeciesCell.Name = "SpeciesCell";
this.SpeciesCell.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.SpeciesCell_BeforePrint);
//
// NumberTested
//
this.NumberTested.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.intTested")});
resources.ApplyResources(this.NumberTested, "NumberTested");
this.NumberTested.Name = "NumberTested";
//
// NumberPositive
//
this.NumberPositive.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.intPositivaReaction")});
resources.ApplyResources(this.NumberPositive, "NumberPositive");
this.NumberPositive.Name = "NumberPositive";
//
// NoteCell
//
this.NoteCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ADiagnosticInvestigationsAZ.strNote")});
resources.ApplyResources(this.NoteCell, "NoteCell");
this.NoteCell.Name = "NoteCell";
//
// VetReportHeader
//
this.VetReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLabel6,
this.xrTable3,
this.xrLabel5,
this.xrLabel4,
this.xrLabel3,
this.xrLabel2,
this.xrLabel1,
this.xrPictureBox1,
this.HeaderLabel,
this.xrTable1});
resources.ApplyResources(this.VetReportHeader, "VetReportHeader");
this.VetReportHeader.Name = "VetReportHeader";
this.VetReportHeader.StylePriority.UseFont = false;
//
// xrLabel6
//
resources.ApplyResources(this.xrLabel6, "xrLabel6");
this.xrLabel6.Name = "xrLabel6";
this.xrLabel6.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel6.StylePriority.UseFont = false;
this.xrLabel6.StylePriority.UseTextAlignment = false;
//
// xrTable3
//
resources.ApplyResources(this.xrTable3, "xrTable3");
this.xrTable3.Name = "xrTable3";
this.xrTable3.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow4,
this.xrTableRow7,
this.xrTableRow8});
//
// xrTableRow4
//
this.xrTableRow4.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell18,
this.Recipient});
resources.ApplyResources(this.xrTableRow4, "xrTableRow4");
this.xrTableRow4.Name = "xrTableRow4";
//
// xrTableCell18
//
resources.ApplyResources(this.xrTableCell18, "xrTableCell18");
this.xrTableCell18.Name = "xrTableCell18";
this.xrTableCell18.StylePriority.UseFont = false;
this.xrTableCell18.StylePriority.UseTextAlignment = false;
//
// Recipient
//
this.Recipient.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.Recipient, "Recipient");
this.Recipient.Name = "Recipient";
this.Recipient.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 0, 0, 0, 100F);
this.Recipient.StylePriority.UseBorders = false;
this.Recipient.StylePriority.UseFont = false;
this.Recipient.StylePriority.UsePadding = false;
this.Recipient.StylePriority.UseTextAlignment = false;
//
// xrTableRow7
//
this.xrTableRow7.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell22,
this.SentBy});
resources.ApplyResources(this.xrTableRow7, "xrTableRow7");
this.xrTableRow7.Name = "xrTableRow7";
//
// xrTableCell22
//
resources.ApplyResources(this.xrTableCell22, "xrTableCell22");
this.xrTableCell22.Name = "xrTableCell22";
this.xrTableCell22.StylePriority.UseFont = false;
this.xrTableCell22.StylePriority.UseTextAlignment = false;
//
// SentBy
//
this.SentBy.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.SentBy, "SentBy");
this.SentBy.Name = "SentBy";
this.SentBy.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 0, 0, 0, 100F);
this.SentBy.StylePriority.UseBorders = false;
this.SentBy.StylePriority.UseFont = false;
this.SentBy.StylePriority.UsePadding = false;
this.SentBy.StylePriority.UseTextAlignment = false;
//
// xrTableRow8
//
this.xrTableRow8.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell20,
this.ForReportPeriod});
resources.ApplyResources(this.xrTableRow8, "xrTableRow8");
this.xrTableRow8.Name = "xrTableRow8";
//
// xrTableCell20
//
resources.ApplyResources(this.xrTableCell20, "xrTableCell20");
this.xrTableCell20.Name = "xrTableCell20";
this.xrTableCell20.StylePriority.UseFont = false;
this.xrTableCell20.StylePriority.UseTextAlignment = false;
//
// ForReportPeriod
//
this.ForReportPeriod.Borders = DevExpress.XtraPrinting.BorderSide.Bottom;
resources.ApplyResources(this.ForReportPeriod, "ForReportPeriod");
this.ForReportPeriod.Name = "ForReportPeriod";
this.ForReportPeriod.Padding = new DevExpress.XtraPrinting.PaddingInfo(10, 0, 0, 0, 100F);
this.ForReportPeriod.StylePriority.UseBorders = false;
this.ForReportPeriod.StylePriority.UseFont = false;
this.ForReportPeriod.StylePriority.UsePadding = false;
this.ForReportPeriod.StylePriority.UseTextAlignment = false;
//
// xrLabel5
//
resources.ApplyResources(this.xrLabel5, "xrLabel5");
this.xrLabel5.Name = "xrLabel5";
this.xrLabel5.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel5.StylePriority.UseFont = false;
this.xrLabel5.StylePriority.UseTextAlignment = false;
//
// xrLabel4
//
resources.ApplyResources(this.xrLabel4, "xrLabel4");
this.xrLabel4.Multiline = true;
this.xrLabel4.Name = "xrLabel4";
this.xrLabel4.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel4.StylePriority.UseFont = false;
this.xrLabel4.StylePriority.UseTextAlignment = false;
//
// xrLabel3
//
resources.ApplyResources(this.xrLabel3, "xrLabel3");
this.xrLabel3.Name = "xrLabel3";
this.xrLabel3.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel3.StylePriority.UseFont = false;
this.xrLabel3.StylePriority.UseTextAlignment = false;
//
// xrLabel2
//
resources.ApplyResources(this.xrLabel2, "xrLabel2");
this.xrLabel2.Name = "xrLabel2";
this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel2.StylePriority.UseFont = false;
this.xrLabel2.StylePriority.UseTextAlignment = false;
//
// xrLabel1
//
resources.ApplyResources(this.xrLabel1, "xrLabel1");
this.xrLabel1.Multiline = true;
this.xrLabel1.Name = "xrLabel1";
this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel1.StylePriority.UseFont = false;
this.xrLabel1.StylePriority.UseTextAlignment = false;
//
// xrPictureBox1
//
resources.ApplyResources(this.xrPictureBox1, "xrPictureBox1");
this.xrPictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("xrPictureBox1.Image")));
this.xrPictureBox1.Name = "xrPictureBox1";
this.xrPictureBox1.Sizing = DevExpress.XtraPrinting.ImageSizeMode.ZoomImage;
//
// HeaderLabel
//
resources.ApplyResources(this.HeaderLabel, "HeaderLabel");
this.HeaderLabel.Name = "HeaderLabel";
this.HeaderLabel.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.HeaderLabel.StylePriority.UseFont = false;
this.HeaderLabel.StylePriority.UseTextAlignment = false;
//
// xrTable1
//
this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable1, "xrTable1");
this.xrTable1.Name = "xrTable1";
this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow5,
this.xrTableRow3});
this.xrTable1.StylePriority.UseBorders = false;
this.xrTable1.StylePriority.UseFont = false;
this.xrTable1.StylePriority.UseTextAlignment = false;
//
// xrTableRow5
//
this.xrTableRow5.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell4,
this.xrTableCell6,
this.xrTableCell1,
this.xrTableCell5,
this.xrTableCell7,
this.xrTableCell3,
this.xrTableCell24,
this.xrTableCell26});
resources.ApplyResources(this.xrTableRow5, "xrTableRow5");
this.xrTableRow5.Name = "xrTableRow5";
//
// xrTableCell4
//
this.xrTableCell4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell4, "xrTableCell4");
this.xrTableCell4.Name = "xrTableCell4";
this.xrTableCell4.StylePriority.UseBorders = false;
this.xrTableCell4.StylePriority.UseFont = false;
this.xrTableCell4.StylePriority.UseTextAlignment = false;
//
// xrTableCell6
//
this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell6, "xrTableCell6");
this.xrTableCell6.Name = "xrTableCell6";
this.xrTableCell6.StylePriority.UseBorders = false;
this.xrTableCell6.StylePriority.UseFont = false;
this.xrTableCell6.StylePriority.UseTextAlignment = false;
//
// xrTableCell1
//
this.xrTableCell1.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell1, "xrTableCell1");
this.xrTableCell1.Multiline = true;
this.xrTableCell1.Name = "xrTableCell1";
this.xrTableCell1.StylePriority.UseBorders = false;
this.xrTableCell1.StylePriority.UseFont = false;
this.xrTableCell1.StylePriority.UseTextAlignment = false;
//
// xrTableCell5
//
this.xrTableCell5.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell5, "xrTableCell5");
this.xrTableCell5.Multiline = true;
this.xrTableCell5.Name = "xrTableCell5";
this.xrTableCell5.StylePriority.UseBorders = false;
this.xrTableCell5.StylePriority.UseFont = false;
this.xrTableCell5.StylePriority.UseTextAlignment = false;
//
// xrTableCell7
//
this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell7, "xrTableCell7");
this.xrTableCell7.Name = "xrTableCell7";
this.xrTableCell7.StylePriority.UseBorders = false;
this.xrTableCell7.StylePriority.UseFont = false;
this.xrTableCell7.StylePriority.UseTextAlignment = false;
//
// xrTableCell3
//
this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell3, "xrTableCell3");
this.xrTableCell3.Name = "xrTableCell3";
this.xrTableCell3.StylePriority.UseBorders = false;
this.xrTableCell3.StylePriority.UseFont = false;
this.xrTableCell3.StylePriority.UseTextAlignment = false;
//
// xrTableCell24
//
resources.ApplyResources(this.xrTableCell24, "xrTableCell24");
this.xrTableCell24.Name = "xrTableCell24";
this.xrTableCell24.StylePriority.UseFont = false;
this.xrTableCell24.StylePriority.UseTextAlignment = false;
//
// xrTableCell26
//
resources.ApplyResources(this.xrTableCell26, "xrTableCell26");
this.xrTableCell26.Name = "xrTableCell26";
this.xrTableCell26.StylePriority.UseFont = false;
this.xrTableCell26.StylePriority.UseTextAlignment = false;
//
// xrTableRow3
//
this.xrTableRow3.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell10,
this.xrTableCell11,
this.xrTableCell12,
this.xrTableCell13,
this.xrTableCell16,
this.xrTableCell17,
this.xrTableCell25,
this.xrTableCell27});
resources.ApplyResources(this.xrTableRow3, "xrTableRow3");
this.xrTableRow3.Name = "xrTableRow3";
//
// xrTableCell10
//
resources.ApplyResources(this.xrTableCell10, "xrTableCell10");
this.xrTableCell10.Name = "xrTableCell10";
this.xrTableCell10.StylePriority.UseFont = false;
//
// xrTableCell11
//
resources.ApplyResources(this.xrTableCell11, "xrTableCell11");
this.xrTableCell11.Name = "xrTableCell11";
this.xrTableCell11.StylePriority.UseFont = false;
this.xrTableCell11.StylePriority.UseTextAlignment = false;
//
// xrTableCell12
//
resources.ApplyResources(this.xrTableCell12, "xrTableCell12");
this.xrTableCell12.Name = "xrTableCell12";
this.xrTableCell12.StylePriority.UseFont = false;
//
// xrTableCell13
//
resources.ApplyResources(this.xrTableCell13, "xrTableCell13");
this.xrTableCell13.Name = "xrTableCell13";
this.xrTableCell13.StylePriority.UseFont = false;
//
// xrTableCell16
//
resources.ApplyResources(this.xrTableCell16, "xrTableCell16");
this.xrTableCell16.Name = "xrTableCell16";
this.xrTableCell16.StylePriority.UseFont = false;
//
// xrTableCell17
//
resources.ApplyResources(this.xrTableCell17, "xrTableCell17");
this.xrTableCell17.Name = "xrTableCell17";
this.xrTableCell17.StylePriority.UseFont = false;
//
// xrTableCell25
//
resources.ApplyResources(this.xrTableCell25, "xrTableCell25");
this.xrTableCell25.Multiline = true;
this.xrTableCell25.Name = "xrTableCell25";
this.xrTableCell25.StylePriority.UseFont = false;
//
// xrTableCell27
//
resources.ApplyResources(this.xrTableCell27, "xrTableCell27");
this.xrTableCell27.Name = "xrTableCell27";
this.xrTableCell27.StylePriority.UseFont = false;
//
// GroupHeaderDiagnosis
//
resources.ApplyResources(this.GroupHeaderDiagnosis, "GroupHeaderDiagnosis");
this.GroupHeaderDiagnosis.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] {
new DevExpress.XtraReports.UI.GroupField("InvestigationOrderColumn", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("strInvestigationName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("DiagnosisOrderColumn", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("strDiagnosisName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)});
this.GroupHeaderDiagnosis.Name = "GroupHeaderDiagnosis";
//
// GroupFooterDiagnosis
//
resources.ApplyResources(this.GroupFooterDiagnosis, "GroupFooterDiagnosis");
this.GroupFooterDiagnosis.Name = "GroupFooterDiagnosis";
this.GroupFooterDiagnosis.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.GroupFooterDiagnosis_BeforePrint);
//
// GroupHeaderLine
//
this.GroupHeaderLine.BorderWidth = 1F;
this.GroupHeaderLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine2});
resources.ApplyResources(this.GroupHeaderLine, "GroupHeaderLine");
this.GroupHeaderLine.Level = 1;
this.GroupHeaderLine.Name = "GroupHeaderLine";
this.GroupHeaderLine.RepeatEveryPage = true;
this.GroupHeaderLine.StylePriority.UseBorderWidth = false;
this.GroupHeaderLine.StylePriority.UseTextAlignment = false;
//
// xrLine2
//
this.xrLine2.BorderWidth = 0F;
resources.ApplyResources(this.xrLine2, "xrLine2");
this.xrLine2.LineWidth = 0;
this.xrLine2.Name = "xrLine2";
this.xrLine2.StylePriority.UseBorderWidth = false;
//
// GroupFooterLine
//
this.GroupFooterLine.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine1});
resources.ApplyResources(this.GroupFooterLine, "GroupFooterLine");
this.GroupFooterLine.Level = 1;
this.GroupFooterLine.Name = "GroupFooterLine";
this.GroupFooterLine.RepeatEveryPage = true;
//
// xrLine1
//
this.xrLine1.BorderWidth = 0F;
resources.ApplyResources(this.xrLine1, "xrLine1");
this.xrLine1.LineWidth = 0;
this.xrLine1.Name = "xrLine1";
this.xrLine1.StylePriority.UseBorderWidth = false;
//
// m_DataAdapter1
//
this.m_DataAdapter1.ClearBeforeFill = true;
//
// m_DataSet
//
this.m_DataSet.DataSetName = "VetForm1ADataSet";
this.m_DataSet.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
//
// m_DataAdapter2
//
this.m_DataAdapter2.ClearBeforeFill = true;
//
// m_DataAdapter3
//
this.m_DataAdapter3.ClearBeforeFill = true;
//
// SanitaryMeasuresReport
//
this.SanitaryMeasuresReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.SanitaryMeasuresDetail,
this.ReportFooter1,
this.SanitaryMeasuresHeader,
this.GroupFooterLine3});
this.SanitaryMeasuresReport.DataAdapter = this.m_DataAdapter3;
this.SanitaryMeasuresReport.DataMember = "spRepVetForm1ASanitaryMeasuresAZ";
this.SanitaryMeasuresReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.SanitaryMeasuresReport, "SanitaryMeasuresReport");
this.SanitaryMeasuresReport.Level = 2;
this.SanitaryMeasuresReport.Name = "SanitaryMeasuresReport";
//
// SanitaryMeasuresDetail
//
this.SanitaryMeasuresDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable8});
resources.ApplyResources(this.SanitaryMeasuresDetail, "SanitaryMeasuresDetail");
this.SanitaryMeasuresDetail.KeepTogether = true;
this.SanitaryMeasuresDetail.Name = "SanitaryMeasuresDetail";
this.SanitaryMeasuresDetail.StylePriority.UseFont = false;
//
// xrTable8
//
this.xrTable8.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable8, "xrTable8");
this.xrTable8.Name = "xrTable8";
this.xrTable8.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow15});
this.xrTable8.StylePriority.UseBorders = false;
this.xrTable8.StylePriority.UseTextAlignment = false;
//
// xrTableRow15
//
this.xrTableRow15.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.RowNumberCell3,
this.NameActionCell,
this.NumberFacilities,
this.SquareCell,
this.NoteCell3});
resources.ApplyResources(this.xrTableRow15, "xrTableRow15");
this.xrTableRow15.Name = "xrTableRow15";
this.xrTableRow15.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTableRow15.StylePriority.UsePadding = false;
//
// RowNumberCell3
//
this.RowNumberCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.RowNumberCell3, "RowNumberCell3");
this.RowNumberCell3.Name = "RowNumberCell3";
this.RowNumberCell3.StylePriority.UseBorders = false;
resources.ApplyResources(xrSummary1, "xrSummary1");
xrSummary1.Func = DevExpress.XtraReports.UI.SummaryFunc.RecordNumber;
xrSummary1.Running = DevExpress.XtraReports.UI.SummaryRunning.Group;
this.RowNumberCell3.Summary = xrSummary1;
//
// NameActionCell
//
this.NameActionCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.NameActionCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ASanitaryMeasuresAZ.strMeasureName")});
resources.ApplyResources(this.NameActionCell, "NameActionCell");
this.NameActionCell.Name = "NameActionCell";
this.NameActionCell.StylePriority.UseBorders = false;
//
// NumberFacilities
//
this.NumberFacilities.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.NumberFacilities.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ASanitaryMeasuresAZ.intNumberFacilities")});
resources.ApplyResources(this.NumberFacilities, "NumberFacilities");
this.NumberFacilities.Name = "NumberFacilities";
this.NumberFacilities.StylePriority.UseBorders = false;
//
// SquareCell
//
this.SquareCell.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.SquareCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ASanitaryMeasuresAZ.intSquare")});
resources.ApplyResources(this.SquareCell, "SquareCell");
this.SquareCell.Name = "SquareCell";
this.SquareCell.StylePriority.UseBorders = false;
//
// NoteCell3
//
this.NoteCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
this.NoteCell3.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1ASanitaryMeasuresAZ.strNote")});
resources.ApplyResources(this.NoteCell3, "NoteCell3");
this.NoteCell3.Name = "NoteCell3";
this.NoteCell3.StylePriority.UseBorders = false;
//
// ReportFooter1
//
this.ReportFooter1.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable5});
resources.ApplyResources(this.ReportFooter1, "ReportFooter1");
this.ReportFooter1.Name = "ReportFooter1";
this.ReportFooter1.StylePriority.UseFont = false;
//
// xrTable5
//
resources.ApplyResources(this.xrTable5, "xrTable5");
this.xrTable5.Name = "xrTable5";
this.xrTable5.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow10,
this.xrTableRow11});
this.xrTable5.StylePriority.UseTextAlignment = false;
//
// xrTableRow10
//
this.xrTableRow10.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell21,
this.PerformerCell});
resources.ApplyResources(this.xrTableRow10, "xrTableRow10");
this.xrTableRow10.Name = "xrTableRow10";
//
// xrTableCell21
//
resources.ApplyResources(this.xrTableCell21, "xrTableCell21");
this.xrTableCell21.Name = "xrTableCell21";
this.xrTableCell21.StylePriority.UseFont = false;
//
// PerformerCell
//
resources.ApplyResources(this.PerformerCell, "PerformerCell");
this.PerformerCell.Name = "PerformerCell";
this.PerformerCell.StylePriority.UseFont = false;
//
// xrTableRow11
//
this.xrTableRow11.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell19,
this.xrTableCell9,
this.xrTableCell53,
this.DateTimeCell});
resources.ApplyResources(this.xrTableRow11, "xrTableRow11");
this.xrTableRow11.Name = "xrTableRow11";
//
// xrTableCell19
//
resources.ApplyResources(this.xrTableCell19, "xrTableCell19");
this.xrTableCell19.Name = "xrTableCell19";
//
// xrTableCell9
//
resources.ApplyResources(this.xrTableCell9, "xrTableCell9");
this.xrTableCell9.Name = "xrTableCell9";
//
// xrTableCell53
//
resources.ApplyResources(this.xrTableCell53, "xrTableCell53");
this.xrTableCell53.Name = "xrTableCell53";
this.xrTableCell53.StylePriority.UseFont = false;
//
// DateTimeCell
//
resources.ApplyResources(this.DateTimeCell, "DateTimeCell");
this.DateTimeCell.Name = "DateTimeCell";
this.DateTimeCell.StylePriority.UseFont = false;
//
// SanitaryMeasuresHeader
//
this.SanitaryMeasuresHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable6,
this.xrLabel8});
resources.ApplyResources(this.SanitaryMeasuresHeader, "SanitaryMeasuresHeader");
this.SanitaryMeasuresHeader.KeepTogether = true;
this.SanitaryMeasuresHeader.Name = "SanitaryMeasuresHeader";
this.SanitaryMeasuresHeader.StylePriority.UseFont = false;
//
// xrTable6
//
this.xrTable6.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable6, "xrTable6");
this.xrTable6.Name = "xrTable6";
this.xrTable6.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow13,
this.xrTableRow9,
this.xrTableRow12});
this.xrTable6.StylePriority.UseBorders = false;
this.xrTable6.StylePriority.UseFont = false;
this.xrTable6.StylePriority.UseTextAlignment = false;
//
// xrTableRow13
//
this.xrTableRow13.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell31,
this.xrTableCell40,
this.xrTableCell43,
this.xrTableCell44});
resources.ApplyResources(this.xrTableRow13, "xrTableRow13");
this.xrTableRow13.Name = "xrTableRow13";
//
// xrTableCell31
//
resources.ApplyResources(this.xrTableCell31, "xrTableCell31");
this.xrTableCell31.Name = "xrTableCell31";
this.xrTableCell31.StylePriority.UseTextAlignment = false;
//
// xrTableCell40
//
resources.ApplyResources(this.xrTableCell40, "xrTableCell40");
this.xrTableCell40.Name = "xrTableCell40";
this.xrTableCell40.StylePriority.UseTextAlignment = false;
//
// xrTableCell43
//
resources.ApplyResources(this.xrTableCell43, "xrTableCell43");
this.xrTableCell43.Name = "xrTableCell43";
//
// xrTableCell44
//
resources.ApplyResources(this.xrTableCell44, "xrTableCell44");
this.xrTableCell44.Name = "xrTableCell44";
//
// xrTableRow9
//
this.xrTableRow9.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell41,
this.xrTableCell42,
this.xrTableCell46,
this.xrTableCell48,
this.xrTableCell49});
resources.ApplyResources(this.xrTableRow9, "xrTableRow9");
this.xrTableRow9.Name = "xrTableRow9";
//
// xrTableCell41
//
this.xrTableCell41.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell41, "xrTableCell41");
this.xrTableCell41.Name = "xrTableCell41";
this.xrTableCell41.StylePriority.UseBorders = false;
this.xrTableCell41.StylePriority.UseFont = false;
this.xrTableCell41.StylePriority.UseTextAlignment = false;
//
// xrTableCell42
//
this.xrTableCell42.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell42, "xrTableCell42");
this.xrTableCell42.Name = "xrTableCell42";
this.xrTableCell42.StylePriority.UseBorders = false;
this.xrTableCell42.StylePriority.UseFont = false;
this.xrTableCell42.StylePriority.UseTextAlignment = false;
//
// xrTableCell46
//
this.xrTableCell46.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell46, "xrTableCell46");
this.xrTableCell46.Name = "xrTableCell46";
this.xrTableCell46.StylePriority.UseBorders = false;
this.xrTableCell46.StylePriority.UseFont = false;
this.xrTableCell46.StylePriority.UseTextAlignment = false;
//
// xrTableCell48
//
resources.ApplyResources(this.xrTableCell48, "xrTableCell48");
this.xrTableCell48.Name = "xrTableCell48";
//
// xrTableCell49
//
this.xrTableCell49.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell49, "xrTableCell49");
this.xrTableCell49.Name = "xrTableCell49";
this.xrTableCell49.StylePriority.UseBorders = false;
this.xrTableCell49.StylePriority.UseFont = false;
this.xrTableCell49.StylePriority.UseTextAlignment = false;
//
// xrTableRow12
//
this.xrTableRow12.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell50,
this.xrTableCell51,
this.xrTableCell58,
this.xrTableCell45,
this.xrTableCell60});
resources.ApplyResources(this.xrTableRow12, "xrTableRow12");
this.xrTableRow12.Name = "xrTableRow12";
//
// xrTableCell50
//
resources.ApplyResources(this.xrTableCell50, "xrTableCell50");
this.xrTableCell50.Name = "xrTableCell50";
this.xrTableCell50.StylePriority.UseFont = false;
//
// xrTableCell51
//
resources.ApplyResources(this.xrTableCell51, "xrTableCell51");
this.xrTableCell51.Name = "xrTableCell51";
this.xrTableCell51.StylePriority.UseFont = false;
this.xrTableCell51.StylePriority.UseTextAlignment = false;
//
// xrTableCell58
//
resources.ApplyResources(this.xrTableCell58, "xrTableCell58");
this.xrTableCell58.Name = "xrTableCell58";
this.xrTableCell58.StylePriority.UseFont = false;
//
// xrTableCell45
//
resources.ApplyResources(this.xrTableCell45, "xrTableCell45");
this.xrTableCell45.Name = "xrTableCell45";
this.xrTableCell45.StylePriority.UseFont = false;
//
// xrTableCell60
//
resources.ApplyResources(this.xrTableCell60, "xrTableCell60");
this.xrTableCell60.Name = "xrTableCell60";
this.xrTableCell60.StylePriority.UseFont = false;
//
// xrLabel8
//
resources.ApplyResources(this.xrLabel8, "xrLabel8");
this.xrLabel8.Name = "xrLabel8";
this.xrLabel8.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel8.StylePriority.UseFont = false;
this.xrLabel8.StylePriority.UseTextAlignment = false;
//
// GroupFooterLine3
//
this.GroupFooterLine3.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine6});
resources.ApplyResources(this.GroupFooterLine3, "GroupFooterLine3");
this.GroupFooterLine3.Name = "GroupFooterLine3";
this.GroupFooterLine3.RepeatEveryPage = true;
//
// xrLine6
//
this.xrLine6.BorderWidth = 0F;
resources.ApplyResources(this.xrLine6, "xrLine6");
this.xrLine6.LineWidth = 0;
this.xrLine6.Name = "xrLine6";
this.xrLine6.StylePriority.UseBorderWidth = false;
//
// VaccinationMeasuresReport
//
this.VaccinationMeasuresReport.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.VaccinationMeasuresDetail,
this.VaccinationMeasuresHeader,
this.GroupHeaderLine2,
this.GroupFooterLine2,
this.GroupFooterDiagnosis2,
this.GroupHeaderDiagnosis2});
this.VaccinationMeasuresReport.DataAdapter = this.m_DataAdapter2;
this.VaccinationMeasuresReport.DataMember = "spRepVetForm1AVaccinationMeasuresAZ";
this.VaccinationMeasuresReport.DataSource = this.m_DataSet;
resources.ApplyResources(this.VaccinationMeasuresReport, "VaccinationMeasuresReport");
this.VaccinationMeasuresReport.Level = 1;
this.VaccinationMeasuresReport.Name = "VaccinationMeasuresReport";
//
// VaccinationMeasuresDetail
//
this.VaccinationMeasuresDetail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable7});
resources.ApplyResources(this.VaccinationMeasuresDetail, "VaccinationMeasuresDetail");
this.VaccinationMeasuresDetail.KeepTogether = true;
this.VaccinationMeasuresDetail.Name = "VaccinationMeasuresDetail";
this.VaccinationMeasuresDetail.StylePriority.UseFont = false;
//
// xrTable7
//
this.xrTable7.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable7, "xrTable7");
this.xrTable7.Name = "xrTable7";
this.xrTable7.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow14});
this.xrTable7.StylePriority.UseBorders = false;
this.xrTable7.StylePriority.UseTextAlignment = false;
//
// xrTableRow14
//
this.xrTableRow14.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.RowNumberCell2,
this.NameMeasureCell,
this.DiseaseCell2,
this.OIECell2,
this.SpeciesCell2,
this.NumberTaken,
this.NoteCell2});
resources.ApplyResources(this.xrTableRow14, "xrTableRow14");
this.xrTableRow14.Name = "xrTableRow14";
this.xrTableRow14.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 2, 2, 100F);
this.xrTableRow14.StylePriority.UsePadding = false;
//
// RowNumberCell2
//
this.RowNumberCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.RowNumberCell2, "RowNumberCell2");
this.RowNumberCell2.Name = "RowNumberCell2";
this.RowNumberCell2.StylePriority.UseBorders = false;
this.RowNumberCell2.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.RowNumberCell2_BeforePrint);
//
// NameMeasureCell
//
this.NameMeasureCell.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.strMeasureName")});
resources.ApplyResources(this.NameMeasureCell, "NameMeasureCell");
this.NameMeasureCell.Name = "NameMeasureCell";
//
// DiseaseCell2
//
this.DiseaseCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.strDiagnosisName")});
resources.ApplyResources(this.DiseaseCell2, "DiseaseCell2");
this.DiseaseCell2.Name = "DiseaseCell2";
//
// OIECell2
//
this.OIECell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.strOIECode")});
resources.ApplyResources(this.OIECell2, "OIECell2");
this.OIECell2.Name = "OIECell2";
//
// SpeciesCell2
//
this.SpeciesCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.strSpecies")});
resources.ApplyResources(this.SpeciesCell2, "SpeciesCell2");
this.SpeciesCell2.Name = "SpeciesCell2";
this.SpeciesCell2.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.SpeciesCell2_BeforePrint);
//
// NumberTaken
//
this.NumberTaken.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.intActionTaken")});
resources.ApplyResources(this.NumberTaken, "NumberTaken");
this.NumberTaken.Name = "NumberTaken";
//
// NoteCell2
//
this.NoteCell2.DataBindings.AddRange(new DevExpress.XtraReports.UI.XRBinding[] {
new DevExpress.XtraReports.UI.XRBinding("Text", null, "spRepVetForm1AVaccinationMeasuresAZ.strNote")});
resources.ApplyResources(this.NoteCell2, "NoteCell2");
this.NoteCell2.Name = "NoteCell2";
//
// VaccinationMeasuresHeader
//
this.VaccinationMeasuresHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrTable4,
this.xrLabel7});
resources.ApplyResources(this.VaccinationMeasuresHeader, "VaccinationMeasuresHeader");
this.VaccinationMeasuresHeader.KeepTogether = true;
this.VaccinationMeasuresHeader.Name = "VaccinationMeasuresHeader";
this.VaccinationMeasuresHeader.StylePriority.UseFont = false;
//
// xrTable4
//
this.xrTable4.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTable4, "xrTable4");
this.xrTable4.Name = "xrTable4";
this.xrTable4.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] {
this.xrTableRow1,
this.xrTableRow2});
this.xrTable4.StylePriority.UseBorders = false;
this.xrTable4.StylePriority.UseFont = false;
this.xrTable4.StylePriority.UseTextAlignment = false;
//
// xrTableRow1
//
this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell2,
this.xrTableCell14,
this.xrTableCell15,
this.xrTableCell23,
this.xrTableCell28,
this.xrTableCell29,
this.xrTableCell30});
resources.ApplyResources(this.xrTableRow1, "xrTableRow1");
this.xrTableRow1.Name = "xrTableRow1";
//
// xrTableCell2
//
this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell2, "xrTableCell2");
this.xrTableCell2.Name = "xrTableCell2";
this.xrTableCell2.StylePriority.UseBorders = false;
this.xrTableCell2.StylePriority.UseFont = false;
this.xrTableCell2.StylePriority.UseTextAlignment = false;
//
// xrTableCell14
//
this.xrTableCell14.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell14, "xrTableCell14");
this.xrTableCell14.Name = "xrTableCell14";
this.xrTableCell14.StylePriority.UseBorders = false;
this.xrTableCell14.StylePriority.UseFont = false;
this.xrTableCell14.StylePriority.UseTextAlignment = false;
//
// xrTableCell15
//
this.xrTableCell15.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell15, "xrTableCell15");
this.xrTableCell15.Multiline = true;
this.xrTableCell15.Name = "xrTableCell15";
this.xrTableCell15.StylePriority.UseBorders = false;
this.xrTableCell15.StylePriority.UseFont = false;
this.xrTableCell15.StylePriority.UseTextAlignment = false;
//
// xrTableCell23
//
this.xrTableCell23.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell23, "xrTableCell23");
this.xrTableCell23.Multiline = true;
this.xrTableCell23.Name = "xrTableCell23";
this.xrTableCell23.StylePriority.UseBorders = false;
this.xrTableCell23.StylePriority.UseFont = false;
this.xrTableCell23.StylePriority.UseTextAlignment = false;
//
// xrTableCell28
//
this.xrTableCell28.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell28, "xrTableCell28");
this.xrTableCell28.Name = "xrTableCell28";
this.xrTableCell28.StylePriority.UseBorders = false;
this.xrTableCell28.StylePriority.UseFont = false;
this.xrTableCell28.StylePriority.UseTextAlignment = false;
//
// xrTableCell29
//
this.xrTableCell29.Borders = ((DevExpress.XtraPrinting.BorderSide)(((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top)
| DevExpress.XtraPrinting.BorderSide.Right)));
resources.ApplyResources(this.xrTableCell29, "xrTableCell29");
this.xrTableCell29.Multiline = true;
this.xrTableCell29.Name = "xrTableCell29";
this.xrTableCell29.StylePriority.UseBorders = false;
this.xrTableCell29.StylePriority.UseFont = false;
this.xrTableCell29.StylePriority.UseTextAlignment = false;
//
// xrTableCell30
//
resources.ApplyResources(this.xrTableCell30, "xrTableCell30");
this.xrTableCell30.Name = "xrTableCell30";
this.xrTableCell30.StylePriority.UseFont = false;
this.xrTableCell30.StylePriority.UseTextAlignment = false;
//
// xrTableRow2
//
this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] {
this.xrTableCell32,
this.xrTableCell34,
this.xrTableCell35,
this.xrTableCell36,
this.xrTableCell37,
this.xrTableCell38,
this.xrTableCell39});
resources.ApplyResources(this.xrTableRow2, "xrTableRow2");
this.xrTableRow2.Name = "xrTableRow2";
//
// xrTableCell32
//
resources.ApplyResources(this.xrTableCell32, "xrTableCell32");
this.xrTableCell32.Name = "xrTableCell32";
this.xrTableCell32.StylePriority.UseFont = false;
//
// xrTableCell34
//
resources.ApplyResources(this.xrTableCell34, "xrTableCell34");
this.xrTableCell34.Name = "xrTableCell34";
this.xrTableCell34.StylePriority.UseFont = false;
this.xrTableCell34.StylePriority.UseTextAlignment = false;
//
// xrTableCell35
//
resources.ApplyResources(this.xrTableCell35, "xrTableCell35");
this.xrTableCell35.Name = "xrTableCell35";
this.xrTableCell35.StylePriority.UseFont = false;
//
// xrTableCell36
//
resources.ApplyResources(this.xrTableCell36, "xrTableCell36");
this.xrTableCell36.Name = "xrTableCell36";
this.xrTableCell36.StylePriority.UseFont = false;
//
// xrTableCell37
//
resources.ApplyResources(this.xrTableCell37, "xrTableCell37");
this.xrTableCell37.Name = "xrTableCell37";
this.xrTableCell37.StylePriority.UseFont = false;
//
// xrTableCell38
//
resources.ApplyResources(this.xrTableCell38, "xrTableCell38");
this.xrTableCell38.Name = "xrTableCell38";
this.xrTableCell38.StylePriority.UseFont = false;
//
// xrTableCell39
//
resources.ApplyResources(this.xrTableCell39, "xrTableCell39");
this.xrTableCell39.Multiline = true;
this.xrTableCell39.Name = "xrTableCell39";
this.xrTableCell39.StylePriority.UseFont = false;
//
// xrLabel7
//
resources.ApplyResources(this.xrLabel7, "xrLabel7");
this.xrLabel7.Name = "xrLabel7";
this.xrLabel7.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F);
this.xrLabel7.StylePriority.UseFont = false;
this.xrLabel7.StylePriority.UseTextAlignment = false;
//
// GroupHeaderLine2
//
this.GroupHeaderLine2.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine3});
resources.ApplyResources(this.GroupHeaderLine2, "GroupHeaderLine2");
this.GroupHeaderLine2.Level = 1;
this.GroupHeaderLine2.Name = "GroupHeaderLine2";
this.GroupHeaderLine2.RepeatEveryPage = true;
//
// xrLine3
//
this.xrLine3.BorderWidth = 0F;
resources.ApplyResources(this.xrLine3, "xrLine3");
this.xrLine3.LineWidth = 0;
this.xrLine3.Name = "xrLine3";
this.xrLine3.StylePriority.UseBorderWidth = false;
//
// GroupFooterLine2
//
this.GroupFooterLine2.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] {
this.xrLine5});
resources.ApplyResources(this.GroupFooterLine2, "GroupFooterLine2");
this.GroupFooterLine2.Level = 1;
this.GroupFooterLine2.Name = "GroupFooterLine2";
this.GroupFooterLine2.RepeatEveryPage = true;
//
// xrLine5
//
this.xrLine5.BorderWidth = 0F;
resources.ApplyResources(this.xrLine5, "xrLine5");
this.xrLine5.LineWidth = 0;
this.xrLine5.Name = "xrLine5";
this.xrLine5.StylePriority.UseBorderWidth = false;
//
// GroupFooterDiagnosis2
//
resources.ApplyResources(this.GroupFooterDiagnosis2, "GroupFooterDiagnosis2");
this.GroupFooterDiagnosis2.Name = "GroupFooterDiagnosis2";
this.GroupFooterDiagnosis2.BeforePrint += new System.Drawing.Printing.PrintEventHandler(this.GroupFooterDiagnosis2_BeforePrint);
//
// GroupHeaderDiagnosis2
//
resources.ApplyResources(this.GroupHeaderDiagnosis2, "GroupHeaderDiagnosis2");
this.GroupHeaderDiagnosis2.GroupFields.AddRange(new DevExpress.XtraReports.UI.GroupField[] {
new DevExpress.XtraReports.UI.GroupField("InvestigationOrderColumn", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("strMeasureName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("DiagnosisOrderColumn", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending),
new DevExpress.XtraReports.UI.GroupField("strDiagnosisName", DevExpress.XtraReports.UI.XRColumnSortOrder.Ascending)});
this.GroupHeaderDiagnosis2.Name = "GroupHeaderDiagnosis2";
//
// spRepVetForm1ADiagnosticInvestigationsAZTableAdapter
//
this.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter.ClearBeforeFill = true;
//
// FormVet1A
//
this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] {
this.Detail,
this.PageHeader,
this.PageFooter,
this.ReportHeader,
this.VetReport,
this.SanitaryMeasuresReport,
this.VaccinationMeasuresReport});
resources.ApplyResources(this, "$this");
this.Version = "14.1";
this.Controls.SetChildIndex(this.VaccinationMeasuresReport, 0);
this.Controls.SetChildIndex(this.SanitaryMeasuresReport, 0);
this.Controls.SetChildIndex(this.VetReport, 0);
this.Controls.SetChildIndex(this.ReportHeader, 0);
this.Controls.SetChildIndex(this.PageFooter, 0);
this.Controls.SetChildIndex(this.PageHeader, 0);
this.Controls.SetChildIndex(this.Detail, 0);
((System.ComponentModel.ISupportInitialize)(this.m_BaseDataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.tableBaseHeader)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.m_DataSet)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable8)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.xrTable4)).EndInit();
((System.ComponentModel.ISupportInitialize)(this)).EndInit();
}
#endregion
private DevExpress.XtraReports.UI.DetailReportBand VetReport;
private DevExpress.XtraReports.UI.DetailBand VetDetail;
private DevExpress.XtraReports.UI.ReportHeaderBand VetReportHeader;
private DevExpress.XtraReports.UI.XRTable xrTable1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell5;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell3;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderDiagnosis;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterDiagnosis;
private DevExpress.XtraReports.UI.XRLine xrLine1;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderLine;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterLine;
private DevExpress.XtraReports.UI.XRTable xrTable2;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow6;
private DevExpress.XtraReports.UI.XRTableCell RowNumberCell;
private DevExpress.XtraReports.UI.XRTableCell NameInvestigationCell;
private DevExpress.XtraReports.UI.XRTableCell DiseaseCell;
private DevExpress.XtraReports.UI.XRTableCell OIECell;
private DataSets.VetForm1ADataSet m_DataSet;
private DevExpress.XtraReports.UI.XRLine xrLine2;
private DevExpress.XtraReports.UI.XRLabel HeaderLabel;
private DevExpress.XtraReports.UI.XRTable xrTable3;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow4;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell18;
private DevExpress.XtraReports.UI.XRTableCell Recipient;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow7;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell22;
private DevExpress.XtraReports.UI.XRTableCell SentBy;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow8;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell20;
private DevExpress.XtraReports.UI.XRTableCell ForReportPeriod;
private DevExpress.XtraReports.UI.XRLabel xrLabel5;
private DevExpress.XtraReports.UI.XRLabel xrLabel4;
private DevExpress.XtraReports.UI.XRLabel xrLabel3;
private DevExpress.XtraReports.UI.XRLabel xrLabel2;
private DevExpress.XtraReports.UI.XRLabel xrLabel1;
private DevExpress.XtraReports.UI.XRPictureBox xrPictureBox1;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow3;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell16;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell17;
private DevExpress.XtraReports.UI.XRTableCell SpeciesCell;
private DevExpress.XtraReports.UI.XRTableCell NumberTested;
private DevExpress.XtraReports.UI.XRTableCell NumberPositive;
private DevExpress.XtraReports.UI.XRTableCell NoteCell;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell24;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell26;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell25;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell27;
private DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter m_DataAdapter1;
private DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1AVaccinationMeasuresAZTableAdapter m_DataAdapter2;
private DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ASanitaryMeasuresAZTableAdapter m_DataAdapter3;
private DevExpress.XtraReports.UI.DetailReportBand SanitaryMeasuresReport;
private DevExpress.XtraReports.UI.DetailBand SanitaryMeasuresDetail;
private DevExpress.XtraReports.UI.DetailReportBand VaccinationMeasuresReport;
private DevExpress.XtraReports.UI.DetailBand VaccinationMeasuresDetail;
private DataSets.VetForm1ADataSetTableAdapters.spRepVetForm1ADiagnosticInvestigationsAZTableAdapter spRepVetForm1ADiagnosticInvestigationsAZTableAdapter;
private DevExpress.XtraReports.UI.ReportFooterBand ReportFooter1;
private DevExpress.XtraReports.UI.XRTable xrTable5;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow10;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell21;
private DevExpress.XtraReports.UI.XRTableCell PerformerCell;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow11;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell53;
private DevExpress.XtraReports.UI.XRTableCell DateTimeCell;
private DevExpress.XtraReports.UI.ReportHeaderBand SanitaryMeasuresHeader;
private DevExpress.XtraReports.UI.ReportHeaderBand VaccinationMeasuresHeader;
private DevExpress.XtraReports.UI.XRLabel xrLabel6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell6;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell11;
private DevExpress.XtraReports.UI.XRTable xrTable6;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow13;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell31;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell40;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell43;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell44;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow9;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell41;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell42;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell46;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell48;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell49;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow12;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell50;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell51;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell58;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell45;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell60;
private DevExpress.XtraReports.UI.XRLabel xrLabel8;
private DevExpress.XtraReports.UI.XRTable xrTable7;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow14;
private DevExpress.XtraReports.UI.XRTableCell RowNumberCell2;
private DevExpress.XtraReports.UI.XRTableCell NameMeasureCell;
private DevExpress.XtraReports.UI.XRTableCell DiseaseCell2;
private DevExpress.XtraReports.UI.XRTableCell OIECell2;
private DevExpress.XtraReports.UI.XRTableCell SpeciesCell2;
private DevExpress.XtraReports.UI.XRTableCell NumberTaken;
private DevExpress.XtraReports.UI.XRTableCell NoteCell2;
private DevExpress.XtraReports.UI.XRTable xrTable4;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow1;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell14;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell15;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell23;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell28;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell29;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell30;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell32;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell34;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell35;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell36;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell37;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell38;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell39;
private DevExpress.XtraReports.UI.XRLabel xrLabel7;
private DevExpress.XtraReports.UI.XRTable xrTable8;
private DevExpress.XtraReports.UI.XRTableRow xrTableRow15;
private DevExpress.XtraReports.UI.XRTableCell RowNumberCell3;
private DevExpress.XtraReports.UI.XRTableCell NameActionCell;
private DevExpress.XtraReports.UI.XRTableCell NumberFacilities;
private DevExpress.XtraReports.UI.XRTableCell SquareCell;
private DevExpress.XtraReports.UI.XRTableCell NoteCell3;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderLine2;
private DevExpress.XtraReports.UI.XRLine xrLine3;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterLine3;
private DevExpress.XtraReports.UI.XRLine xrLine6;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterLine2;
private DevExpress.XtraReports.UI.XRLine xrLine5;
private DevExpress.XtraReports.UI.GroupFooterBand GroupFooterDiagnosis2;
private DevExpress.XtraReports.UI.GroupHeaderBand GroupHeaderDiagnosis2;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell19;
private DevExpress.XtraReports.UI.XRTableCell xrTableCell9;
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, ".NET Framework throws PNSE for ServerCertificateCustomValidationCallback")]
public partial class HttpClientHandler_ServerCertificates_Test : HttpClientTestBase
{
private static bool ClientSupportsDHECipherSuites => (!PlatformDetection.IsWindows || PlatformDetection.IsWindows10Version1607OrGreater);
private bool BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites =>
(BackendSupportsCustomCertificateHandling && ClientSupportsDHECipherSuites);
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultPropertyValues_UapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.True(handler.CheckCertificateRevocationList);
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap)]
public void Ctor_ExpectedDefaultValues_NotUapPlatform()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Assert.False(handler.CheckCertificateRevocationList);
}
}
[Fact]
public void ServerCertificateCustomValidationCallback_SetGet_Roundtrips()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Null(handler.ServerCertificateCustomValidationCallback);
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> callback1 = (req, cert, chain, policy) => throw new NotImplementedException("callback1");
Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> callback2 = (req, cert, chain, policy) => throw new NotImplementedException("callback2");
handler.ServerCertificateCustomValidationCallback = callback1;
Assert.Same(callback1, handler.ServerCertificateCustomValidationCallback);
handler.ServerCertificateCustomValidationCallback = callback2;
Assert.Same(callback2, handler.ServerCertificateCustomValidationCallback);
handler.ServerCertificateCustomValidationCallback = null;
Assert.Null(handler.ServerCertificateCustomValidationCallback);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_ValidCertificate_SuccessAndExpectedPropertyBehavior()
{
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.SecureRemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.Throws<InvalidOperationException>(() => handler.ServerCertificateCustomValidationCallback = null);
Assert.Throws<InvalidOperationException>(() => handler.CheckCertificateRevocationList = false);
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP won't send requests through a custom proxy")]
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_HaveNoCredsAndUseAuthenticatedCustomProxyAndPostToSecureServer_ProxyAuthenticationRequiredStatusCode()
{
if (!BackendSupportsCustomCertificateHandling)
{
return;
}
if (UseSocketsHttpHandler)
{
return; // TODO #23136: SSL proxy tunneling not yet implemented in SocketsHttpHandler
}
int port;
Task<LoopbackGetRequestHttpProxy.ProxyResult> proxyTask = LoopbackGetRequestHttpProxy.StartAsync(
out port,
requireAuth: true,
expectCreds: false);
Uri proxyUrl = new Uri($"http://localhost:{port}");
HttpClientHandler handler = CreateHttpClientHandler();
handler.Proxy = new UseSpecifiedUriWebProxy(proxyUrl, null);
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
Task<HttpResponseMessage> responseTask = client.PostAsync(
Configuration.Http.SecureRemoteEchoServer,
new StringContent("This is a test"));
await TestHelper.WhenAllCompletedOrAnyFailed(proxyTask, responseTask);
using (responseTask.Result)
{
Assert.Equal(HttpStatusCode.ProxyAuthenticationRequired, responseTask.Result.StatusCode);
}
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_NotSecureConnection_CallbackNotCalled()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_NotSecureConnection_CallbackNotCalled)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = delegate { callbackCalled = true; return true; };
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RemoteEchoServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.False(callbackCalled);
}
}
public static IEnumerable<object[]> UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls()
{
foreach (bool checkRevocation in new[] { true, false })
{
yield return new object[] { Configuration.Http.SecureRemoteEchoServer, checkRevocation };
yield return new object[] {
Configuration.Http.RedirectUriForDestinationUri(
secure:true,
statusCode:302,
destinationUri:Configuration.Http.SecureRemoteEchoServer,
hops:1),
checkRevocation };
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback_Urls))]
public async Task UseCallback_ValidCertificate_ExpectedValuesDuringCallback(Uri url, bool checkRevocation)
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_ValidCertificate_ExpectedValuesDuringCallback)}({url}, {checkRevocation})");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.CheckCertificateRevocationList = checkRevocation;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) => {
callbackCalled = true;
Assert.NotNull(request);
X509ChainStatusFlags flags = chain.ChainStatus.Aggregate(X509ChainStatusFlags.NoError, (cur, status) => cur | status.Status);
bool ignoreErrors = // https://github.com/dotnet/corefx/issues/21922#issuecomment-315555237
RuntimeInformation.IsOSPlatform(OSPlatform.OSX) &&
checkRevocation &&
errors == SslPolicyErrors.RemoteCertificateChainErrors &&
flags == X509ChainStatusFlags.RevocationStatusUnknown;
Assert.True(ignoreErrors || errors == SslPolicyErrors.None, $"Expected {SslPolicyErrors.None}, got {errors} with chain status {flags}");
Assert.True(chain.ChainElements.Count > 0);
Assert.NotEmpty(cert.Subject);
// UWP always uses CheckCertificateRevocationList=true regardless of setting the property and
// the getter always returns true. So, for this next Assert, it is better to get the property
// value back from the handler instead of using the parameter value of the test.
Assert.Equal(
handler.CheckCertificateRevocationList ? X509RevocationMode.Online : X509RevocationMode.NoCheck,
chain.ChainPolicy.RevocationMode);
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_CallbackReturnsFailure_ThrowsException()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackReturnsFailure_ThrowsException)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return false; };
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_CallbackThrowsException_ExceptionPropagatesAsBaseException)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
using (var client = new HttpClient(handler))
{
var e = new DivideByZeroException();
handler.ServerCertificateCustomValidationCallback = delegate { throw e; };
HttpRequestException ex = await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
Assert.Same(e, ex.GetBaseException());
}
}
public static readonly object[][] CertificateValidationServers =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer },
new object[] { Configuration.Http.SelfSignedCertRemoteServer },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer },
};
[OuterLoop] // TODO: Issue #11345
[ConditionalTheory(nameof(ClientSupportsDHECipherSuites))]
[MemberData(nameof(CertificateValidationServers))]
public async Task NoCallback_BadCertificate_ThrowsException(string url)
{
using (HttpClient client = CreateHttpClient())
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(url));
}
}
[SkipOnTargetFramework(TargetFrameworkMonikers.Uap, "UAP doesn't allow revocation checking to be turned off")]
[OuterLoop] // TODO: Issue #11345
[ConditionalFact(nameof(ClientSupportsDHECipherSuites))]
public async Task NoCallback_RevokedCertificate_NoRevocationChecking_Succeeds()
{
// On macOS (libcurl+darwinssl) we cannot turn revocation off.
// But we also can't realistically say that the default value for
// CheckCertificateRevocationList throws in the general case.
try
{
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.GetAsync(Configuration.Http.RevokedCertRemoteServer))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
catch (HttpRequestException)
{
if (UseSocketsHttpHandler || !ShouldSuppressRevocationException)
throw;
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task NoCallback_RevokedCertificate_RevocationChecking_Fails()
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(NoCallback_RevokedCertificate_RevocationChecking_Fails)}()");
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.CheckCertificateRevocationList = true;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<HttpRequestException>(() => client.GetAsync(Configuration.Http.RevokedCertRemoteServer));
}
}
public static readonly object[][] CertificateValidationServersAndExpectedPolicies =
{
new object[] { Configuration.Http.ExpiredCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.SelfSignedCertRemoteServer, SslPolicyErrors.RemoteCertificateChainErrors },
new object[] { Configuration.Http.WrongHostNameCertRemoteServer , SslPolicyErrors.RemoteCertificateNameMismatch},
};
private async Task UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(string url, bool useSocketsHttpHandler, SslPolicyErrors expectedErrors)
{
if (!BackendSupportsCustomCertificateHandling)
{
Console.WriteLine($"Skipping {nameof(UseCallback_BadCertificate_ExpectedPolicyErrors)}({url}, {expectedErrors})");
return;
}
HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandler);
using (var client = new HttpClient(handler))
{
bool callbackCalled = false;
handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
{
callbackCalled = true;
Assert.NotNull(request);
Assert.NotNull(cert);
Assert.NotNull(chain);
if (!useSocketsHttpHandler)
{
// TODO #23137: This test is failing with SocketsHttpHandler on the exact value of the managed errors,
// e.g. reporting "RemoteCertificateNameMismatch, RemoteCertificateChainErrors" when we only expect
// "RemoteCertificateChainErrors"
Assert.Equal(expectedErrors, errors);
}
return true;
};
using (HttpResponseMessage response = await client.GetAsync(url))
{
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
Assert.True(callbackCalled);
}
}
[OuterLoop] // TODO: Issue #11345
[Theory]
[MemberData(nameof(CertificateValidationServersAndExpectedPolicies))]
public async Task UseCallback_BadCertificate_ExpectedPolicyErrors(string url, SslPolicyErrors expectedErrors)
{
const int SEC_E_BUFFER_TOO_SMALL = unchecked((int)0x80090321);
if (!BackendSupportsCustomCertificateHandlingAndClientSupportsDHECipherSuites)
{
return;
}
try
{
if (PlatformDetection.IsUap)
{
// UAP HTTP stack caches connections per-process. This causes interference when these tests run in
// the same process as the other tests. Each test needs to be isolated to its own process.
// See dicussion: https://github.com/dotnet/corefx/issues/21945
RemoteInvoke((remoteUrl, remoteExpectedErrors, useSocketsHttpHandlerString) =>
{
UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(
remoteUrl,
bool.Parse(useSocketsHttpHandlerString),
(SslPolicyErrors)Enum.Parse(typeof(SslPolicyErrors), remoteExpectedErrors)).Wait();
return SuccessExitCode;
}, url, expectedErrors.ToString(), UseSocketsHttpHandler.ToString()).Dispose();
}
else
{
await UseCallback_BadCertificate_ExpectedPolicyErrors_Helper(url, UseSocketsHttpHandler, expectedErrors);
}
}
catch (HttpRequestException e) when (e.InnerException?.GetType().Name == "WinHttpException" &&
e.InnerException.HResult == SEC_E_BUFFER_TOO_SMALL &&
!PlatformDetection.IsWindows10Version1607OrGreater)
{
// Testing on old Windows versions can hit https://github.com/dotnet/corefx/issues/7812
// Ignore SEC_E_BUFFER_TOO_SMALL error on such cases.
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
public async Task SSLBackendNotSupported_Callback_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling)
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[Fact]
// For macOS the "custom handling" means that revocation can't be *disabled*. So this test does not apply.
[PlatformSpecific(~TestPlatforms.OSX)]
public async Task SSLBackendNotSupported_Revocation_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling)
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.CheckCertificateRevocationList = true;
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop] // TODO: Issue #11345
[PlatformSpecific(TestPlatforms.Windows)] // CopyToAsync(Stream, TransportContext) isn't used on unix
[Fact]
public async Task PostAsync_Post_ChannelBinding_ConfiguredCorrectly()
{
var content = new ChannelBindingAwareContent("Test contest");
using (HttpClient client = CreateHttpClient())
using (HttpResponseMessage response = await client.PostAsync(Configuration.Http.SecureRemoteEchoServer, content))
{
// Validate status.
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
// Validate the ChannelBinding object exists.
ChannelBinding channelBinding = content.ChannelBinding;
if (PlatformDetection.IsUap)
{
// UAP currently doesn't expose channel binding information.
Assert.Null(channelBinding);
}
else
{
Assert.NotNull(channelBinding);
// Validate the ChannelBinding's validity.
if (BackendSupportsCustomCertificateHandling)
{
Assert.False(channelBinding.IsInvalid, "Expected valid binding");
Assert.NotEqual(IntPtr.Zero, channelBinding.DangerousGetHandle());
// Validate the ChannelBinding's description.
string channelBindingDescription = channelBinding.ToString();
Assert.NotNull(channelBindingDescription);
Assert.NotEmpty(channelBindingDescription);
Assert.True((channelBindingDescription.Length + 1) % 3 == 0, $"Unexpected length {channelBindingDescription.Length}");
for (int i = 0; i < channelBindingDescription.Length; i++)
{
char c = channelBindingDescription[i];
if (i % 3 == 2)
{
Assert.Equal(' ', c);
}
else
{
Assert.True((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F'), $"Expected hex, got {c}");
}
}
}
else
{
// Backend doesn't support getting the details to create the CBT.
Assert.True(channelBinding.IsInvalid, "Expected invalid binding");
Assert.Equal(IntPtr.Zero, channelBinding.DangerousGetHandle());
Assert.Null(channelBinding.ToString());
}
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.VisualStudio.Services.Agent.Util;
using Microsoft.VisualStudio.Services.Agent.Worker;
using Microsoft.VisualStudio.Services.Agent.Worker.Build;
using Moq;
using Xunit;
namespace Microsoft.VisualStudio.Services.Agent.Tests.Worker.Build
{
public sealed class TfsVCSourceProvider_WorkspaceUtilL0
{
private TfsVCSourceProvider.DefinitionWorkspaceMapping[] _definitionMappings;
private Mock<IExecutionContext> _executionContext;
private string _sourceFile;
private string _sourcesDirectory;
private Tracing _trace;
private string _workspaceName;
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_Cloak_ServerPath()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
MappingType = TfsVCSourceProvider.DefinitionMappingType.Cloak,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).ServerPath = "$/otherProj";
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_ComputerName()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory,
computer: "NON_MATCHING_COMPUTER_NAME");
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_Map_LocalPath()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "myProj",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).LocalPath = Path.Combine(_sourcesDirectory, "otherProj");
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_Map_Recursive()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).Recursive = false;
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_Map_ServerPath()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).ServerPath = "$/otherProj";
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_Map_SingleLevel()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj/*",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).Recursive = true;
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_MappingType()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
(tfWorkspace.Mappings[0] as MockTfsVCMapping).Cloak = true;
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void DoesNotMatch_WorkspaceName()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
};
var tfWorkspace = new MockTfsVCWorkspace(
name: "NON_MATCHING_WORKSPACE_NAME",
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { tfWorkspace },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Null(actual);
}
finally
{
Cleanup();
}
}
}
[Fact]
[Trait("Level", "L0")]
[Trait("Category", "Worker")]
public void Matches()
{
using (TestHostContext tc = new TestHostContext(this))
{
try
{
// Arrange.
Prepare(tc);
var expected = new MockTfsVCWorkspace(
name: _workspaceName,
mappings: _definitionMappings,
localRoot: _sourcesDirectory);
// Act.
ITfsVCWorkspace actual = TfsVCSourceProvider.WorkspaceUtil.MatchExactWorkspace(
executionContext: _executionContext.Object,
tfWorkspaces: new[] { expected },
name: _workspaceName,
definitionMappings: _definitionMappings,
sourcesDirectory: _sourcesDirectory);
// Assert.
Assert.Equal(expected, actual);
}
finally
{
Cleanup();
}
}
}
private void Cleanup()
{
if (!string.IsNullOrEmpty(_sourcesDirectory))
{
Directory.Delete(_sourcesDirectory, recursive: true);
}
}
private void Prepare(TestHostContext hostContext)
{
_trace = hostContext.GetTrace();
// Prepare the sources directory. The workspace helper will not return any
// matches if the sources directory does not exist with something in it.
_sourcesDirectory = Path.Combine(hostContext.GetDirectory(WellKnownDirectory.Bin), Path.GetRandomFileName());
_sourceFile = Path.Combine(_sourcesDirectory, "some file");
Directory.CreateDirectory(_sourcesDirectory);
File.WriteAllText(path: _sourceFile, contents: "some contents");
// Prepare a basic definition workspace.
_workspaceName = "ws_1_1";
_definitionMappings = new[]
{
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/*",
},
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "myProj",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/myProj",
},
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "myProj/Drops",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Cloak,
ServerPath = "$/myProj/Drops",
},
new TfsVCSourceProvider.DefinitionWorkspaceMapping
{
LocalPath = "otherProj/mydir",
MappingType = TfsVCSourceProvider.DefinitionMappingType.Map,
ServerPath = "$/otherProj/mydir/*",
},
};
_executionContext = new Mock<IExecutionContext>();
_executionContext
.Setup(x => x.WriteDebug)
.Returns(true);
_executionContext
.Setup(x => x.Write(It.IsAny<string>(), It.IsAny<string>()))
.Callback((string tag, string message) => _trace.Info($"[ExecutionContext]{tag} {message}"));
}
public sealed class MockTfsVCWorkspace : ITfsVCWorkspace
{
public MockTfsVCWorkspace(
string name,
TfsVCSourceProvider.DefinitionWorkspaceMapping[] mappings = null,
string localRoot = null,
string computer = null)
{
ArgUtil.NotNullOrEmpty(name, nameof(name));
Computer = computer != null ? computer : Environment.MachineName;
Mappings = (mappings ?? new TfsVCSourceProvider.DefinitionWorkspaceMapping[0])
.Select(x => new MockTfsVCMapping(x, localRoot))
.ToArray();
Name = name;
}
public string Computer { get; set; }
public string Name { get; set; }
public string Owner { get; set; }
public ITfsVCMapping[] Mappings { get; set; }
}
public sealed class MockTfsVCMapping : ITfsVCMapping
{
public MockTfsVCMapping(TfsVCSourceProvider.DefinitionWorkspaceMapping mapping, string localRoot)
{
ArgUtil.NotNull(mapping, nameof(mapping));
ArgUtil.NotNull(localRoot, nameof(localRoot));
Cloak = mapping.MappingType == TfsVCSourceProvider.DefinitionMappingType.Cloak;
LocalPath = mapping.GetRootedLocalPath(localRoot);
Recursive = mapping.Recursive;
ServerPath = mapping.NormalizedServerPath;
}
public bool Cloak { get; set; }
public string LocalPath { get; set; }
public bool Recursive { get; set; }
public string ServerPath { get; set; }
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Reflection;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.Messages.Linden;
using OpenMetaverse.StructuredData;
using Aurora.Framework;
using Aurora.Framework.Capabilities;
using Aurora.Framework.Servers.HttpServer;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using ExtraParamType = OpenMetaverse.ExtraParamType;
namespace Aurora.Modules.Caps
{
public class UploadObjectAssetModule : INonSharedRegionModule
{
private IScene m_scene;
#region INonSharedRegionModule Members
public Type ReplaceableInterface
{
get { return null; }
}
public void Initialise(IConfigSource source)
{
}
public void AddRegion(IScene pScene)
{
m_scene = pScene;
}
public void RemoveRegion(IScene scene)
{
m_scene.EventManager.OnRegisterCaps -= RegisterCaps;
m_scene = null;
}
public void RegionLoaded(IScene scene)
{
m_scene.EventManager.OnRegisterCaps += RegisterCaps;
}
public void Close()
{
}
public string Name
{
get { return "UploadObjectAssetModuleModule"; }
}
#endregion
public OSDMap RegisterCaps(UUID agentID, IHttpServer server)
{
OSDMap retVal = new OSDMap();
retVal["UploadObjectAsset"] = CapsUtil.CreateCAPS("UploadObjectAsset", "");
#if (!ISWIN)
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["UploadObjectAsset"],
delegate(Hashtable m_dhttpMethod)
{
return ProcessAdd(m_dhttpMethod, agentID);
}));
#else
server.AddStreamHandler(new RestHTTPHandler("POST", retVal["UploadObjectAsset"],
m_dhttpMethod => ProcessAdd(m_dhttpMethod, agentID)));
#endif
return retVal;
}
/// <summary>
/// Parses ad request
/// </summary>
/// <param name = "request"></param>
/// <param name = "AgentId"></param>
/// <param name = "cap"></param>
/// <returns></returns>
public Hashtable ProcessAdd(Hashtable request, UUID AgentId)
{
Hashtable responsedata = new Hashtable();
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = "Request wasn't what was expected";
IScenePresence avatar;
if (!m_scene.TryGetScenePresence(AgentId, out avatar))
return responsedata;
OSDMap r = (OSDMap) OSDParser.Deserialize((string) request["requestbody"]);
UploadObjectAssetMessage message = new UploadObjectAssetMessage();
try
{
message.Deserialize(r);
}
catch (Exception ex)
{
MainConsole.Instance.Error("[UploadObjectAssetModule]: Error deserializing message " + ex);
message = null;
}
if (message == null)
{
responsedata["int_response_code"] = 400; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] =
"<llsd><map><key>error</key><string>Error parsing Object</string></map></llsd>";
return responsedata;
}
Vector3 pos = avatar.AbsolutePosition + (Vector3.UnitX*avatar.Rotation);
Quaternion rot = Quaternion.Identity;
Vector3 rootpos = Vector3.Zero;
SceneObjectGroup rootGroup = null;
SceneObjectGroup[] allparts = new SceneObjectGroup[message.Objects.Length];
for (int i = 0; i < message.Objects.Length; i++)
{
UploadObjectAssetMessage.Object obj = message.Objects[i];
PrimitiveBaseShape pbs = PrimitiveBaseShape.CreateBox();
if (i == 0)
{
rootpos = obj.Position;
}
// Combine the extraparams data into it's ugly blob again....
//int bytelength = 0;
//for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
//{
// bytelength += obj.ExtraParams[extparams].ExtraParamData.Length;
//}
//byte[] extraparams = new byte[bytelength];
//int position = 0;
//for (int extparams = 0; extparams < obj.ExtraParams.Length; extparams++)
//{
// Buffer.BlockCopy(obj.ExtraParams[extparams].ExtraParamData, 0, extraparams, position,
// obj.ExtraParams[extparams].ExtraParamData.Length);
//
// position += obj.ExtraParams[extparams].ExtraParamData.Length;
// }
//pbs.ExtraParams = extraparams;
foreach (UploadObjectAssetMessage.Object.ExtraParam extraParam in obj.ExtraParams)
{
switch ((ushort) extraParam.Type)
{
case (ushort) ExtraParamType.Sculpt:
Primitive.SculptData sculpt = new Primitive.SculptData(extraParam.ExtraParamData, 0);
pbs.SculptEntry = true;
pbs.SculptTexture = obj.SculptID;
pbs.SculptType = (byte) sculpt.Type;
break;
case (ushort) ExtraParamType.Flexible:
Primitive.FlexibleData flex = new Primitive.FlexibleData(extraParam.ExtraParamData, 0);
pbs.FlexiEntry = true;
pbs.FlexiDrag = flex.Drag;
pbs.FlexiForceX = flex.Force.X;
pbs.FlexiForceY = flex.Force.Y;
pbs.FlexiForceZ = flex.Force.Z;
pbs.FlexiGravity = flex.Gravity;
pbs.FlexiSoftness = flex.Softness;
pbs.FlexiTension = flex.Tension;
pbs.FlexiWind = flex.Wind;
break;
case (ushort) ExtraParamType.Light:
Primitive.LightData light = new Primitive.LightData(extraParam.ExtraParamData, 0);
pbs.LightColorA = light.Color.A;
pbs.LightColorB = light.Color.B;
pbs.LightColorG = light.Color.G;
pbs.LightColorR = light.Color.R;
pbs.LightCutoff = light.Cutoff;
pbs.LightEntry = true;
pbs.LightFalloff = light.Falloff;
pbs.LightIntensity = light.Intensity;
pbs.LightRadius = light.Radius;
break;
case 0x40:
pbs.ReadProjectionData(extraParam.ExtraParamData, 0);
break;
}
}
pbs.PathBegin = (ushort) obj.PathBegin;
pbs.PathCurve = (byte) obj.PathCurve;
pbs.PathEnd = (ushort) obj.PathEnd;
pbs.PathRadiusOffset = (sbyte) obj.RadiusOffset;
pbs.PathRevolutions = (byte) obj.Revolutions;
pbs.PathScaleX = (byte) obj.ScaleX;
pbs.PathScaleY = (byte) obj.ScaleY;
pbs.PathShearX = (byte) obj.ShearX;
pbs.PathShearY = (byte) obj.ShearY;
pbs.PathSkew = (sbyte) obj.Skew;
pbs.PathTaperX = (sbyte) obj.TaperX;
pbs.PathTaperY = (sbyte) obj.TaperY;
pbs.PathTwist = (sbyte) obj.Twist;
pbs.PathTwistBegin = (sbyte) obj.TwistBegin;
pbs.HollowShape = (HollowShape) obj.ProfileHollow;
pbs.PCode = (byte) PCode.Prim;
pbs.ProfileBegin = (ushort) obj.ProfileBegin;
pbs.ProfileCurve = (byte) obj.ProfileCurve;
pbs.ProfileEnd = (ushort) obj.ProfileEnd;
pbs.Scale = obj.Scale;
pbs.State = 0;
SceneObjectPart prim = new SceneObjectPart(AgentId, pbs, obj.Position, obj.Rotation,
Vector3.Zero, obj.Name, m_scene)
{
UUID = UUID.Random(),
CreatorID = AgentId,
OwnerID = AgentId,
GroupID = obj.GroupID
};
prim.LastOwnerID = prim.OwnerID;
prim.CreationDate = Util.UnixTimeSinceEpoch();
prim.Name = obj.Name;
prim.Description = "";
prim.PayPrice[0] = -2;
prim.PayPrice[1] = -2;
prim.PayPrice[2] = -2;
prim.PayPrice[3] = -2;
prim.PayPrice[4] = -2;
Primitive.TextureEntry tmp =
new Primitive.TextureEntry(UUID.Parse("89556747-24cb-43ed-920b-47caed15465f"));
for (int j = 0; j < obj.Faces.Length; j++)
{
UploadObjectAssetMessage.Object.Face face = obj.Faces[j];
Primitive.TextureEntryFace primFace = tmp.CreateFace((uint) j);
primFace.Bump = face.Bump;
primFace.RGBA = face.Color;
primFace.Fullbright = face.Fullbright;
primFace.Glow = face.Glow;
primFace.TextureID = face.ImageID;
primFace.Rotation = face.ImageRot;
primFace.MediaFlags = ((face.MediaFlags & 1) != 0);
primFace.OffsetU = face.OffsetS;
primFace.OffsetV = face.OffsetT;
primFace.RepeatU = face.ScaleS;
primFace.RepeatV = face.ScaleT;
primFace.TexMapType = (MappingType) (face.MediaFlags & 6);
}
pbs.TextureEntry = tmp.GetBytes();
prim.Shape = pbs;
prim.Scale = obj.Scale;
SceneObjectGroup grp = new SceneObjectGroup(prim, m_scene);
prim.ParentID = 0;
if (i == 0)
rootGroup = grp;
grp.AbsolutePosition = obj.Position;
prim.RotationOffset = obj.Rotation;
grp.RootPart.IsAttachment = false;
string reason;
if (m_scene.Permissions.CanRezObject(1, avatar.UUID, pos, out reason))
{
m_scene.SceneGraph.AddPrimToScene(grp);
grp.AbsolutePosition = obj.Position;
}
else
{
//Stop now then
avatar.ControllingClient.SendAlertMessage("You do not have permission to rez objects here: " +
reason);
return responsedata;
}
allparts[i] = grp;
}
for (int j = 1; j < allparts.Length; j++)
{
rootGroup.LinkToGroup(allparts[j]);
}
rootGroup.ScheduleGroupUpdate(PrimUpdateFlags.ForcedFullUpdate);
pos = m_scene.SceneGraph.GetNewRezLocation(Vector3.Zero, rootpos, UUID.Zero, rot, 1, 1, true,
allparts[0].GroupScale(), false);
responsedata["int_response_code"] = 200; //501; //410; //404;
responsedata["content_type"] = "text/plain";
responsedata["keepalive"] = false;
responsedata["str_response_string"] = String.Format("<llsd><map><key>local_id</key>{0}</map></llsd>",
ConvertUintToBytes(allparts[0].LocalId));
return responsedata;
}
private string ConvertUintToBytes(uint val)
{
byte[] resultbytes = Utils.UIntToBytes(val);
if (BitConverter.IsLittleEndian)
Array.Reverse(resultbytes);
return String.Format("<binary encoding=\"base64\">{0}</binary>", Convert.ToBase64String(resultbytes));
}
}
}
| |
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 Proxy.InfoPath
{
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.
using System.Linq;
using System.Numerics;
using System.Collections.Generic;
namespace System.Buffers.Text.Tests
{
internal static partial class TestData
{
public static IEnumerable<ParserTestData<sbyte>> SByteParserTestData
{
get
{
foreach (ParserTestData<sbyte> testData in SByteFormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<sbyte> testData in GeneralIntegerParserTestData<sbyte>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<sbyte>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<sbyte>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<sbyte>("5ff", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<byte>> ByteParserTestData
{
get
{
foreach (ParserTestData<byte> testData in ByteFormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<byte> testData in GeneralIntegerParserTestData<byte>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<byte>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<byte>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<byte>("5ff", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<short>> Int16ParserTestData
{
get
{
foreach (ParserTestData<short> testData in Int16FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<short> testData in GeneralIntegerParserTestData<short>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<short>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<short>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<short>("5faaf", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<ushort>> UInt16ParserTestData
{
get
{
foreach (ParserTestData<ushort> testData in UInt16FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<ushort> testData in GeneralIntegerParserTestData<ushort>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<ushort>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<ushort>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<ushort>("5faaf", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<int>> Int32ParserTestData
{
get
{
foreach (ParserTestData<int> testData in Int32FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<int> testData in GeneralIntegerParserTestData<int>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<int>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<int>("5faaccbbf", 0, 'x', expectedSuccess: false);
// This value will overflow a UInt32 accumulator upon assimilating the 0 in a way such that the wrapped-around value still looks like
// it's in the range of an Int32. Unless, of course, the implementation had the foresight to check before assimilating.
yield return new ParserTestData<int>("9999999990", 0, 'D', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<uint>> UInt32ParserTestData
{
get
{
foreach (ParserTestData<uint> testData in UInt32FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<uint> testData in GeneralIntegerParserTestData<uint>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<uint>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<uint>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<uint>("5faaccbbf", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<long>> Int64ParserTestData
{
get
{
foreach (ParserTestData<long> testData in Int64FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<long> testData in GeneralIntegerParserTestData<long>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<long>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<long>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<long>("5faaccbb11223344f", 0, 'x', expectedSuccess: false);
}
}
public static IEnumerable<ParserTestData<ulong>> UInt64ParserTestData
{
get
{
foreach (ParserTestData<ulong> testData in UInt64FormatterTestData.ToParserTheoryDataCollection())
{
yield return testData;
}
foreach (ParserTestData<ulong> testData in GeneralIntegerParserTestData<ulong>())
{
yield return testData;
}
// Code coverage
yield return new ParserTestData<ulong>("5$", 5, 'D', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<ulong>("5$", 5, 'x', expectedSuccess: true) { ExpectedBytesConsumed = 1 };
yield return new ParserTestData<ulong>("5faaccbb11223344f", 0, 'x', expectedSuccess: false);
}
}
private static IEnumerable<ParserTestData<T>> GeneralIntegerParserTestData<T>()
{
string[] GeneralIntegerNegativeInputs =
{
string.Empty,
"-",
"+",
"--5",
"++5",
};
BigInteger minValue = TestUtils.GetMinValue<T>();
BigInteger maxValue = TestUtils.GetMaxValue<T>();
bool isSigned = !minValue.IsZero;
foreach (SupportedFormat format in IntegerFormats.Where(f => f.IsParsingImplemented<T>() && f.ParseSynonymFor == default))
{
foreach (string integerNegativeInput in GeneralIntegerNegativeInputs)
{
yield return new ParserTestData<T>(integerNegativeInput, default, format.Symbol, expectedSuccess: false);
}
// The hex format always parses as an unsigned number. That violates the assumptions made by this next set of test data.
// Since the parser uses the same code for hex-parsing signed and unsigned, just generate the data for the unsigned types only with
// no loss in code coverage.
if (!((format.Symbol == 'X' || format.Symbol == 'x') && isSigned))
{
// Make sure that MaxValue and values just below it parse successfully.
for (int offset = -20; offset <= 0; offset++)
{
BigInteger bigValue = maxValue + offset;
string textD = bigValue.ToString("D");
string text = bigValue.ToString(format.Symbol.ToString());
T expectedValue = (T)(Convert.ChangeType(textD, typeof(T)));
yield return new ParserTestData<T>(text, expectedValue, format.Symbol, expectedSuccess: true);
}
// Make sure that values just above MaxValue don't parse successfully.
for (int offset = 1; offset <= 20; offset++)
{
BigInteger bigValue = maxValue + offset;
string text = bigValue.ToString(format.Symbol.ToString());
yield return new ParserTestData<T>(text, default, format.Symbol, expectedSuccess: false);
}
{
BigInteger bigValue = maxValue * 10;
string text = bigValue.ToString(format.Symbol.ToString());
yield return new ParserTestData<T>(text, default, format.Symbol, expectedSuccess: false);
}
if (isSigned) // No such thing as an underflow for unsigned integer parsing...
{
// Make sure that MinValue and values just above it parse successfully.
for (int offset = 0; offset <= 20; offset++)
{
BigInteger bigValue = minValue + offset;
string textD = bigValue.ToString("D");
string text = bigValue.ToString(format.Symbol.ToString());
T expectedValue = (T)(Convert.ChangeType(textD, typeof(T)));
yield return new ParserTestData<T>(text, expectedValue, format.Symbol, expectedSuccess: true);
}
// Make sure that values just below MinValue don't parse successfully.
for (int offset = -20; offset <= -1; offset++)
{
BigInteger bigValue = minValue + offset;
string text = bigValue.ToString(format.Symbol.ToString());
yield return new ParserTestData<T>(text, default, format.Symbol, expectedSuccess: false);
}
{
BigInteger bigValue = minValue * 10;
string text = bigValue.ToString(format.Symbol.ToString());
yield return new ParserTestData<T>(text, default, format.Symbol, expectedSuccess: false);
}
}
}
if (format.Symbol == 'N' || format.Symbol == 'n')
{
// "N" format parsing
foreach (ParserTestData<T> testData in TestDataForNFormat.ConvertTestDataForNFormat<T>())
{
yield return testData;
}
}
}
}
// Test data specific to the "N" format. This set is up-converted and reused for all the integer types.
// Non-N-specific issues like overflow and underflow detection are already covered by GeneralIntegerParserTestData().
private static IEnumerable<ParserTestData<sbyte>> TestDataForNFormat
{
get
{
yield return new ParserTestData<sbyte>("12,3", 123, 'N', expectedSuccess: true);
yield return new ParserTestData<sbyte>("1,0,4", 104, 'N', expectedSuccess: true);
yield return new ParserTestData<sbyte>("1,,23", 123, 'N', expectedSuccess: true); // Comma placement is completely flexible.
yield return new ParserTestData<sbyte>("+1,,23", 123, 'N', expectedSuccess: true); // Comma placement is completely flexible.
yield return new ParserTestData<sbyte>("-1,,23", -123, 'N', expectedSuccess: true); // Comma placement is completely flexible.
yield return new ParserTestData<sbyte>(",234", default, 'N', expectedSuccess: false); // Leading comma not allowed.
yield return new ParserTestData<sbyte>("+,234", default, 'N', expectedSuccess: false); // Leading comma not allowed.
yield return new ParserTestData<sbyte>("-,234", default, 'N', expectedSuccess: false); // Leading comma not allowed.
yield return new ParserTestData<sbyte>("104,", 104, 'N', expectedSuccess: true); // Trailing comma is allowed.
yield return new ParserTestData<sbyte>("104,,", 104, 'N', expectedSuccess: true); // Trailing comma is allowed.
yield return new ParserTestData<sbyte>("104,.00", 104, 'N', expectedSuccess: true); // Trailing comma is allowed.
yield return new ParserTestData<sbyte>(".", default, 'N', expectedSuccess: false); // Standalone period not allowed.
yield return new ParserTestData<sbyte>(".0", 0, 'N', expectedSuccess: true); // But missing digits on either side allowed (as long as not both)
yield return new ParserTestData<sbyte>("5.", 5, 'N', expectedSuccess: true); // But missing digits on either side allowed (as long as not both)
yield return new ParserTestData<sbyte>("+", default, 'N', expectedSuccess: false); // Standalone sign symbol not allowed
yield return new ParserTestData<sbyte>("-", default, 'N', expectedSuccess: false); // Standalone sign symbol not allowed
yield return new ParserTestData<sbyte>("2.000000000000000000000000000000000", 2, 'N', expectedSuccess: true); // Decimal portion allowed as long as its 0.
yield return new ParserTestData<sbyte>("2.000000000000000000000000000000001", default, 'N', expectedSuccess: false);
yield return new ParserTestData<sbyte>(".1", default, 'N', expectedSuccess: false);
yield return new ParserTestData<sbyte>("2.0,0", 2, 'N', expectedSuccess: true) { ExpectedBytesConsumed = 3 }; // Commas must appear before the decimal point, not after.
}
}
private static IEnumerable<ParserTestData<T>> ConvertTestDataForNFormat<T>(this IEnumerable<ParserTestData<sbyte>> testData) => testData.Select(td => td.ConvertTestDataForNFormat<T>());
private static ParserTestData<T> ConvertTestDataForNFormat<T>(this ParserTestData<sbyte> testData)
{
Type t = typeof(T);
bool isSignedType = t == typeof(sbyte) || t == typeof(short) || t == typeof(int) || t == typeof(long);
if (testData.ExpectedValue < 0 && !isSignedType)
return new ParserTestData<T>(testData.Text, default, testData.FormatSymbol, expectedSuccess: false); // Unsigned parsers will never produce negative values.
T convertedValue;
if (t == typeof(sbyte))
convertedValue = (T)(object)testData.ExpectedValue;
else if (t == typeof(byte))
convertedValue = (T)(object)Convert.ToByte(testData.ExpectedValue);
else if (t == typeof(short))
convertedValue = (T)(object)Convert.ToInt16(testData.ExpectedValue);
else if (t == typeof(ushort))
convertedValue = (T)(object)Convert.ToUInt16(testData.ExpectedValue);
else if (t == typeof(int))
convertedValue = (T)(object)Convert.ToInt32(testData.ExpectedValue);
else if (t == typeof(uint))
convertedValue = (T)(object)Convert.ToUInt32(testData.ExpectedValue);
else if (t == typeof(long))
convertedValue = (T)(object)Convert.ToInt64(testData.ExpectedValue);
else if (t == typeof(ulong))
convertedValue = (T)(object)Convert.ToUInt64(testData.ExpectedValue);
else
throw new Exception("Not an integer type: " + t);
return new ParserTestData<T>(testData.Text, convertedValue, testData.FormatSymbol, testData.ExpectedSuccess) { ExpectedBytesConsumed = testData.ExpectedBytesConsumed };
}
}
}
| |
// 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.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
namespace System.Runtime.InteropServices.WindowsRuntime
{
// An event registration token table stores mappings from delegates to event tokens, in order to support
// sourcing WinRT style events from managed code.
public sealed class EventRegistrationTokenTable<T> where T : class
{
// Note this dictionary is also used as the synchronization object for this table
private System.Collections.Generic.Dictionary<EventRegistrationToken, T> m_tokens = new System.Collections.Generic.Dictionary<EventRegistrationToken, T>();
// Cached multicast delegate which will invoke all of the currently registered delegates. This
// will be accessed frequently in common coding paterns, so we don't want to calculate it repeatedly.
private volatile T m_invokeList;
public EventRegistrationTokenTable()
{
// T must be a delegate type, but we cannot constrain on being a delegate. Therefore, we'll do a
// static check at construction time
/*
if (!typeof(Delegate).IsAssignableFrom(typeof(T)))
{
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_EventTokenTableRequiresDelegate", typeof(T)));
}
*/
}
// The InvocationList property provides access to a delegate which will invoke every registered event handler
// in this table. If the property is set, the new value will replace any existing token registrations.
public T InvocationList
{
get
{
return m_invokeList;
}
set
{
lock (m_tokens)
{
// The value being set replaces any of the existing values
m_tokens.Clear();
m_invokeList = null;
if (value != null)
{
AddEventHandlerNoLock(value);
}
}
}
}
public EventRegistrationToken AddEventHandler(T handler)
{
// Windows Runtime allows null handlers. Assign those a token value of 0 for easy identity
if (handler == null)
{
return new EventRegistrationToken(0);
}
lock (m_tokens)
{
return AddEventHandlerNoLock(handler);
}
}
private EventRegistrationToken AddEventHandlerNoLock(T handler)
{
Debug.Assert(handler != null);
// Get a registration token, making sure that we haven't already used the value. This should be quite
// rare, but in the case it does happen, just keep trying until we find one that's unused.
EventRegistrationToken token = GetPreferredToken(handler);
while (m_tokens.ContainsKey(token))
{
token = new EventRegistrationToken(token.Value + 1);
}
m_tokens[token] = handler;
// Update the current invocation list to include the newly added delegate
Delegate invokeList = (Delegate)(object)m_invokeList;
invokeList = MulticastDelegate.Combine(invokeList, (Delegate)(object)handler);
m_invokeList = (T)(object)invokeList;
return token;
}
// Get the delegate associated with an event registration token if it exists. Additionally,
// remove the registration from the table at the same time. If the token is not registered,
// Extract returns null and does not modify the table.
// [System.Runtime.CompilerServices.FriendAccessAllowed]
internal T ExtractHandler(EventRegistrationToken token)
{
T handler = null;
lock (m_tokens)
{
if (m_tokens.TryGetValue(token, out handler))
{
RemoveEventHandlerNoLock(token);
}
}
return handler;
}
// Generate a token that may be used for a particular event handler. We will frequently be called
// upon to look up a token value given only a delegate to start from. Therefore, we want to make
// an initial token value that is easily determined using only the delegate instance itself. Although
// in the common case this token value will be used to uniquely identify the handler, it is not
// the only possible token that can represent the handler.
//
// This means that both:
// * if there is a handler assigned to the generated initial token value, it is not necessarily
// this handler.
// * if there is no handler assigned to the generated initial token value, the handler may still
// be registered under a different token
//
// Effectively the only reasonable thing to do with this value is either to:
// 1. Use it as a good starting point for generating a token for handler
// 2. Use it as a guess to quickly see if the handler was really assigned this token value
private static EventRegistrationToken GetPreferredToken(T handler)
{
Debug.Assert(handler != null);
// We want to generate a token value that has the following properties:
// 1. is quickly obtained from the handler instance
// 2. uses bits in the upper 32 bits of the 64 bit value, in order to avoid bugs where code
// may assume the value is realy just 32 bits
// 3. uses bits in the bottom 32 bits of the 64 bit value, in order to ensure that code doesn't
// take a dependency on them always being 0.
//
// The simple algorithm chosen here is to simply assign the upper 32 bits the metadata token of the
// event handler type, and the lower 32 bits the hash code of the handler instance itself. Using the
// metadata token for the upper 32 bits gives us at least a small chance of being able to identify a
// totally corrupted token if we ever come across one in a minidump or other scenario.
//
// The hash code of a unicast delegate is not tied to the method being invoked, so in the case
// of a unicast delegate, the hash code of the target method is used instead of the full delegate
// hash code.
//
// While calculating this initial value will be somewhat more expensive than just using a counter
// for events that have few registrations, it will also gives us a shot at preventing unregistration
// from becoming an O(N) operation.
//
// We should feel free to change this algorithm as other requirements / optimizations become
// available. This implementation is sufficiently random that code cannot simply guess the value to
// take a dependency upon it. (Simply applying the hash-value algorithm directly won't work in the
// case of collisions, where we'll use a different token value).
uint handlerHashCode = 0;
/*
Delegate[] invocationList = ((Delegate)(object)handler).GetInvocationList();
if (invocationList.Length == 1)
{
handlerHashCode = (uint)invocationList[0].Method.GetHashCode();
}
else
{
*/
handlerHashCode = (uint)handler.GetHashCode();
// }
ulong tokenValue = /* ((ulong)(uint)typeof(T).MetadataToken << 32) | */ handlerHashCode;
return new EventRegistrationToken(unchecked((long)tokenValue));
}
public void RemoveEventHandler(EventRegistrationToken token)
{
// The 0 token is assigned to null handlers, so there's nothing to do
if (token.Value == 0)
{
return;
}
lock (m_tokens)
{
RemoveEventHandlerNoLock(token);
}
}
public void RemoveEventHandler(T handler)
{
// To match the Windows Runtime behaivor when adding a null handler, removing one is a no-op
if (handler == null)
{
return;
}
lock (m_tokens)
{
// Fast path - if the delegate is stored with its preferred token, then there's no need to do
// a full search of the table for it. Note that even if we find something stored using the
// preferred token value, it's possible we have a collision and another delegate was using that
// value. Therefore we need to make sure we really have the handler we want before taking the
// fast path.
EventRegistrationToken preferredToken = GetPreferredToken(handler);
T registeredHandler;
if (m_tokens.TryGetValue(preferredToken, out registeredHandler))
{
if (registeredHandler == handler)
{
RemoveEventHandlerNoLock(preferredToken);
return;
}
}
// Slow path - we didn't find the delegate with its preferred token, so we need to fall
// back to a search of the table
foreach (KeyValuePair<EventRegistrationToken, T> registration in m_tokens)
{
if (registration.Value == (T)(object)handler)
{
RemoveEventHandlerNoLock(registration.Key);
// If a delegate has been added multiple times to handle an event, then it
// needs to be removed the same number of times to stop handling the event.
// Stop after the first one we find.
return;
}
}
// Note that falling off the end of the loop is not an error, as removing a registration
// for a handler that is not currently registered is simply a no-op
}
}
private void RemoveEventHandlerNoLock(EventRegistrationToken token)
{
T handler;
if (m_tokens.TryGetValue(token, out handler))
{
m_tokens.Remove(token);
// Update the current invocation list to remove the delegate
Delegate invokeList = (Delegate)(object)m_invokeList;
invokeList = MulticastDelegate.Remove(invokeList, (Delegate)(object)handler);
m_invokeList = (T)(object)invokeList;
}
}
public static EventRegistrationTokenTable<T> GetOrCreateEventRegistrationTokenTable(ref EventRegistrationTokenTable<T> refEventTable)
{
if (refEventTable == null)
{
Interlocked.CompareExchange(ref refEventTable, new EventRegistrationTokenTable<T>(), null);
}
return refEventTable;
}
}
public static partial class EventRegistrationHelpers
{
/// <summary>
/// A helper method that exposed in our System.Private.MCG
/// contract assembly to access the internal ExtractHandler method
/// There are other options such as
/// 1) define another EventRegistrationTokenTable.Extracthandler in
/// System.Private.MCG assembly. Unfortunately this doesn't work because
/// compiler sees two EventRegistrationTokenTable classes in two contracts
/// 2) make a Extracthandler an extention method. This requires having a "using" statement for the
/// extension methods and doesn't make things easier to understand
/// </summary>
public static T ExtractHandler<T>(System.Runtime.InteropServices.WindowsRuntime.EventRegistrationTokenTable<T> table, System.Runtime.InteropServices.WindowsRuntime.EventRegistrationToken token) where T : class
{
return table.ExtractHandler(token);
}
/// <summary>
/// Given a key, locate the corresponding value in the ConditionalWeakTable according to value
/// equality. Will create a new value if the key is not found.
/// <summary>
public static TValue GetValueFromEquivalentKey<TKey, TValue>(ConditionalWeakTable<TKey, TValue> table, TKey key, ConditionalWeakTable<TKey, TValue>.CreateValueCallback callback)
where TKey : class
where TValue : class
{
TValue value;
TKey foundKey = table.FindEquivalentKeyUnsafe(key, out value);
if (foundKey == default(TKey))
{
value = callback(key);
table.Add(key, value);
}
return value;
}
}
}
| |
using System;
using System.Globalization;
#if !BUILDTASK
using Avalonia.Animation.Animators;
#endif
using Avalonia.Utilities;
namespace Avalonia
{
/// <summary>
/// Defines a size.
/// </summary>
#if !BUILDTASK
public
#endif
readonly struct Size : IEquatable<Size>
{
static Size()
{
#if !BUILDTASK
Animation.Animation.RegisterAnimator<SizeAnimator>(prop => typeof(Size).IsAssignableFrom(prop.PropertyType));
#endif
}
/// <summary>
/// A size representing infinity.
/// </summary>
public static readonly Size Infinity = new Size(double.PositiveInfinity, double.PositiveInfinity);
/// <summary>
/// A size representing zero
/// </summary>
public static readonly Size Empty = new Size(0, 0);
/// <summary>
/// The width.
/// </summary>
private readonly double _width;
/// <summary>
/// The height.
/// </summary>
private readonly double _height;
/// <summary>
/// Initializes a new instance of the <see cref="Size"/> structure.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public Size(double width, double height)
{
_width = width;
_height = height;
}
/// <summary>
/// Gets the aspect ratio of the size.
/// </summary>
public double AspectRatio => _width / _height;
/// <summary>
/// Gets the width.
/// </summary>
public double Width => _width;
/// <summary>
/// Gets the height.
/// </summary>
public double Height => _height;
/// <summary>
/// Checks for equality between two <see cref="Size"/>s.
/// </summary>
/// <param name="left">The first size.</param>
/// <param name="right">The second size.</param>
/// <returns>True if the sizes are equal; otherwise false.</returns>
public static bool operator ==(Size left, Size right)
{
return left.Equals(right);
}
/// <summary>
/// Checks for inequality between two <see cref="Size"/>s.
/// </summary>
/// <param name="left">The first size.</param>
/// <param name="right">The second size.</param>
/// <returns>True if the sizes are unequal; otherwise false.</returns>
public static bool operator !=(Size left, Size right)
{
return !(left == right);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator *(Size size, Vector scale)
{
return new Size(size._width * scale.X, size._height * scale.Y);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator /(Size size, Vector scale)
{
return new Size(size._width / scale.X, size._height / scale.Y);
}
/// <summary>
/// Divides a size by another size to produce a scaling factor.
/// </summary>
/// <param name="left">The first size</param>
/// <param name="right">The second size.</param>
/// <returns>The scaled size.</returns>
public static Vector operator /(Size left, Size right)
{
return new Vector(left._width / right._width, left._height / right._height);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator *(Size size, double scale)
{
return new Size(size._width * scale, size._height * scale);
}
/// <summary>
/// Scales a size.
/// </summary>
/// <param name="size">The size</param>
/// <param name="scale">The scaling factor.</param>
/// <returns>The scaled size.</returns>
public static Size operator /(Size size, double scale)
{
return new Size(size._width / scale, size._height / scale);
}
public static Size operator +(Size size, Size toAdd)
{
return new Size(size._width + toAdd._width, size._height + toAdd._height);
}
public static Size operator -(Size size, Size toSubtract)
{
return new Size(size._width - toSubtract._width, size._height - toSubtract._height);
}
/// <summary>
/// Parses a <see cref="Size"/> string.
/// </summary>
/// <param name="s">The string.</param>
/// <returns>The <see cref="Size"/>.</returns>
public static Size Parse(string s)
{
using (var tokenizer = new StringTokenizer(s, CultureInfo.InvariantCulture, exceptionMessage: "Invalid Size."))
{
return new Size(
tokenizer.ReadDouble(),
tokenizer.ReadDouble());
}
}
/// <summary>
/// Constrains the size.
/// </summary>
/// <param name="constraint">The size to constrain to.</param>
/// <returns>The constrained size.</returns>
public Size Constrain(Size constraint)
{
return new Size(
Math.Min(_width, constraint._width),
Math.Min(_height, constraint._height));
}
/// <summary>
/// Deflates the size by a <see cref="Thickness"/>.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The deflated size.</returns>
/// <remarks>The deflated size cannot be less than 0.</remarks>
public Size Deflate(Thickness thickness)
{
return new Size(
Math.Max(0, _width - thickness.Left - thickness.Right),
Math.Max(0, _height - thickness.Top - thickness.Bottom));
}
/// <summary>
/// Returns a boolean indicating whether the size is equal to the other given size (bitwise).
/// </summary>
/// <param name="other">The other size to test equality against.</param>
/// <returns>True if this size is equal to other; False otherwise.</returns>
public bool Equals(Size other)
{
// ReSharper disable CompareOfFloatsByEqualityOperator
return _width == other._width &&
_height == other._height;
// ReSharper enable CompareOfFloatsByEqualityOperator
}
/// <summary>
/// Returns a boolean indicating whether the size is equal to the other given size (numerically).
/// </summary>
/// <param name="other">The other size to test equality against.</param>
/// <returns>True if this size is equal to other; False otherwise.</returns>
public bool NearlyEquals(Size other)
{
return MathUtilities.AreClose(_width, other._width) &&
MathUtilities.AreClose(_height, other._height);
}
/// <summary>
/// Checks for equality between a size and an object.
/// </summary>
/// <param name="obj">The object.</param>
/// <returns>
/// True if <paramref name="obj"/> is a size that equals the current size.
/// </returns>
public override bool Equals(object? obj) => obj is Size other && Equals(other);
/// <summary>
/// Returns a hash code for a <see cref="Size"/>.
/// </summary>
/// <returns>The hash code.</returns>
public override int GetHashCode()
{
unchecked
{
int hash = 17;
hash = (hash * 23) + Width.GetHashCode();
hash = (hash * 23) + Height.GetHashCode();
return hash;
}
}
/// <summary>
/// Inflates the size by a <see cref="Thickness"/>.
/// </summary>
/// <param name="thickness">The thickness.</param>
/// <returns>The inflated size.</returns>
public Size Inflate(Thickness thickness)
{
return new Size(
_width + thickness.Left + thickness.Right,
_height + thickness.Top + thickness.Bottom);
}
/// <summary>
/// Returns a new <see cref="Size"/> with the same height and the specified width.
/// </summary>
/// <param name="width">The width.</param>
/// <returns>The new <see cref="Size"/>.</returns>
public Size WithWidth(double width)
{
return new Size(width, _height);
}
/// <summary>
/// Returns a new <see cref="Size"/> with the same width and the specified height.
/// </summary>
/// <param name="height">The height.</param>
/// <returns>The new <see cref="Size"/>.</returns>
public Size WithHeight(double height)
{
return new Size(_width, height);
}
/// <summary>
/// Returns the string representation of the size.
/// </summary>
/// <returns>The string representation of the size.</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "{0}, {1}", _width, _height);
}
/// <summary>
/// Deconstructs the size into its Width and Height values.
/// </summary>
/// <param name="width">The width.</param>
/// <param name="height">The height.</param>
public void Deconstruct(out double width, out double height)
{
width = this._width;
height = this._height;
}
/// <summary>
/// Gets a value indicating whether the Width and Height values are zero.
/// </summary>
public bool IsDefault
{
get { return (_width == 0) && (_height == 0); }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Giftable.API.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="WmlCalendarAdapter.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Globalization;
using System.IO;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.MobileControls;
using System.Web.UI.MobileControls.Adapters;
using System.Web.UI.WebControls;
using System.Diagnostics;
using System.Collections;
using System.Security.Permissions;
#if COMPILING_FOR_SHIPPED_SOURCE
namespace System.Web.UI.MobileControls.ShippedAdapterSource
#else
namespace System.Web.UI.MobileControls.Adapters
#endif
{
/*
* WmlCalendarAdapter provides the wml device functionality for Calendar
* control. It is using secondary UI support to provide internal screens
* to allow the user to pick or enter a date.
*
* Copyright (c) 2000 Microsoft Corporation
*/
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter"]/*' />
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class WmlCalendarAdapter : WmlControlAdapter
{
private SelectionList _selectList;
private TextBox _textBox;
private List _optionList;
private List _monthList;
private List _weekList;
private List _dayList;
private int _chooseOption = FirstPrompt;
private int _monthsToDisplay;
private int _eraCount = 0;
/////////////////////////////////////////////////////////////////////
// Globalization of Calendar Information:
// Similar to the globalization support of the ASP.NET Calendar control,
// this support is done via COM+ thread culture info/object.
// Specific example can be found from ASP.NET Calendar spec.
/////////////////////////////////////////////////////////////////////
// This member variable is set each time when calendar info needs to
// be accessed and be shared for other helper functions.
private Globalization.Calendar _threadCalendar;
private String _textBoxErrorMessage;
// Since SecondaryUIMode is an int type, we use constant integers here
// instead of enum so the mode can be compared without casting.
private const int FirstPrompt = NotSecondaryUIInit;
private const int OptionPrompt = NotSecondaryUIInit + 1;
private const int TypeDate = NotSecondaryUIInit + 2;
private const int DateOption = NotSecondaryUIInit + 3;
private const int WeekOption = NotSecondaryUIInit + 4;
private const int MonthOption = NotSecondaryUIInit + 5;
private const int ChooseMonth = NotSecondaryUIInit + 6;
private const int ChooseWeek = NotSecondaryUIInit + 7;
private const int ChooseDay = NotSecondaryUIInit + 8;
private const int DefaultDateDone = NotSecondaryUIInit + 9;
private const int TypeDateDone = NotSecondaryUIInit + 10;
private const int Done = NotSecondaryUIInit + 11;
private const String DaySeparator = " - ";
private const String Space = " ";
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.Control"]/*' />
protected new Calendar Control
{
get
{
return (Calendar)base.Control;
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.OnInit"]/*' />
public override void OnInit(EventArgs e)
{
ListCommandEventHandler listCommandEventHandler;
// Create secondary child controls for rendering secondary UI.
// Note that their ViewState is disabled because they are used
// for rendering only.
//---------------------------------------------------------------
_selectList = new SelectionList();
_selectList.Visible = false;
_selectList.EnableViewState = false;
Control.Controls.Add(_selectList);
_textBox = new TextBox();
_textBox.Visible = false;
_textBox.EnableViewState = false;
Control.Controls.Add(_textBox);
// Below are initialization of several list controls. A note is
// that here the usage of DataMember is solely for remembering
// how many items a particular list control is bounded to. The
// property is not used as originally designed.
//---------------------------------------------------------------
_optionList = new List();
_optionList.DataMember = "5";
listCommandEventHandler = new ListCommandEventHandler(this.OptionListEventHandler);
InitList(_optionList, listCommandEventHandler);
// Use MobileCapabilities to check screen size and determine how
// many months should be displayed for different devices.
_monthsToDisplay = MonthsToDisplay(Device.ScreenCharactersHeight);
// Create the list of months, including [Next] and [Prev] links
_monthList = new List();
_monthList.DataMember = Convert.ToString(_monthsToDisplay + 2, CultureInfo.InvariantCulture);
listCommandEventHandler = new ListCommandEventHandler(this.MonthListEventHandler);
InitList(_monthList, listCommandEventHandler);
_weekList = new List();
_weekList.DataMember = "6";
listCommandEventHandler = new ListCommandEventHandler(this.WeekListEventHandler);
InitList(_weekList, listCommandEventHandler);
_dayList = new List();
_dayList.DataMember = "7";
listCommandEventHandler = new ListCommandEventHandler(this.DayListEventHandler);
InitList(_dayList, listCommandEventHandler);
// Initialize the VisibleDate which will be used to keep track
// the ongoing selection of year, month and day from multiple
// secondary UI screens. If the page is loaded for the first
// time, it doesn't need to be initialized (since it is not used
// yet) so no unnecessary viewstate value will be generated.
if (Page.IsPostBack && Control.VisibleDate == DateTime.MinValue)
{
Control.VisibleDate = DateTime.Today;
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.OnLoad"]/*' />
public override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Here we check to see which list control should be initialized
// with items so postback event can be handled properly.
if (Page.IsPostBack)
{
String controlId = Page.Request[MobilePage.HiddenPostEventSourceId];
if (controlId != null && controlId.Length != 0)
{
List list = Page.FindControl(controlId) as List;
if (list != null &&
Control.Controls.Contains(list))
{
DataBindListWithEmptyValues(
list, Convert.ToInt32(list.DataMember, CultureInfo.InvariantCulture));
}
}
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.LoadAdapterState"]/*' />
public override void LoadAdapterState(Object state)
{
if (state != null)
{
if (state is Pair)
{
Pair pair = (Pair)state;
base.LoadAdapterState(pair.First);
_chooseOption = (int)pair.Second;
}
else if (state is Triplet)
{
Triplet triplet = (Triplet)state;
base.LoadAdapterState(triplet.First);
_chooseOption = (int)triplet.Second;
Control.VisibleDate = new DateTime(Int64.Parse((String)triplet.Third, CultureInfo.InvariantCulture));
}
else if (state is Object[])
{
Object[] viewState = (Object[])state;
base.LoadAdapterState(viewState[0]);
_chooseOption = (int)viewState[1];
Control.VisibleDate = new DateTime(Int64.Parse((String)viewState[2], CultureInfo.InvariantCulture));
_eraCount = (int)viewState[3];
if (SecondaryUIMode == TypeDate)
{
// Create a placeholder list for capturing the selected era
// in postback data.
for (int i = 0; i < _eraCount; i++)
{
_selectList.Items.Add(String.Empty);
}
}
}
else
{
_chooseOption = (int)state;
}
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.SaveAdapterState"]/*' />
public override Object SaveAdapterState()
{
DateTime visibleDate = Control.VisibleDate;
bool saveVisibleDate = visibleDate != DateTime.MinValue &&
DateTime.Compare(visibleDate, DateTime.Today) != 0 &&
!IsViewStateEnabled();
Object baseState = base.SaveAdapterState();
if (baseState == null && !saveVisibleDate && _eraCount == 0)
{
if (_chooseOption != FirstPrompt)
{
return _chooseOption;
}
else
{
return null;
}
}
else if (!saveVisibleDate && _eraCount == 0)
{
return new Pair(baseState, _chooseOption);
}
else if (_eraCount == 0)
{
return new Triplet(baseState, _chooseOption, visibleDate.Ticks.ToString(CultureInfo.InvariantCulture));
}
else
{
return new Object[] { baseState,
_chooseOption,
visibleDate.Ticks.ToString(CultureInfo.InvariantCulture),
_eraCount };
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.OnPreRender"]/*' />
public override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// We specially binding eras of the current calendar object here
// when the UI of typing date is display. We do it only if the
// calendar supports more than one era.
if (SecondaryUIMode == TypeDate)
{
DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo;
int [] ints = currentInfo.Calendar.Eras;
if (ints.Length > 1)
{
// Save the value in private view state
_eraCount = ints.Length;
int currentEra;
if (_selectList.SelectedIndex != -1)
{
currentEra = ints[_selectList.SelectedIndex];
}
else
{
currentEra =
currentInfo.Calendar.GetEra(Control.VisibleDate);
}
// Clear the placeholder item list if created in LoadAdapterState
_selectList.Items.Clear();
for (int i = 0; i < ints.Length; i++)
{
int era = ints[i];
_selectList.Items.Add(currentInfo.GetEraName(era));
// There is no association between the era value and
// its index in the era array, so we need to check it
// explicitly for the default selected index.
if (currentEra == era)
{
_selectList.SelectedIndex = i;
}
}
_selectList.Visible = true;
}
else
{
// disable viewstate since no need to save any data for
// this control
_selectList.EnableViewState = false;
}
}
else
{
_selectList.EnableViewState = false;
}
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.Render"]/*' />
public override void Render(WmlMobileTextWriter writer)
{
ArrayList arr;
DateTime tempDate;
DateTimeFormatInfo currentDateTimeInfo = DateTimeFormatInfo.CurrentInfo;
String abbreviatedMonthDayPattern = AbbreviateMonthPattern(currentDateTimeInfo.MonthDayPattern);
_threadCalendar = currentDateTimeInfo.Calendar;
// RendersWmlSelectsAsMenuCards is true means the list control will be
// rendered as select/option tags, where the break tag before
// them will become an extra line which doesn't like good.
bool addBreakBeforeListControl = Device.RendersWmlSelectsAsMenuCards;
writer.EnterStyle(Style);
Debug.Assert(NotSecondaryUI == NotSecondaryUIInit);
switch (SecondaryUIMode)
{
case FirstPrompt:
String promptText = Control.CalendarEntryText;
if (String.IsNullOrEmpty(promptText))
{
promptText = SR.GetString(SR.CalendarAdapterFirstPrompt);
}
// Link to input option selection screen
RenderPostBackEvent(writer,
OptionPrompt.ToString(CultureInfo.InvariantCulture),
GetDefaultLabel(GoLabel),
true,
promptText,
true);
break;
// Render the first secondary page that provides differnt
// options to select a date.
case OptionPrompt:
writer.RenderText(SR.GetString(SR.CalendarAdapterOptionPrompt),
!addBreakBeforeListControl);
arr = new ArrayList();
// Option to select the default date
arr.Add(Control.VisibleDate.ToString(
currentDateTimeInfo.ShortDatePattern, CultureInfo.CurrentCulture));
// Option to another page that can enter a date by typing
arr.Add(SR.GetString(SR.CalendarAdapterOptionType));
// Options to a set of pages for selecting a date, a week
// or a month by picking month/year, week and day
// accordingly. Available options are determined by
// SelectionMode.
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseDate));
if (Control.SelectionMode == CalendarSelectionMode.DayWeek ||
Control.SelectionMode == CalendarSelectionMode.DayWeekMonth)
{
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseWeek));
if (Control.SelectionMode == CalendarSelectionMode.DayWeekMonth)
{
arr.Add(SR.GetString(SR.CalendarAdapterOptionChooseMonth));
}
}
DataBindAndRender(writer, _optionList, arr);
break;
// Render a title and textbox to capture a date entered by user
case TypeDate:
if (_textBoxErrorMessage != null)
{
writer.RenderText(_textBoxErrorMessage, true);
}
if (_selectList.Visible)
{
writer.RenderText(SR.GetString(SR.CalendarAdapterOptionEra), true);
_selectList.RenderControl(writer);
}
String numericDateFormat = GetNumericDateFormat();
writer.RenderText(SR.GetString(SR.CalendarAdapterOptionType) + ":", true);
writer.RenderText("(");
writer.RenderText(numericDateFormat.ToUpper(CultureInfo.InvariantCulture));
writer.RenderText(")");
if (!_selectList.Visible)
{
writer.RenderText(GetEra(Control.VisibleDate));
}
writer.RenderText(String.Empty, true);
_textBox.Numeric = true;
_textBox.Size = numericDateFormat.Length;
_textBox.MaxLength = numericDateFormat.Length;
_textBox.Text = Control.VisibleDate.ToString(numericDateFormat, CultureInfo.InvariantCulture);
_textBox.Visible = true;
_textBox.RenderControl(writer);
String okLabel = GetDefaultLabel(OKLabel);
// accept softkey for sending the textbox value back to the server
RenderPostBackEvent(writer,
TypeDateDone.ToString(CultureInfo.InvariantCulture),
okLabel,
true,
okLabel,
true,
WmlPostFieldType.Raw);
break;
// Render a paged list for choosing a month
case ChooseMonth:
{
String displayText = String.Format(CultureInfo.CurrentCulture, "{0}:", SR.GetString(SR.CalendarAdapterOptionChooseMonth));
writer.RenderText(displayText, !addBreakBeforeListControl);
tempDate = Control.VisibleDate;
String abbreviatedYearMonthPattern = AbbreviateMonthPattern(currentDateTimeInfo.YearMonthPattern);
// This is to be consistent with ASP.NET Calendar control
// on handling YearMonthPattern:
// Some cultures have a comma in their YearMonthPattern,
// which does not look right in a calendar. Here we
// strip the comma off.
int indexComma = abbreviatedYearMonthPattern.IndexOf(',');
if (indexComma >= 0)
{
abbreviatedYearMonthPattern =
abbreviatedYearMonthPattern.Remove(indexComma, 1);
}
arr = new ArrayList();
for (int i = 0; i < _monthsToDisplay; i++)
{
arr.Add(tempDate.ToString(abbreviatedYearMonthPattern, CultureInfo.CurrentCulture));
tempDate = _threadCalendar.AddMonths(tempDate, 1);
}
arr.Add(GetDefaultLabel(NextLabel));
arr.Add(GetDefaultLabel(PreviousLabel));
DataBindAndRender(writer, _monthList, arr);
break;
}
// Based on the month selected in case ChooseMonth above, render a list of
// availabe weeks of the month.
case ChooseWeek:
{
String monthFormat = (GetNumericDateFormat()[0] == 'y') ? "yyyy/M" : "M/yyyy";
String displayText = String.Format(CultureInfo.CurrentCulture, "{0} ({1}):",
SR.GetString(SR.CalendarAdapterOptionChooseWeek),
Control.VisibleDate.ToString(monthFormat, CultureInfo.CurrentCulture));
writer.RenderText(displayText, !addBreakBeforeListControl);
// List weeks of days of the selected month. May include
// days from the previous and the next month to fill out
// all six week choices. This is consistent with the
// ASP.NET Calendar control.
// Note that the event handling code of this list control
// should be implemented according to the index content
// generated here.
tempDate = FirstCalendarDay(Control.VisibleDate);
arr = new ArrayList();
String weekDisplay;
for (int i = 0; i < 6; i++)
{
weekDisplay = tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
weekDisplay += DaySeparator;
tempDate = _threadCalendar.AddDays(tempDate, 6);
weekDisplay += tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
arr.Add(weekDisplay);
tempDate = _threadCalendar.AddDays(tempDate, 1);
}
DataBindAndRender(writer, _weekList, arr);
break;
}
// Based on the month and week selected in case ChooseMonth and ChooseWeek above,
// render a list of the dates in the week.
case ChooseDay:
{
String displayText = String.Format(CultureInfo.CurrentCulture, "{0}:", SR.GetString(SR.CalendarAdapterOptionChooseDate));
writer.RenderText(displayText, !addBreakBeforeListControl);
tempDate = Control.VisibleDate;
arr = new ArrayList();
String date;
String dayName;
StringBuilder dayDisplay = new StringBuilder();
bool dayNameFirst = (GetNumericDateFormat()[0] != 'y');
for (int i = 0; i < 7; i++)
{
date = tempDate.ToString(abbreviatedMonthDayPattern, CultureInfo.CurrentCulture);
if (Control.ShowDayHeader)
{
// Use the short format for displaying day name
dayName = GetAbbreviatedDayName(tempDate);
dayDisplay.Length = 0;
if (dayNameFirst)
{
dayDisplay.Append(dayName);
dayDisplay.Append(Space);
dayDisplay.Append(date);
}
else
{
dayDisplay.Append(date);
dayDisplay.Append(Space);
dayDisplay.Append(dayName);
}
arr.Add(dayDisplay.ToString());
}
else
{
arr.Add(date);
}
tempDate = _threadCalendar.AddDays(tempDate, 1);
}
DataBindAndRender(writer, _dayList, arr);
break;
}
default:
Debug.Assert(false, "Unexpected Secondary UI Mode");
break;
}
writer.ExitStyle(Style);
}
/// <include file='doc\WmlCalendarAdapter.uex' path='docs/doc[@for="WmlCalendarAdapter.HandlePostBackEvent"]/*' />
public override bool HandlePostBackEvent(String eventArgument)
{
// This is mainly to capture the option picked by the user on
// secondary pages and manipulate SecondaryUIMode accordingly so
// Render() can generate the appropriate UI.
// It also capture the state "Done" which can be set when a date,
// a week or a month is selected or entered in some secondary
// page.
SecondaryUIMode = Int32.Parse(eventArgument, CultureInfo.InvariantCulture);
Debug.Assert(NotSecondaryUI == NotSecondaryUIInit);
switch (SecondaryUIMode)
{
case DefaultDateDone:
SelectRange(Control.VisibleDate, Control.VisibleDate);
goto case Done;
case TypeDateDone:
try
{
String dateText = _textBox.Text;
String dateFormat = GetNumericDateFormat();
DateTimeFormatInfo currentInfo = DateTimeFormatInfo.CurrentInfo;
int eraIndex = _selectList.SelectedIndex;
if (eraIndex >= 0 &&
eraIndex < currentInfo.Calendar.Eras.Length)
{
dateText += currentInfo.GetEraName(currentInfo.Calendar.Eras[eraIndex]);
dateFormat += "gg";
}
DateTime dateTime = DateTime.ParseExact(dateText, dateFormat, null);
SelectRange(dateTime, dateTime);
Control.VisibleDate = dateTime;
}
catch
{
_textBoxErrorMessage = SR.GetString(SR.CalendarAdapterTextBoxErrorMessage);
SecondaryUIMode = TypeDate;
break;
}
goto case Done;
case Done:
// Set the secondary exit code and raise the selection event for
// web page developer to manipulate the selected date.
ExitSecondaryUIMode();
_chooseOption = FirstPrompt;
break;
case DateOption:
case WeekOption:
case MonthOption:
_chooseOption = SecondaryUIMode; // save in the ViewState
// In all 3 cases, continue to the UI that chooses a month
SecondaryUIMode = ChooseMonth;
break;
}
return true;
}
/////////////////////////////////////////////////////////////////////
// Misc. helper and wrapper functions
/////////////////////////////////////////////////////////////////////
private int MonthsToDisplay(int screenCharactersHeight)
{
const int MinMonthsToDisplay = 4;
const int MaxMonthsToDisplay = 12;
if (screenCharactersHeight < MinMonthsToDisplay)
{
return MinMonthsToDisplay;
}
else if (screenCharactersHeight > MaxMonthsToDisplay)
{
return MaxMonthsToDisplay;
}
return screenCharactersHeight;
}
// A helper function to initialize and add a child list control
private void InitList(List list,
ListCommandEventHandler eventHandler)
{
list.Visible = false;
list.ItemCommand += eventHandler;
list.EnableViewState = false;
Control.Controls.Add(list);
}
private void DataBindListWithEmptyValues(List list, int arraySize)
{
ArrayList arr = new ArrayList();
for (int i = 0; i < arraySize; i++)
{
arr.Add("");
}
list.DataSource = arr;
list.DataBind();
}
// A helper function to do the common code for DataBind and
// RenderChildren.
private void DataBindAndRender(WmlMobileTextWriter writer,
List list,
ArrayList arr)
{
list.DataSource = arr;
list.DataBind();
list.Visible = true;
list.RenderControl(writer);
}
// Abbreviate the Month format from "MMMM" (full
// month name) to "MMM" (three-character month abbreviation)
private String AbbreviateMonthPattern(String pattern)
{
const String FullMonthFormat = "MMMM";
int i = pattern.IndexOf(FullMonthFormat, StringComparison.Ordinal);
if (i != -1)
{
pattern = pattern.Remove(i, 1);
}
return pattern;
}
private String GetAbbreviatedDayName(DateTime dateTime)
{
return DateTimeFormatInfo.CurrentInfo.GetAbbreviatedDayName(
_threadCalendar.GetDayOfWeek(dateTime));
}
private String GetEra(DateTime dateTime)
{
// We shouldn't need to display the era for the common Gregorian
// Calendar
if (DateTimeFormatInfo.CurrentInfo.Calendar.GetType() ==
typeof(GregorianCalendar))
{
return String.Empty;
}
else
{
return dateTime.ToString("gg", CultureInfo.CurrentCulture);
}
}
private static readonly char[] formatChars =
new char[] { 'M', 'd', 'y' };
private String GetNumericDateFormat()
{
String shortDatePattern =
DateTimeFormatInfo.CurrentInfo.ShortDatePattern;
// Guess on what short date pattern should be used
int i = shortDatePattern.IndexOfAny(formatChars);
char firstFormatChar;
if (i == -1)
{
firstFormatChar = 'M';
}
else
{
firstFormatChar = shortDatePattern[i];
}
// We either use two or four digits for the year
String yearPattern;
if (shortDatePattern.IndexOf("yyyy", StringComparison.Ordinal) == -1)
{
yearPattern = "yy";
}
else
{
yearPattern = "yyyy";
}
switch (firstFormatChar)
{
case 'M':
default:
return "MMdd" + yearPattern;
case 'd':
return "ddMM" + yearPattern;
case 'y':
return yearPattern + "MMdd";
}
}
/////////////////////////////////////////////////////////////////////
// Helper functions
/////////////////////////////////////////////////////////////////////
// Return the first date of the input year and month
private DateTime EffectiveVisibleDate(DateTime visibleDate)
{
return _threadCalendar.AddDays(
visibleDate,
-(_threadCalendar.GetDayOfMonth(visibleDate) - 1));
}
// Return the beginning date of a calendar that includes the
// targeting month. The date can actually be in the previous month.
private DateTime FirstCalendarDay(DateTime visibleDate)
{
DateTime firstDayOfMonth = EffectiveVisibleDate(visibleDate);
int daysFromLastMonth =
((int)_threadCalendar.GetDayOfWeek(firstDayOfMonth)) -
NumericFirstDayOfWeek();
// Always display at least one day from the previous month
if (daysFromLastMonth <= 0)
{
daysFromLastMonth += 7;
}
return _threadCalendar.AddDays(firstDayOfMonth, -daysFromLastMonth);
}
private int NumericFirstDayOfWeek()
{
// Used globalized value by default
return(Control.FirstDayOfWeek == FirstDayOfWeek.Default)
? (int) DateTimeFormatInfo.CurrentInfo.FirstDayOfWeek
: (int) Control.FirstDayOfWeek;
}
/////////////////////////////////////////////////////////////////////
// The followings are event handlers to capture the selection from
// the corresponding list control in an secondary page. The index of
// the selection is used to determine which and how the next
// secondary page is rendered. Some event handlers below update
// Calendar.VisibleDate and set SecondaryUIMode with appropriate
// values.
////////////////////////////////////////////////////////////////////////
private static readonly int[] Options =
{DefaultDateDone, TypeDate, DateOption, WeekOption, MonthOption};
private void OptionListEventHandler(Object source, ListCommandEventArgs e)
{
SecondaryUIMode = Options[e.ListItem.Index];
HandlePostBackEvent(SecondaryUIMode.ToString(CultureInfo.InvariantCulture));
}
private void MonthListEventHandler(Object source, ListCommandEventArgs e)
{
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
if (e.ListItem.Index == _monthsToDisplay)
{
// Next was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate, _monthsToDisplay);
SecondaryUIMode = ChooseMonth;
}
else if (e.ListItem.Index == _monthsToDisplay + 1)
{
// Prev was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate, -_monthsToDisplay);
SecondaryUIMode = ChooseMonth;
}
else
{
// A month was selected
Control.VisibleDate = _threadCalendar.AddMonths(
Control.VisibleDate,
e.ListItem.Index);
if (_chooseOption == MonthOption)
{
// Add the whole month to the date list
DateTime beginDate = EffectiveVisibleDate(Control.VisibleDate);
Control.VisibleDate = beginDate;
DateTime endDate = _threadCalendar.AddMonths(beginDate, 1);
endDate = _threadCalendar.AddDays(endDate, -1);
SelectRange(beginDate, endDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
else
{
SecondaryUIMode = ChooseWeek;
}
}
}
private void WeekListEventHandler(Object source, ListCommandEventArgs e)
{
// Get the first calendar day and adjust it to the week the user
// selected (to be consistent with the index setting in Render())
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
DateTime tempDate = FirstCalendarDay(Control.VisibleDate);
Control.VisibleDate = _threadCalendar.AddDays(tempDate, e.ListItem.Index * 7);
if (_chooseOption == WeekOption)
{
// Add the whole week to the date list
DateTime endDate = _threadCalendar.AddDays(Control.VisibleDate, 6);
SelectRange(Control.VisibleDate, endDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
else
{
SecondaryUIMode = ChooseDay;
}
}
private void DayListEventHandler(Object source, ListCommandEventArgs e)
{
_threadCalendar = DateTimeFormatInfo.CurrentInfo.Calendar;
// VisibleDate should have been set with the first day of the week
// so the selected index can be used to adjust to the selected day.
Control.VisibleDate = _threadCalendar.AddDays(Control.VisibleDate, e.ListItem.Index);
SelectRange(Control.VisibleDate, Control.VisibleDate);
HandlePostBackEvent(Done.ToString(CultureInfo.InvariantCulture));
}
private void SelectRange(DateTime dateFrom, DateTime dateTo)
{
Debug.Assert(dateFrom <= dateTo, "Bad Date Range");
// see if this range differs in any way from the current range
// these checks will determine this because the colleciton is sorted
TimeSpan ts = dateTo - dateFrom;
SelectedDatesCollection selectedDates = Control.SelectedDates;
if (selectedDates.Count != ts.Days + 1
|| selectedDates[0] != dateFrom
|| selectedDates[selectedDates.Count - 1] != dateTo)
{
selectedDates.SelectRange(dateFrom, dateTo);
Control.RaiseSelectionChangedEvent();
}
}
private bool IsViewStateEnabled()
{
Control ctl = Control;
while (ctl != null)
{
if (!ctl.EnableViewState)
{
return false;
}
ctl = ctl.Parent;
}
return true;
}
}
}
| |
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/*
* AvaTax API Client Library
*
* (c) 2004-2019 Avalara, Inc.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author Genevieve Conty
* @author Greg Hester
* Swagger name: AvaTaxClient
*/
namespace Avalara.AvaTax.RestClient
{
/// <summary>
/// Represents information about a tax form known to Avalara
/// </summary>
public class FormMasterModel
{
/// <summary>
/// Unique ID number of this form master object
/// </summary>
public Int32? id { get; set; }
/// <summary>
/// The type of the form being submitted
/// </summary>
public Int32? formTypeId { get; set; }
/// <summary>
/// Unique tax form code representing this tax form
/// </summary>
public String taxFormCode { get; set; }
/// <summary>
/// Legacy return name as known in the AvaFileForm table
/// </summary>
public String legacyReturnName { get; set; }
/// <summary>
/// Human readable form summary name
/// </summary>
public String taxFormName { get; set; }
/// <summary>
/// Description of this tax form
/// </summary>
public String description { get; set; }
/// <summary>
/// True if this form is available for use
/// </summary>
public Boolean? isEffective { get; set; }
/// <summary>
/// ISO 3166 code of the country that issued this tax form
/// </summary>
public String country { get; set; }
/// <summary>
/// The region within which this form was issued
/// </summary>
public String region { get; set; }
/// <summary>
/// Tax authority that issued the form
/// </summary>
public String authorityName { get; set; }
/// <summary>
/// DEPRECATED
/// </summary>
public String shortCode { get; set; }
/// <summary>
/// Day of the month when the form is due
/// </summary>
public Int32? dueDay { get; set; }
/// <summary>
/// Day of the month on which the form is considered delinquent. Almost always the same as DueDay
/// </summary>
public Int32? delinquentDay { get; set; }
/// <summary>
/// Month of the year the state considers as the first fiscal month
/// </summary>
public Int32? fiscalYearStartMonth { get; set; }
/// <summary>
/// Can form support multi frequencies
/// </summary>
public Boolean? hasMultiFrequencies { get; set; }
/// <summary>
/// Does this tax authority require a power of attorney in order to speak to Avalara
/// </summary>
public Boolean? isPOARequired { get; set; }
/// <summary>
/// True if this form requires that the customer register with the authority
/// </summary>
public Boolean? isRegistrationRequired { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasMultiRegistrationMethods { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasSchedules { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasMultiFilingMethods { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasMultiPayMethods { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? isEFTRequired { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? isFilePayMethodLinked { get; set; }
/// <summary>
/// Unused
/// </summary>
public Int32? mailingReceivedRuleId { get; set; }
/// <summary>
/// Unused
/// </summary>
public Int32? proofOfMailingId { get; set; }
/// <summary>
/// True if you can report a negative amount in a single jurisdiction on the form
/// </summary>
public Boolean? isNegAmountAllowed { get; set; }
/// <summary>
/// True if the form overall can go negative
/// </summary>
public Boolean? allowNegativeOverallTax { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? isNettingRequired { get; set; }
/// <summary>
/// Unused
/// </summary>
public Int32? roundingMethodId { get; set; }
/// <summary>
/// Total amount of discounts that can be received by a vendor each year
/// </summary>
public Decimal? vendorDiscountAnnualMax { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? versionsRequireAuthorityApproval { get; set; }
/// <summary>
/// Type of outlet reporting for this form
/// </summary>
public Int32? outletReportingMethodId { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasReportingCodes { get; set; }
/// <summary>
/// Not sure if used
/// </summary>
public Boolean? hasPrepayments { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? grossIncludesInterstateSales { get; set; }
/// <summary>
/// Unused
/// </summary>
public String grossIncludesTax { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasEfileFee { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasEpayFee { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? hasDependencies { get; set; }
/// <summary>
/// Unused
/// </summary>
public String requiredEfileTrigger { get; set; }
/// <summary>
/// Unused
/// </summary>
public String requiredEftTrigger { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? vendorDiscountEfile { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? vendorDiscountPaper { get; set; }
/// <summary>
/// Unused
/// </summary>
public String peerReviewed { get; set; }
/// <summary>
/// Unused
/// </summary>
public String peerReviewedId { get; set; }
/// <summary>
/// Unused
/// </summary>
public String peerReviewedDate { get; set; }
/// <summary>
/// ID of the Avalara user who created the form
/// </summary>
public Int32? createdUserId { get; set; }
/// <summary>
/// Date when form was created
/// </summary>
public DateTime? createdDate { get; set; }
/// <summary>
/// ID of the Avalara user who modified the form
/// </summary>
public Int32? modifiedUserId { get; set; }
/// <summary>
/// Date when form was modified
/// </summary>
public DateTime? modifiedDate { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddressMailTo { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddress1 { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddress2 { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddressCity { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddressRegion { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddressPostalCode { get; set; }
/// <summary>
/// Mailing address of the department of revenue
/// </summary>
public String dorAddressCountry { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddressMailTo { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddress1 { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddress2 { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddressCity { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddressRegion { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddressPostalCode { get; set; }
/// <summary>
/// Mailing address to use when a zero dollar form is filed
/// </summary>
public String zeroAddressCountry { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddressMailTo { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddress1 { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddress2 { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddressCity { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddressRegion { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddressPostalCode { get; set; }
/// <summary>
/// Mailing address to use when filing an amended return
/// </summary>
public String amendedAddressCountry { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? onlineBackFiling { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? onlineAmendedReturns { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public String prepaymentFrequency { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? outletLocationIdentifiersRequired { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public String listingSortOrder { get; set; }
/// <summary>
/// Link to the state department of revenue website, if available
/// </summary>
public String dorWebsite { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public Boolean? fileForAllOutlets { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public Boolean? paperFormsDoNotHaveDiscounts { get; set; }
/// <summary>
/// Internal behavior
/// </summary>
public Boolean? stackAggregation { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public String roundingPrecision { get; set; }
/// <summary>
/// --Need Further Clarification
/// </summary>
public String inconsistencyTolerance { get; set; }
/// <summary>
/// Date when this form became effective
/// </summary>
public DateTime? effDate { get; set; }
/// <summary>
/// Date when this form expired
/// </summary>
public DateTime? endDate { get; set; }
/// <summary>
/// True if this form can be shown to customers
/// </summary>
public Boolean? visibleToCustomers { get; set; }
/// <summary>
/// True if this form requires that you set up outlets in the state
/// </summary>
public Boolean? requiresOutletSetup { get; set; }
/// <summary>
/// True if this state permits payment by ACH Credit
/// </summary>
public Boolean? achCreditAllowed { get; set; }
/// <summary>
/// Jurisdiction level of the state
/// </summary>
public String reportLevel { get; set; }
/// <summary>
/// True if this form is verified filed via email
/// </summary>
public Boolean? postOfficeValidated { get; set; }
/// <summary>
/// Internal Avalara flag
/// </summary>
public String stackAggregationOption { get; set; }
/// <summary>
/// Internal Avalara flag
/// </summary>
public String sstBehavior { get; set; }
/// <summary>
/// Internal Avalara flag
/// </summary>
public String nonSstBehavior { get; set; }
/// <summary>
/// Phone number of the department of revenue
/// </summary>
public String dorPhoneNumber { get; set; }
/// <summary>
/// Unused
/// </summary>
public String averageCheckClearDays { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? filterZeroRatedLineDetails { get; set; }
/// <summary>
/// Unused
/// </summary>
public Boolean? allowsBulkFilingAccounts { get; set; }
/// <summary>
/// Unused
/// </summary>
public String bulkAccountInstructionLink { get; set; }
/// <summary>
/// Unused
/// </summary>
public String registrationIdFormat { get; set; }
/// <summary>
/// Unused
/// </summary>
public String thresholdTrigger { get; set; }
/// <summary>
/// Unused
/// </summary>
public String transactionSortingOption { get; set; }
/// <summary>
/// Unused
/// </summary>
public Int32? contentReviewFrequencyId { get; set; }
/// <summary>
/// Unused
/// </summary>
public String aliasForFormMasterId { get; set; }
/// <summary>
/// Convert this object to a JSON string of itself
/// </summary>
/// <returns>A JSON string of this object</returns>
public override string ToString()
{
return JsonConvert.SerializeObject(this, new JsonSerializerSettings() { Formatting = Formatting.Indented });
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="Vector3DKeyFrameCollection.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// This file was generated, please do not edit it directly.
//
// Please see http://wiki/default.aspx/Microsoft.Projects.Avalon/MilCodeGen.html for more information.
//
//---------------------------------------------------------------------------
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Windows.Media.Animation;
using System.Windows.Media.Media3D;
namespace System.Windows.Media.Animation
{
/// <summary>
/// This collection is used in conjunction with a KeyFrameVector3DAnimation
/// to animate a Vector3D property value along a set of key frames.
/// </summary>
public class Vector3DKeyFrameCollection : Freezable, IList
{
#region Data
private List<Vector3DKeyFrame> _keyFrames;
private static Vector3DKeyFrameCollection s_emptyCollection;
#endregion
#region Constructors
/// <Summary>
/// Creates a new Vector3DKeyFrameCollection.
/// </Summary>
public Vector3DKeyFrameCollection()
: base()
{
_keyFrames = new List< Vector3DKeyFrame>(2);
}
#endregion
#region Static Methods
/// <summary>
/// An empty Vector3DKeyFrameCollection.
/// </summary>
public static Vector3DKeyFrameCollection Empty
{
get
{
if (s_emptyCollection == null)
{
Vector3DKeyFrameCollection emptyCollection = new Vector3DKeyFrameCollection();
emptyCollection._keyFrames = new List< Vector3DKeyFrame>(0);
emptyCollection.Freeze();
s_emptyCollection = emptyCollection;
}
return s_emptyCollection;
}
}
#endregion
#region Freezable
/// <summary>
/// Creates a freezable copy of this Vector3DKeyFrameCollection.
/// </summary>
/// <returns>The copy</returns>
public new Vector3DKeyFrameCollection Clone()
{
return (Vector3DKeyFrameCollection)base.Clone();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CreateInstanceCore">Freezable.CreateInstanceCore</see>.
/// </summary>
/// <returns>The new Freezable.</returns>
protected override Freezable CreateInstanceCore()
{
return new Vector3DKeyFrameCollection();
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCore(System.Windows.Freezable)">Freezable.CloneCore</see>.
/// </summary>
protected override void CloneCore(Freezable sourceFreezable)
{
Vector3DKeyFrameCollection sourceCollection = (Vector3DKeyFrameCollection) sourceFreezable;
base.CloneCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< Vector3DKeyFrame>(count);
for (int i = 0; i < count; i++)
{
Vector3DKeyFrame keyFrame = (Vector3DKeyFrame)sourceCollection._keyFrames[i].Clone();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.CloneCurrentValueCore(System.Windows.Freezable)">Freezable.CloneCurrentValueCore</see>.
/// </summary>
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
Vector3DKeyFrameCollection sourceCollection = (Vector3DKeyFrameCollection) sourceFreezable;
base.CloneCurrentValueCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< Vector3DKeyFrame>(count);
for (int i = 0; i < count; i++)
{
Vector3DKeyFrame keyFrame = (Vector3DKeyFrame)sourceCollection._keyFrames[i].CloneCurrentValue();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetAsFrozenCore(System.Windows.Freezable)">Freezable.GetAsFrozenCore</see>.
/// </summary>
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
Vector3DKeyFrameCollection sourceCollection = (Vector3DKeyFrameCollection) sourceFreezable;
base.GetAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< Vector3DKeyFrame>(count);
for (int i = 0; i < count; i++)
{
Vector3DKeyFrame keyFrame = (Vector3DKeyFrame)sourceCollection._keyFrames[i].GetAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
/// Implementation of <see cref="System.Windows.Freezable.GetCurrentValueAsFrozenCore(System.Windows.Freezable)">Freezable.GetCurrentValueAsFrozenCore</see>.
/// </summary>
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
Vector3DKeyFrameCollection sourceCollection = (Vector3DKeyFrameCollection) sourceFreezable;
base.GetCurrentValueAsFrozenCore(sourceFreezable);
int count = sourceCollection._keyFrames.Count;
_keyFrames = new List< Vector3DKeyFrame>(count);
for (int i = 0; i < count; i++)
{
Vector3DKeyFrame keyFrame = (Vector3DKeyFrame)sourceCollection._keyFrames[i].GetCurrentValueAsFrozen();
_keyFrames.Add(keyFrame);
OnFreezablePropertyChanged(null, keyFrame);
}
}
/// <summary>
///
/// </summary>
protected override bool FreezeCore(bool isChecking)
{
bool canFreeze = base.FreezeCore(isChecking);
for (int i = 0; i < _keyFrames.Count && canFreeze; i++)
{
canFreeze &= Freezable.Freeze(_keyFrames[i], isChecking);
}
return canFreeze;
}
#endregion
#region IEnumerable
/// <summary>
/// Returns an enumerator of the Vector3DKeyFrames in the collection.
/// </summary>
public IEnumerator GetEnumerator()
{
ReadPreamble();
return _keyFrames.GetEnumerator();
}
#endregion
#region ICollection
/// <summary>
/// Returns the number of Vector3DKeyFrames in the collection.
/// </summary>
public int Count
{
get
{
ReadPreamble();
return _keyFrames.Count;
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.IsSynchronized">ICollection.IsSynchronized</see>.
/// </summary>
public bool IsSynchronized
{
get
{
ReadPreamble();
return (IsFrozen || Dispatcher != null);
}
}
/// <summary>
/// See <see cref="System.Collections.ICollection.SyncRoot">ICollection.SyncRoot</see>.
/// </summary>
public object SyncRoot
{
get
{
ReadPreamble();
return ((ICollection)_keyFrames).SyncRoot;
}
}
/// <summary>
/// Copies all of the Vector3DKeyFrames in the collection to an
/// array.
/// </summary>
void ICollection.CopyTo(Array array, int index)
{
ReadPreamble();
((ICollection)_keyFrames).CopyTo(array, index);
}
/// <summary>
/// Copies all of the Vector3DKeyFrames in the collection to an
/// array of Vector3DKeyFrames.
/// </summary>
public void CopyTo(Vector3DKeyFrame[] array, int index)
{
ReadPreamble();
_keyFrames.CopyTo(array, index);
}
#endregion
#region IList
/// <summary>
/// Adds a Vector3DKeyFrame to the collection.
/// </summary>
int IList.Add(object keyFrame)
{
return Add((Vector3DKeyFrame)keyFrame);
}
/// <summary>
/// Adds a Vector3DKeyFrame to the collection.
/// </summary>
public int Add(Vector3DKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Add(keyFrame);
WritePostscript();
return _keyFrames.Count - 1;
}
/// <summary>
/// Removes all Vector3DKeyFrames from the collection.
/// </summary>
public void Clear()
{
WritePreamble();
if (_keyFrames.Count > 0)
{
for (int i = 0; i < _keyFrames.Count; i++)
{
OnFreezablePropertyChanged(_keyFrames[i], null);
}
_keyFrames.Clear();
WritePostscript();
}
}
/// <summary>
/// Returns true of the collection contains the given Vector3DKeyFrame.
/// </summary>
bool IList.Contains(object keyFrame)
{
return Contains((Vector3DKeyFrame)keyFrame);
}
/// <summary>
/// Returns true of the collection contains the given Vector3DKeyFrame.
/// </summary>
public bool Contains(Vector3DKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.Contains(keyFrame);
}
/// <summary>
/// Returns the index of a given Vector3DKeyFrame in the collection.
/// </summary>
int IList.IndexOf(object keyFrame)
{
return IndexOf((Vector3DKeyFrame)keyFrame);
}
/// <summary>
/// Returns the index of a given Vector3DKeyFrame in the collection.
/// </summary>
public int IndexOf(Vector3DKeyFrame keyFrame)
{
ReadPreamble();
return _keyFrames.IndexOf(keyFrame);
}
/// <summary>
/// Inserts a Vector3DKeyFrame into a specific location in the collection.
/// </summary>
void IList.Insert(int index, object keyFrame)
{
Insert(index, (Vector3DKeyFrame)keyFrame);
}
/// <summary>
/// Inserts a Vector3DKeyFrame into a specific location in the collection.
/// </summary>
public void Insert(int index, Vector3DKeyFrame keyFrame)
{
if (keyFrame == null)
{
throw new ArgumentNullException("keyFrame");
}
WritePreamble();
OnFreezablePropertyChanged(null, keyFrame);
_keyFrames.Insert(index, keyFrame);
WritePostscript();
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsFixedSize
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Returns true if the collection is frozen.
/// </summary>
public bool IsReadOnly
{
get
{
ReadPreamble();
return IsFrozen;
}
}
/// <summary>
/// Removes a Vector3DKeyFrame from the collection.
/// </summary>
void IList.Remove(object keyFrame)
{
Remove((Vector3DKeyFrame)keyFrame);
}
/// <summary>
/// Removes a Vector3DKeyFrame from the collection.
/// </summary>
public void Remove(Vector3DKeyFrame keyFrame)
{
WritePreamble();
if (_keyFrames.Contains(keyFrame))
{
OnFreezablePropertyChanged(keyFrame, null);
_keyFrames.Remove(keyFrame);
WritePostscript();
}
}
/// <summary>
/// Removes the Vector3DKeyFrame at the specified index from the collection.
/// </summary>
public void RemoveAt(int index)
{
WritePreamble();
OnFreezablePropertyChanged(_keyFrames[index], null);
_keyFrames.RemoveAt(index);
WritePostscript();
}
/// <summary>
/// Gets or sets the Vector3DKeyFrame at a given index.
/// </summary>
object IList.this[int index]
{
get
{
return this[index];
}
set
{
this[index] = (Vector3DKeyFrame)value;
}
}
/// <summary>
/// Gets or sets the Vector3DKeyFrame at a given index.
/// </summary>
public Vector3DKeyFrame this[int index]
{
get
{
ReadPreamble();
return _keyFrames[index];
}
set
{
if (value == null)
{
throw new ArgumentNullException(String.Format(CultureInfo.InvariantCulture, "Vector3DKeyFrameCollection[{0}]", index));
}
WritePreamble();
if (value != _keyFrames[index])
{
OnFreezablePropertyChanged(_keyFrames[index], value);
_keyFrames[index] = value;
Debug.Assert(_keyFrames[index] != null);
WritePostscript();
}
}
}
#endregion
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Globalization;
namespace Microsoft.PythonTools.Parsing {
/// <summary>
/// Represents a location in source code.
/// </summary>
[Serializable]
public struct SourceLocation {
// TODO: remove index
private readonly int _index;
private readonly int _line;
private readonly int _column;
/// <summary>
/// Creates a new source location.
/// </summary>
/// <param name="index">The index in the source stream the location represents (0-based).</param>
/// <param name="line">The line in the source stream the location represents (1-based).</param>
/// <param name="column">The column in the source stream the location represents (1-based).</param>
public SourceLocation(int index, int line, int column) {
ValidateLocation(index, line, column);
_index = index;
_line = line;
_column = column;
}
private static void ValidateLocation(int index, int line, int column) {
if (index < 0) {
throw ErrorOutOfRange("index", 0);
}
if (line < 1) {
throw ErrorOutOfRange("line", 1);
}
if (column < 1) {
throw ErrorOutOfRange("column", 1);
}
}
private static Exception ErrorOutOfRange(object p0, object p1) {
return new ArgumentOutOfRangeException(string.Format("{0} must be greater than or equal to {1}", p0, p1));
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters")]
private SourceLocation(int index, int line, int column, bool noChecks) {
_index = index;
_line = line;
_column = column;
}
/// <summary>
/// The index in the source stream the location represents (0-based).
/// </summary>
public int Index {
get { return _index; }
}
/// <summary>
/// The line in the source stream the location represents (1-based).
/// </summary>
public int Line {
get { return _line; }
}
/// <summary>
/// The column in the source stream the location represents (1-based).
/// </summary>
public int Column {
get { return _column; }
}
/// <summary>
/// Compares two specified location values to see if they are equal.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the locations are the same, False otherwise.</returns>
public static bool operator ==(SourceLocation left, SourceLocation right) {
return left._index == right._index && left._line == right._line && left._column == right._column;
}
/// <summary>
/// Compares two specified location values to see if they are not equal.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the locations are not the same, False otherwise.</returns>
public static bool operator !=(SourceLocation left, SourceLocation right) {
return left._index != right._index || left._line != right._line || left._column != right._column;
}
/// <summary>
/// Compares two specified location values to see if one is before the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is before the other location, False otherwise.</returns>
public static bool operator <(SourceLocation left, SourceLocation right) {
return left._index < right._index;
}
/// <summary>
/// Compares two specified location values to see if one is after the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is after the other location, False otherwise.</returns>
public static bool operator >(SourceLocation left, SourceLocation right) {
return left._index > right._index;
}
/// <summary>
/// Compares two specified location values to see if one is before or the same as the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is before or the same as the other location, False otherwise.</returns>
public static bool operator <=(SourceLocation left, SourceLocation right) {
return left._index <= right._index;
}
/// <summary>
/// Compares two specified location values to see if one is after or the same as the other.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>True if the first location is after or the same as the other location, False otherwise.</returns>
public static bool operator >=(SourceLocation left, SourceLocation right) {
return left._index >= right._index;
}
/// <summary>
/// Compares two specified location values.
/// </summary>
/// <param name="left">One location to compare.</param>
/// <param name="right">The other location to compare.</param>
/// <returns>0 if the locations are equal, -1 if the left one is less than the right one, 1 otherwise.</returns>
public static int Compare(SourceLocation left, SourceLocation right) {
if (left < right) return -1;
if (left > right) return 1;
return 0;
}
/// <summary>
/// A location that is valid but represents no location at all.
/// </summary>
public static readonly SourceLocation None = new SourceLocation(0, 0xfeefee, 0, true);
/// <summary>
/// An invalid location.
/// </summary>
public static readonly SourceLocation Invalid = new SourceLocation(0, 0, 0, true);
/// <summary>
/// A minimal valid location.
/// </summary>
public static readonly SourceLocation MinValue = new SourceLocation(0, 1, 1);
/// <summary>
/// Whether the location is a valid location.
/// </summary>
/// <returns>True if the location is valid, False otherwise.</returns>
public bool IsValid {
get {
return this._line != 0 && this._column != 0;
}
}
public override bool Equals(object obj) {
if (!(obj is SourceLocation)) return false;
SourceLocation other = (SourceLocation)obj;
return other._index == _index && other._line == _line && other._column == _column;
}
public override int GetHashCode() {
return (_line << 16) ^ _column;
}
public override string ToString() {
return "(" + _line + "," + _column + ")";
}
internal string ToDebugString() {
return String.Format(CultureInfo.CurrentCulture, "({0},{1},{2})", _index, _line, _column);
}
}
}
| |
/// Copyright (C) 2012-2014 Soomla 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 UnityEngine;
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using Soomla.Singletons;
namespace Soomla.Profile {
/// <summary>
/// This class provides functions for event handling. To handle various events, just add your
/// game-specific behavior to the delegates below.
/// </summary>
public class ProfileEvents : CodeGeneratedSingleton {
private const string TAG = "SOOMLA ProfileEvents";
public static ProfileEvents Instance = null;
protected override bool DontDestroySingleton
{
get { return true; }
}
/// <summary>
/// Initializes the game state before the game starts.
/// </summary>
protected override void InitAfterRegisteringAsSingleInstance()
{
base.InitAfterRegisteringAsSingleInstance();
// now we initialize the event pusher
#if UNITY_ANDROID && !UNITY_EDITOR
pep = new ProfileEventPusherAndroid();
#elif UNITY_IOS && !UNITY_EDITOR
pep = new ProfileEventPusherIOS();
#endif
}
// private static ProfileEvents instance = null;
#pragma warning disable 414
private static ProfileEventPusher pep = null;
#pragma warning restore 414
public static void Initialize() {
if (Instance == null) {
CoreEvents.Initialize();
Instance = GetSynchronousCodeGeneratedInstance<ProfileEvents>();
SoomlaUtils.LogDebug (TAG, "Initializing ProfileEvents ...");
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJNI.PushLocalFrame(100);
//init ProfileEventHandler
using(AndroidJavaClass jniEventHandler = new AndroidJavaClass("com.soomla.profile.unity.ProfileEventHandler")) {
jniEventHandler.CallStatic("initialize");
}
AndroidJNI.PopLocalFrame(IntPtr.Zero);
#elif UNITY_IOS && !UNITY_EDITOR
// On iOS, this is initialized inside the bridge library when we call "soomlaProfile_Initialize" in SoomlaProfileIOS
#endif
}
}
/// <summary>
/// Handles an <c>onSoomlaProfileInitialized</c> event, which is fired when SoomlaProfile
/// has been initialzed
/// </summary>
public void onSoomlaProfileInitialized()
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSoomlaProfileInitialized");
SoomlaProfile.nativeModulesInitialized = true;
SoomlaProfile.TryFireProfileInitialized();
}
/// <summary>
/// Handles an <c>onUserRatingEvent</c> event
/// </summary>
public void onUserRatingEvent()
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserRatingEvent");
ProfileEvents.OnUserRatingEvent ();
//ProfileEvents.OnUserRatingEvent (new UserRatingEvent());
}
/// <summary>
/// Handles an <c>onUserProfileUpdated</c> event
/// </summary>
/// <param name="message">Will contain a JSON representation of a <c>UserProfile</c></param>
public void onUserProfileUpdated(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onUserProfileUpdated");
JSONObject eventJson = new JSONObject(message);
UserProfile userProfile = new UserProfile (eventJson ["userProfile"]);
ProfileEvents.OnUserProfileUpdated (userProfile);
//ProfileEvents.OnUserProfileUpdated (new UserProfileUpdatedEvent(userProfile));
}
/// <summary>
/// Handles an <c>onLoginStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// as well as payload </param>
public void onLoginStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt((int)(eventJson["provider"].n));
bool autoLogin = eventJson["autoLogin"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
string payload = ProfilePayload.GetUserPayload(payloadJSON);
ProfileEvents.OnLoginStarted(provider, autoLogin, payload);
//ProfileEvents.OnLoginStarted(new LoginStartedEvent(provider, autoLogin, payload));
}
/// <summary>
/// Handles an <c>onLoginFinished</c> event
/// </summary>
/// <param name="message">Will contain a JSON representation of a <c>UserProfile</c> and payload</param>
public void onLoginFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFinished");
JSONObject eventJson = new JSONObject(message);
UserProfile userProfile = new UserProfile (eventJson ["userProfile"]);
bool autoLogin = eventJson["autoLogin"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
//give a reward
Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON));
if (reward !=null)
reward.Give();
ProfileEvents.OnLoginFinished(userProfile, autoLogin, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnLoginFinished(new LoginFinishedEvent(userProfile, autoLogin, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onLoginCancelled</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// as well as payload </param>
public void onLoginCancelled(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginCancelled");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt((int)(eventJson["provider"].n));
bool autoLogin = eventJson["autoLogin"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnLoginCancelled (provider, autoLogin, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnLoginCancelled (new LoginCancelledEvent(provider, autoLogin, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onLoginFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// ,error message and payload </param>
public void onLoginFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLoginFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt((int)(eventJson["provider"].n));
String errorMessage = eventJson["message"].str;
bool autoLogin = eventJson["autoLogin"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnLoginFailed(provider, errorMessage, autoLogin, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnLoginFailed(new LoginFailedEvent(provider, errorMessage, autoLogin, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onLogoutStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c></param>
public void onLogoutStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)(eventJson["provider"].n));
ProfileEvents.OnLogoutStarted (provider);
//ProfileEvents.OnLogoutStarted (new LogoutStartedEvent(provider));
}
/// <summary>
/// Handles an <c>onLogoutFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c></param>
public void onLogoutFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)(eventJson["provider"].n));
ProfileEvents.OnLogoutFinished(provider);
//ProfileEvents.OnLogoutFinished(new LogoutFinishedEvent(provider));
}
/// <summary>
/// Handles an <c>onLogoutFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// and payload</param>
public void onLogoutFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onLogoutFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)(eventJson["provider"].n));
String errorMessage = eventJson["message"].str;
ProfileEvents.OnLogoutFailed (provider, errorMessage);
//ProfileEvents.OnLogoutFailed (new LogoutFailedEvent(provider, errorMessage));
}
/// <summary>
/// Handles an <c>onSocialActionStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c> and payload</param>
public void onSocialActionStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)(eventJson["provider"].n));
SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSocialActionStarted (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnSocialActionStarted (new SocialActionStartedEvent(provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSocialActionFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c> and payload</param>
public void onSocialActionFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
//give a reward
Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON));
if (reward != null)
reward.Give();
ProfileEvents.OnSocialActionFinished (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnSocialActionFinished (new SocialActionFinishedEvent(provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSocialActionCancelled</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c> and payload</param>
public void onSocialActionCancelled(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionCancelled");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSocialActionCancelled (provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnSocialActionCancelled (new SocialActionCancelledEvent(provider, socialAction, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSocialActionFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c>,
/// error message and payload</param>
public void onSocialActionFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSocialActionFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
SocialActionType socialAction = SocialActionType.fromInt ((int)eventJson["socialActionType"].n);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSocialActionFailed (provider, socialAction, errorMessage, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnSocialActionFailed (new SocialActionFailedEvent(provider, socialAction, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetContactsStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetContactsStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
bool fromStart = eventJson["fromStart"].b;
ProfileEvents.OnGetContactsStarted (provider, fromStart, ProfilePayload.GetUserPayload (payloadJSON));
//ProfileEvents.OnGetContactsStarted (new GetContactsStartedEvent(provider, fromStart, ProfilePayload.GetUserPayload (payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetContactsFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// JSON array of <c>UserProfile</c>s and payload</param>
public void onGetContactsFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
bool hasMore = eventJson["hasMore"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
JSONObject userProfilesArray = eventJson ["contacts"];
List<UserProfile> userProfiles = new List<UserProfile>();
foreach (JSONObject userProfileJson in userProfilesArray.list) {
userProfiles.Add(new UserProfile(userProfileJson));
}
SocialPageData<UserProfile> data = new SocialPageData<UserProfile>();
data.PageData = userProfiles;
data.PageNumber = 0;
data.HasMore = hasMore;
ProfileEvents.OnGetContactsFinished(provider, data, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnGetContactsFinished(new GetContactsFinishedEvent(provider, data, ProfilePayload.GetUserPayload(payloadJSON)) );
}
/// <summary>
/// Handles an <c>onGetContactsFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// error message payload</param>
public void onGetContactsFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetContactsFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
bool fromStart = eventJson["fromStart"].b;
ProfileEvents.OnGetContactsFailed (provider, errorMessage, fromStart, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnGetContactsFailed (new GetContactsFailedEvent(provider, errorMessage, fromStart, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetFeedStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetFeedStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
ProfileEvents.OnGetFeedStarted (provider);
//ProfileEvents.OnGetFeedStarted (new GetFeedStartedEvent(provider));
}
/// <summary>
/// Handles an <c>onGetFeedFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// json array of feeds</param>
public void onGetFeedFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject feedsJson = eventJson ["feeds"];
List<String> feeds = new List<String>();
foreach (JSONObject feedVal in feedsJson.list) {
//iterate "feed" keys
feeds.Add(feedVal.str);
}
bool hasMore = eventJson["hasMore"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
SocialPageData<String> result = new SocialPageData<String>();
result.PageData = feeds;
result.PageNumber = 0;
result.HasMore = hasMore;
ProfileEvents.OnGetFeedFinished (provider, result);
//ProfileEvents.OnGetFeedFinished (new GetFeedFinishedEvent(provider, result));
}
/// <summary>
/// Handles an <c>onGetFeedFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and an error message</param>
public void onGetFeedFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetFeedFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
String errorMessage = eventJson["message"].str;
ProfileEvents.OnGetFeedFailed (provider, errorMessage);
//ProfileEvents.OnGetFeedFailed (new GetFeedFailedEvent(provider, errorMessage));
}
/// <summary>
/// Handles an <c>onInviteStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c> and payload</param>
public void onInviteStarted(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onInviteStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)(eventJson["provider"].n));
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnInviteStarted (provider, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnInviteStarted (new InviteStartedEvent(provider, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onInviteFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c>
/// id of given request, list of invite recipients
/// and payload</param>
public void onInviteFinished(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onInviteFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
String requestId = eventJson["requestId"].str;
JSONObject recipientsJson = eventJson ["invitedIds"];
List<String> recipients = new List<String>();
foreach (JSONObject recipientVal in recipientsJson.list) {
//iterate "feed" keys
recipients.Add(recipientVal.str);
}
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
//give a reward
Reward reward = Reward.GetReward(ProfilePayload.GetRewardId(payloadJSON));
if (reward != null)
reward.Give();
ProfileEvents.OnInviteFinished (provider, requestId, recipients, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnInviteFinished (new InviteFinishedEvent(provider, requestId, recipients, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onInviteCancelled</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c> and payload</param>
public void onInviteCancelled(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onInviteCancelled");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnInviteCancelled (provider, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnInviteCancelled (new InviteCancelledEvent(provider, ProfilePayload.GetUserPayload(payloadJSON) ) );
}
/// <summary>
/// Handles an <c>onInviteFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// numeric representation of <c>SocialActionType</c>,
/// error message and payload</param>
public void onInviteFailed(String message)
{
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onInviteFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnInviteFailed (provider, errorMessage, ProfilePayload.GetUserPayload(payloadJSON));
//ProfileEvents.OnInviteFailed (new InviteFailedEvent(provider, errorMessage, ProfilePayload.GetUserPayload(payloadJSON) ) );
}
/// <summary>
/// Handles an <c>onGetLeaderboardsStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetLeaderboardsStarted(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetLeaderboardsStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnGetLeaderboardsStarted(new GetLeaderboardsStartedEvent(provider, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetLeaderboardsFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetLeaderboardsFinished(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetLeaderboardsFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
JSONObject leaderboardsArray = eventJson ["leaderboards"];
List<Leaderboard> leaderboards = new List<Leaderboard>();
foreach (JSONObject leaderboardJson in leaderboardsArray.list) {
leaderboards.Add(new Leaderboard(leaderboardJson));
}
SocialPageData<Leaderboard> data = new SocialPageData<Leaderboard>();
data.PageData = leaderboards;
data.PageNumber = 0;
data.HasMore = false;
ProfileEvents.OnGetLeaderboardsFinished(new GetLeaderboardsFinishedEvent(provider, data, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetLeaderboardsFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetLeaderboardsFailed(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetLeaderboardsFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnGetLeaderboardsFailed(new GetLeaderboardsFailedEvent(provider, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetScoresStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetScoresStarted(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetScoresStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
bool fromStart = eventJson["fromStart"].b;
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnGetScoresStarted(new GetScoresStartedEvent(provider, owner, fromStart, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetScoresFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetScoresFinished(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetScoresFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
bool hasMore = eventJson["hasMore"].b;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
JSONObject scoresArray = eventJson ["scores"];
List<Score> scores = new List<Score>();
foreach (JSONObject scoreJson in scoresArray.list) {
scores.Add(new Score(scoreJson));
}
SocialPageData<Score> data = new SocialPageData<Score>();
data.PageData = scores;
data.PageNumber = 0;
data.HasMore = hasMore;
ProfileEvents.OnGetScoresFinished(new GetScoresFinishedEvent(provider, owner, data, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onGetScoresFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onGetScoresFailed(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onGetScoresFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
bool fromStart = eventJson["fromStart"].b;
ProfileEvents.OnGetScoresFailed(new GetScoresFailedEvent(provider, owner, fromStart, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSubmitScoreStarted</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onSubmitScoreStarted(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSubmitScoreStarted");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSubmitScoreStarted(new SubmitScoreStartedEvent(provider, owner, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSubmitScoreFinished</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onSubmitScoreFinished(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSubmitScoreFinished");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
Score score = new Score(eventJson["score"]);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSubmitScoreFinished(new SubmitScoreFinishedEvent(provider, owner, score, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onSubmitScoreFailed</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>,
/// and payload</param>
public void onSubmitScoreFailed(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onSubmitScoreFailed");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
Leaderboard owner = new Leaderboard(eventJson["leaderboard"]);
String errorMessage = eventJson["message"].str;
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnSubmitScoreFailed(new SubmitScoreFailedEvent(provider, owner, errorMessage, ProfilePayload.GetUserPayload(payloadJSON)));
}
/// <summary>
/// Handles an <c>onShowLeaderboards</c> event
/// </summary>
/// <param name="message">
/// Will contain a numeric representation of <c>Provider</c>
/// </param>
public void onShowLeaderboards(String message) {
SoomlaUtils.LogDebug(TAG, "SOOMLA/UNITY onShowLeaderboards");
JSONObject eventJson = new JSONObject(message);
Provider provider = Provider.fromInt ((int)eventJson["provider"].n);
JSONObject payloadJSON = new JSONObject(eventJson ["payload"].str);
ProfileEvents.OnShowLeaderboards(new ShowLeaderboardsEvent(provider, ProfilePayload.GetUserPayload(payloadJSON)));
}
public delegate void Action();
public delegate void Action<T1, T2, T3, T4, T5>(T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5);
public static Action OnSoomlaProfileInitialized = delegate {};
//public static Action<ProfileInitializedEvent> OnSoomlaProfileInitialized = delegate {};
public static Action OnUserRatingEvent =delegate {};
//public static Action<UserRatingEvent> OnUserRatingEvent =delegate {};
public static Action<UserProfile> OnUserProfileUpdated = delegate {};
//public static Action<UserProfileUpdatedEvent> OnUserProfileUpdated = delegate {};
public static Action<Provider, string, bool, string> OnLoginFailed = delegate {};
//public static Action<LoginFailedEvent> OnLoginFailed = delegate {};
public static Action<UserProfile, bool, string> OnLoginFinished = delegate {};
//public static Action<LoginFinishedEvent> OnLoginFinished = delegate {};
public static Action<Provider, bool, string> OnLoginStarted = delegate {};
//public static Action<LoginStartedEvent> OnLoginStarted = delegate {};
public static Action<Provider, bool, string> OnLoginCancelled = delegate {};
//public static Action<LoginCancelledEvent> OnLoginCancelled = delegate {};
public static Action<Provider, string> OnLogoutFailed = delegate {};
//public static Action<LogoutFailedEvent> OnLogoutFailed = delegate {};
public static Action<Provider> OnLogoutFinished = delegate {};
//public static Action<LogoutFinishedEvent> OnLogoutFinished = delegate {};
public static Action<Provider> OnLogoutStarted = delegate {};
//public static Action<LogoutStartedEvent> OnLogoutStarted = delegate {};
public static Action<Provider, SocialActionType, string, string> OnSocialActionFailed = delegate {};
//public static Action<SocialActionFailedEvent> OnSocialActionFailed = delegate {};
public static Action<Provider, SocialActionType, string> OnSocialActionFinished = delegate {};
//public static Action<SocialActionFinishedEvent> OnSocialActionFinished = delegate {};
public static Action<Provider, SocialActionType, string> OnSocialActionStarted = delegate {};
//public static Action<SocialActionStartedEvent> OnSocialActionStarted = delegate {};
public static Action<Provider, SocialActionType, string> OnSocialActionCancelled = delegate {};
//public static Action<SocialActionCancelledEvent> OnSocialActionCancelled = delegate {};
public static Action<Provider, string, bool, string> OnGetContactsFailed = delegate {};
//public static Action<GetContactsFailedEvent> OnGetContactsFailed = delegate {};
public static Action<Provider, SocialPageData<UserProfile>, string> OnGetContactsFinished = delegate {};
//public static Action<GetContactsFinishedEvent> OnGetContactsFinished = delegate {};
public static Action<Provider, bool, string> OnGetContactsStarted = delegate {};
//public static Action<GetContactsStartedEvent> OnGetContactsStarted = delegate {};
public static Action<Provider, string> OnGetFeedFailed = delegate {};
//public static Action<GetFeedFailedEvent> OnGetFeedFailed = delegate {};
public static Action<Provider, SocialPageData<String>> OnGetFeedFinished = delegate {};
//public static Action<GetFeedFinishedEvent> OnGetFeedFinished = delegate {};
public static Action<Provider> OnGetFeedStarted = delegate {};
//public static Action<GetFeedStartedEvent> OnGetFeedStarted = delegate {};
public static Action<Provider> OnAddAppRequestStarted = delegate {};
//public static Action<AddAppRequestStartedEvent> OnAddAppRequestStarted = delegate {};
public static Action<Provider, string> OnAddAppRequestFinished = delegate {};
//public static Action<AddAppRequestFinishedEvent> OnAddAppRequestFinished = delegate {};
public static Action<Provider, string> OnAddAppRequestFailed = delegate {};
//public static Action<AddAppRequestFailedEvent> OnAddAppRequestFailed = delegate {};
public static Action<Provider, string> OnInviteStarted = delegate {};
//public static Action<InviteStartedEvent> OnInviteStarted = delegate {};
public static Action<Provider, string, List<string>, string> OnInviteFinished = delegate {};
//public static Action<InviteFinishedEvent> OnInviteFinished = delegate {};
public static Action<Provider, string, string> OnInviteFailed = delegate {};
//public static Action<InviteFailedEvent> OnInviteFailed = delegate {};
public static Action<Provider, string> OnInviteCancelled = delegate {};
//public static Action<InviteCancelledEvent> OnInviteCancelled = delegate {};
public static Action<GetLeaderboardsStartedEvent> OnGetLeaderboardsStarted = delegate {};
public static Action<GetLeaderboardsFinishedEvent> OnGetLeaderboardsFinished = delegate {};
public static Action<GetLeaderboardsFailedEvent> OnGetLeaderboardsFailed = delegate {};
public static Action<GetScoresStartedEvent> OnGetScoresStarted = delegate {};
public static Action<GetScoresFinishedEvent> OnGetScoresFinished = delegate {};
public static Action<GetScoresFailedEvent> OnGetScoresFailed = delegate {};
public static Action<SubmitScoreStartedEvent> OnSubmitScoreStarted = delegate {};
public static Action<SubmitScoreFinishedEvent> OnSubmitScoreFinished = delegate {};
public static Action<SubmitScoreFailedEvent> OnSubmitScoreFailed = delegate {};
public static Action<ShowLeaderboardsEvent> OnShowLeaderboards = delegate {};
public class ProfileEventPusher {
/// <summary>
/// Registers all events.
/// </summary>
public ProfileEventPusher() {
ProfileEvents.OnLoginCancelled += _pushEventLoginCancelled;
ProfileEvents.OnLoginFailed += _pushEventLoginFailed;
ProfileEvents.OnLoginFinished += _pushEventLoginFinished;
ProfileEvents.OnLoginStarted += _pushEventLoginStarted;
ProfileEvents.OnLogoutFailed += _pushEventLogoutFailed;
ProfileEvents.OnLogoutFinished += _pushEventLogoutFinished;
ProfileEvents.OnLogoutStarted += _pushEventLogoutStarted;
ProfileEvents.OnSocialActionCancelled += _pushEventSocialActionCancelled;
ProfileEvents.OnSocialActionFailed += _pushEventSocialActionFailed;
ProfileEvents.OnSocialActionFinished += _pushEventSocialActionFinished;
ProfileEvents.OnSocialActionStarted += _pushEventSocialActionStarted;
ProfileEvents.OnGetContactsStarted += _pushEventGetContactsStarted;
ProfileEvents.OnGetContactsFinished += _pushEventGetContactsFinished;
ProfileEvents.OnGetContactsFailed += _pushEventGetContactsFailed;
ProfileEvents.OnInviteStarted += _pushEventInviteStarted;
ProfileEvents.OnInviteFinished += _pushEventInviteFinished;
ProfileEvents.OnInviteFailed += _pushEventInviteFailed;
ProfileEvents.OnInviteCancelled += _pushEventInviteCancelled;
ProfileEvents.OnGetLeaderboardsStarted += _pushEventGetLeaderboardsStarted;
ProfileEvents.OnGetLeaderboardsFinished += _pushEventGetLeaderboardsFinished;
ProfileEvents.OnGetLeaderboardsFailed += _pushEventGetLeaderboardsFailed;
ProfileEvents.OnGetScoresStarted += _pushEventGetScoresStarted;
ProfileEvents.OnGetScoresFinished += _pushEventGetScoresFinished;
ProfileEvents.OnGetScoresFailed += _pushEventGetScoresFailed;
ProfileEvents.OnSubmitScoreStarted += _pushEventSubmitScoreStarted;
ProfileEvents.OnSubmitScoreFinished += _pushEventSubmitScoreFinished;
ProfileEvents.OnSubmitScoreFailed += _pushEventSubmitScoreFailed;
ProfileEvents.OnShowLeaderboards += _pushEventShowLeaderboards;
}
// Event pushing back to native (when using FB Unity SDK)
/*
protected virtual void _pushEventLoginStarted(LoginStartedEvent e) {}
protected virtual void _pushEventLoginFinished(LoginFinishedEvent e){}
protected virtual void _pushEventLoginFailed(LoginFailedEvent e){}
protected virtual void _pushEventLoginCancelled(LoginCancelledEvent e){}
protected virtual void _pushEventLogoutStarted(LogoutStartedEvent e){}
protected virtual void _pushEventLogoutFinished(LogoutFinishedEvent e){}
protected virtual void _pushEventLogoutFailed(LogoutFailedEvent e){}
protected virtual void _pushEventSocialActionStarted(SocialActionStartedEvent e){}
protected virtual void _pushEventSocialActionFinished(SocialActionFinishedEvent e){}
protected virtual void _pushEventSocialActionCancelled(SocialActionCancelledEvent e){}
protected virtual void _pushEventSocialActionFailed(SocialActionFailedEvent e){}
protected virtual void _pushEventGetContactsStarted(GetContactsStartedEvent e){}
protected virtual void _pushEventGetContactsFinished(GetContactsFinishedEvent e){}
protected virtual void _pushEventGetContactsFailed(GetContactsFailedEvent e){}
protected virtual void _pushEventGetFeedFinished(GetFeedFinishedEvent e) {}
protected virtual void _pushEventGetFeedFailed(GetFeedFailedEvent e) {}
protected virtual void _pushEventInviteStarted(InviteStartedEvent e){}
protected virtual void _pushEventInviteFinished(InviteFinishedEvent e){}
protected virtual void _pushEventInviteFailed(InviteFailedEvent e){}
protected virtual void _pushEventInviteCancelled(InviteCancelledEvent e){}
*/
protected virtual void _pushEventLoginStarted(Provider provider, bool autoLogin, string payload) {}
protected virtual void _pushEventLoginFinished(UserProfile userProfileJson, bool autoLogin, string payload){}
protected virtual void _pushEventLoginFailed(Provider provider, string message, bool autoLogin, string payload){}
protected virtual void _pushEventLoginCancelled(Provider provider, bool autoLogin, string payload){}
protected virtual void _pushEventLogoutStarted(Provider provider){}
protected virtual void _pushEventLogoutFinished(Provider provider){}
protected virtual void _pushEventLogoutFailed(Provider provider, string message){}
protected virtual void _pushEventSocialActionStarted(Provider provider, SocialActionType actionType, string payload){}
protected virtual void _pushEventSocialActionFinished(Provider provider, SocialActionType actionType, string payload){}
protected virtual void _pushEventSocialActionCancelled(Provider provider, SocialActionType actionType, string payload){}
protected virtual void _pushEventSocialActionFailed(Provider provider, SocialActionType actionType, string message, string payload){}
protected virtual void _pushEventGetContactsStarted(Provider provider, bool fromStart, string payload){}
protected virtual void _pushEventGetContactsFinished(Provider provider, SocialPageData<UserProfile> contactsPage, string payload){}
protected virtual void _pushEventGetContactsFailed(Provider provider, string message, bool fromStart, string payload){}
protected virtual void _pushEventGetFeedFinished(Provider provider, SocialPageData<String> feedPage, string payload) {}
protected virtual void _pushEventGetFeedFailed(Provider provider, string message, bool fromStart, string payload) {}
protected virtual void _pushEventInviteStarted(Provider provider, string payload){}
protected virtual void _pushEventInviteFinished(Provider provider, string requestId, List<string> invitedIds, string payload){}
protected virtual void _pushEventInviteFailed(Provider provider, string message, string payload){}
protected virtual void _pushEventInviteCancelled(Provider provider, string payload){}
protected virtual void _pushEventGetLeaderboardsStarted(GetLeaderboardsStartedEvent getLeaderboardsStartedEvent) {}
protected virtual void _pushEventGetLeaderboardsFinished(GetLeaderboardsFinishedEvent getLeaderboardsFinishedEvent) {}
protected virtual void _pushEventGetLeaderboardsFailed(GetLeaderboardsFailedEvent getLeaderboardsFailedEvent) {}
protected virtual void _pushEventGetScoresStarted(GetScoresStartedEvent getScoresStartedEvent) {}
protected virtual void _pushEventGetScoresFinished(GetScoresFinishedEvent getScoresFinishedEvent) {}
protected virtual void _pushEventGetScoresFailed(GetScoresFailedEvent getScoresFailedEvent) {}
protected virtual void _pushEventSubmitScoreStarted(SubmitScoreStartedEvent submitScoreStartedEvent) {}
protected virtual void _pushEventSubmitScoreFinished(SubmitScoreFinishedEvent submitScoreFinishedEvent) {}
protected virtual void _pushEventSubmitScoreFailed(SubmitScoreFailedEvent submitScoreFailedEvent) {}
protected virtual void _pushEventShowLeaderboards(ShowLeaderboardsEvent showLeaderboardsEvent) {}
}
}
}
| |
// Copyright 2018 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
using linq = System.Linq;
namespace Google.Cloud.Kms.V1
{
/// <summary>
/// Resource name for the 'key_ring' resource.
/// </summary>
public sealed partial class KeyRingName : gax::IResourceName, sys::IEquatable<KeyRingName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}");
/// <summary>
/// Parses the given key_ring resource name in string form into a new
/// <see cref="KeyRingName"/> instance.
/// </summary>
/// <param name="keyRingName">The key_ring resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="KeyRingName"/> if successful.</returns>
public static KeyRingName Parse(string keyRingName)
{
gax::GaxPreconditions.CheckNotNull(keyRingName, nameof(keyRingName));
gax::TemplatedResourceName resourceName = s_template.ParseName(keyRingName);
return new KeyRingName(resourceName[0], resourceName[1], resourceName[2]);
}
/// <summary>
/// Tries to parse the given key_ring resource name in string form into a new
/// <see cref="KeyRingName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="keyRingName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="keyRingName">The key_ring resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="KeyRingName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string keyRingName, out KeyRingName result)
{
gax::GaxPreconditions.CheckNotNull(keyRingName, nameof(keyRingName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(keyRingName, out resourceName))
{
result = new KeyRingName(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="KeyRingName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
/// <param name="keyRingId">The keyRing ID. Must not be <c>null</c>.</param>
public KeyRingName(string projectId, string locationId, string keyRingId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
KeyRingId = gax::GaxPreconditions.CheckNotNull(keyRingId, nameof(keyRingId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The keyRing ID. Never <c>null</c>.
/// </summary>
public string KeyRingId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId, KeyRingId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as KeyRingName);
/// <inheritdoc />
public bool Equals(KeyRingName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(KeyRingName a, KeyRingName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(KeyRingName a, KeyRingName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'crypto_key_path' resource.
/// </summary>
public sealed partial class CryptoKeyPathName : gax::IResourceName, sys::IEquatable<CryptoKeyPathName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key_path=**}");
/// <summary>
/// Parses the given crypto_key_path resource name in string form into a new
/// <see cref="CryptoKeyPathName"/> instance.
/// </summary>
/// <param name="cryptoKeyPathName">The crypto_key_path resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CryptoKeyPathName"/> if successful.</returns>
public static CryptoKeyPathName Parse(string cryptoKeyPathName)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyPathName, nameof(cryptoKeyPathName));
gax::TemplatedResourceName resourceName = s_template.ParseName(cryptoKeyPathName);
return new CryptoKeyPathName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
}
/// <summary>
/// Tries to parse the given crypto_key_path resource name in string form into a new
/// <see cref="CryptoKeyPathName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="cryptoKeyPathName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="cryptoKeyPathName">The crypto_key_path resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="CryptoKeyPathName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cryptoKeyPathName, out CryptoKeyPathName result)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyPathName, nameof(cryptoKeyPathName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(cryptoKeyPathName, out resourceName))
{
result = new CryptoKeyPathName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="CryptoKeyPathName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
/// <param name="keyRingId">The keyRing ID. Must not be <c>null</c>.</param>
/// <param name="cryptoKeyPathId">The cryptoKeyPath ID. Must not be <c>null</c>.</param>
public CryptoKeyPathName(string projectId, string locationId, string keyRingId, string cryptoKeyPathId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
KeyRingId = gax::GaxPreconditions.CheckNotNull(keyRingId, nameof(keyRingId));
CryptoKeyPathId = gax::GaxPreconditions.CheckNotNull(cryptoKeyPathId, nameof(cryptoKeyPathId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The keyRing ID. Never <c>null</c>.
/// </summary>
public string KeyRingId { get; }
/// <summary>
/// The cryptoKeyPath ID. Never <c>null</c>.
/// </summary>
public string CryptoKeyPathId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId, KeyRingId, CryptoKeyPathId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as CryptoKeyPathName);
/// <inheritdoc />
public bool Equals(CryptoKeyPathName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(CryptoKeyPathName a, CryptoKeyPathName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(CryptoKeyPathName a, CryptoKeyPathName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'location' resource.
/// </summary>
public sealed partial class LocationName : gax::IResourceName, sys::IEquatable<LocationName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}");
/// <summary>
/// Parses the given location resource name in string form into a new
/// <see cref="LocationName"/> instance.
/// </summary>
/// <param name="locationName">The location resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="LocationName"/> if successful.</returns>
public static LocationName Parse(string locationName)
{
gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName));
gax::TemplatedResourceName resourceName = s_template.ParseName(locationName);
return new LocationName(resourceName[0], resourceName[1]);
}
/// <summary>
/// Tries to parse the given location resource name in string form into a new
/// <see cref="LocationName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="locationName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="locationName">The location resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="LocationName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string locationName, out LocationName result)
{
gax::GaxPreconditions.CheckNotNull(locationName, nameof(locationName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(locationName, out resourceName))
{
result = new LocationName(resourceName[0], resourceName[1]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="LocationName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
public LocationName(string projectId, string locationId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as LocationName);
/// <inheritdoc />
public bool Equals(LocationName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(LocationName a, LocationName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(LocationName a, LocationName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'crypto_key' resource.
/// </summary>
public sealed partial class CryptoKeyName : gax::IResourceName, sys::IEquatable<CryptoKeyName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}");
/// <summary>
/// Parses the given crypto_key resource name in string form into a new
/// <see cref="CryptoKeyName"/> instance.
/// </summary>
/// <param name="cryptoKeyName">The crypto_key resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CryptoKeyName"/> if successful.</returns>
public static CryptoKeyName Parse(string cryptoKeyName)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyName, nameof(cryptoKeyName));
gax::TemplatedResourceName resourceName = s_template.ParseName(cryptoKeyName);
return new CryptoKeyName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
}
/// <summary>
/// Tries to parse the given crypto_key resource name in string form into a new
/// <see cref="CryptoKeyName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="cryptoKeyName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="cryptoKeyName">The crypto_key resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="CryptoKeyName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cryptoKeyName, out CryptoKeyName result)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyName, nameof(cryptoKeyName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(cryptoKeyName, out resourceName))
{
result = new CryptoKeyName(resourceName[0], resourceName[1], resourceName[2], resourceName[3]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="CryptoKeyName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
/// <param name="keyRingId">The keyRing ID. Must not be <c>null</c>.</param>
/// <param name="cryptoKeyId">The cryptoKey ID. Must not be <c>null</c>.</param>
public CryptoKeyName(string projectId, string locationId, string keyRingId, string cryptoKeyId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
KeyRingId = gax::GaxPreconditions.CheckNotNull(keyRingId, nameof(keyRingId));
CryptoKeyId = gax::GaxPreconditions.CheckNotNull(cryptoKeyId, nameof(cryptoKeyId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The keyRing ID. Never <c>null</c>.
/// </summary>
public string KeyRingId { get; }
/// <summary>
/// The cryptoKey ID. Never <c>null</c>.
/// </summary>
public string CryptoKeyId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId, KeyRingId, CryptoKeyId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as CryptoKeyName);
/// <inheritdoc />
public bool Equals(CryptoKeyName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(CryptoKeyName a, CryptoKeyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(CryptoKeyName a, CryptoKeyName b) => !(a == b);
}
/// <summary>
/// Resource name for the 'crypto_key_version' resource.
/// </summary>
public sealed partial class CryptoKeyVersionName : gax::IResourceName, sys::IEquatable<CryptoKeyVersionName>
{
private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}/cryptoKeyVersions/{crypto_key_version}");
/// <summary>
/// Parses the given crypto_key_version resource name in string form into a new
/// <see cref="CryptoKeyVersionName"/> instance.
/// </summary>
/// <param name="cryptoKeyVersionName">The crypto_key_version resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CryptoKeyVersionName"/> if successful.</returns>
public static CryptoKeyVersionName Parse(string cryptoKeyVersionName)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyVersionName, nameof(cryptoKeyVersionName));
gax::TemplatedResourceName resourceName = s_template.ParseName(cryptoKeyVersionName);
return new CryptoKeyVersionName(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
}
/// <summary>
/// Tries to parse the given crypto_key_version resource name in string form into a new
/// <see cref="CryptoKeyVersionName"/> instance.
/// </summary>
/// <remarks>
/// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="cryptoKeyVersionName"/> is null,
/// as this would usually indicate a programming error rather than a data error.
/// </remarks>
/// <param name="cryptoKeyVersionName">The crypto_key_version resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">When this method returns, the parsed <see cref="CryptoKeyVersionName"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string cryptoKeyVersionName, out CryptoKeyVersionName result)
{
gax::GaxPreconditions.CheckNotNull(cryptoKeyVersionName, nameof(cryptoKeyVersionName));
gax::TemplatedResourceName resourceName;
if (s_template.TryParseName(cryptoKeyVersionName, out resourceName))
{
result = new CryptoKeyVersionName(resourceName[0], resourceName[1], resourceName[2], resourceName[3], resourceName[4]);
return true;
}
else
{
result = null;
return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="CryptoKeyVersionName"/> resource name class
/// from its component parts.
/// </summary>
/// <param name="projectId">The project ID. Must not be <c>null</c>.</param>
/// <param name="locationId">The location ID. Must not be <c>null</c>.</param>
/// <param name="keyRingId">The keyRing ID. Must not be <c>null</c>.</param>
/// <param name="cryptoKeyId">The cryptoKey ID. Must not be <c>null</c>.</param>
/// <param name="cryptoKeyVersionId">The cryptoKeyVersion ID. Must not be <c>null</c>.</param>
public CryptoKeyVersionName(string projectId, string locationId, string keyRingId, string cryptoKeyId, string cryptoKeyVersionId)
{
ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId));
LocationId = gax::GaxPreconditions.CheckNotNull(locationId, nameof(locationId));
KeyRingId = gax::GaxPreconditions.CheckNotNull(keyRingId, nameof(keyRingId));
CryptoKeyId = gax::GaxPreconditions.CheckNotNull(cryptoKeyId, nameof(cryptoKeyId));
CryptoKeyVersionId = gax::GaxPreconditions.CheckNotNull(cryptoKeyVersionId, nameof(cryptoKeyVersionId));
}
/// <summary>
/// The project ID. Never <c>null</c>.
/// </summary>
public string ProjectId { get; }
/// <summary>
/// The location ID. Never <c>null</c>.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The keyRing ID. Never <c>null</c>.
/// </summary>
public string KeyRingId { get; }
/// <summary>
/// The cryptoKey ID. Never <c>null</c>.
/// </summary>
public string CryptoKeyId { get; }
/// <summary>
/// The cryptoKeyVersion ID. Never <c>null</c>.
/// </summary>
public string CryptoKeyVersionId { get; }
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple;
/// <inheritdoc />
public override string ToString() => s_template.Expand(ProjectId, LocationId, KeyRingId, CryptoKeyId, CryptoKeyVersionId);
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as CryptoKeyVersionName);
/// <inheritdoc />
public bool Equals(CryptoKeyVersionName other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(CryptoKeyVersionName a, CryptoKeyVersionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(CryptoKeyVersionName a, CryptoKeyVersionName b) => !(a == b);
}
/// <summary>
/// Resource name which will contain one of a choice of resource names.
/// </summary>
/// <remarks>
/// This resource name will contain one of the following:
/// <list type="bullet">
/// <item><description>KeyRingName: A resource of type 'key_ring'.</description></item>
/// <item><description>CryptoKeyName: A resource of type 'crypto_key'.</description></item>
/// </list>
/// </remarks>
public sealed partial class KeyNameOneof : gax::IResourceName, sys::IEquatable<KeyNameOneof>
{
/// <summary>
/// The possible contents of <see cref="KeyNameOneof"/>.
/// </summary>
public enum OneofType
{
/// <summary>
/// A resource of an unknown type.
/// </summary>
Unknown = 0,
/// <summary>
/// A resource of type 'key_ring'.
/// </summary>
KeyRingName = 1,
/// <summary>
/// A resource of type 'crypto_key'.
/// </summary>
CryptoKeyName = 2,
}
/// <summary>
/// Parses a resource name in string form into a new <see cref="KeyNameOneof"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully the resource name must be one of the following:
/// <list type="bullet">
/// <item><description>KeyRingName: A resource of type 'key_ring'.</description></item>
/// <item><description>CryptoKeyName: A resource of type 'crypto_key'.</description></item>
/// </list>
/// Or an <see cref="gax::UnknownResourceName"/> if <paramref name="allowUnknown"/> is <c>true</c>.
/// </remarks>
/// <param name="name">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnknown">If true, will successfully parse an unknown resource name
/// into an <see cref="gax::UnknownResourceName"/>; otherwise will throw an
/// <see cref="sys::ArgumentException"/> if an unknown resource name is given.</param>
/// <returns>The parsed <see cref="KeyNameOneof"/> if successful.</returns>
public static KeyNameOneof Parse(string name, bool allowUnknown)
{
KeyNameOneof result;
if (TryParse(name, allowUnknown, out result))
{
return result;
}
throw new sys::ArgumentException("Invalid name", nameof(name));
}
/// <summary>
/// Tries to parse a resource name in string form into a new <see cref="KeyNameOneof"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully the resource name must be one of the following:
/// <list type="bullet">
/// <item><description>KeyRingName: A resource of type 'key_ring'.</description></item>
/// <item><description>CryptoKeyName: A resource of type 'crypto_key'.</description></item>
/// </list>
/// Or an <see cref="gax::UnknownResourceName"/> if <paramref name="allowUnknown"/> is <c>true</c>.
/// </remarks>
/// <param name="name">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnknown">If true, will successfully parse an unknown resource name
/// into an <see cref="gax::UnknownResourceName"/>.</param>
/// <param name="result">When this method returns, the parsed <see cref="KeyNameOneof"/>,
/// or <c>null</c> if parsing fails.</param>
/// <returns><c>true</c> if the name was parsed succssfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string name, bool allowUnknown, out KeyNameOneof result)
{
gax::GaxPreconditions.CheckNotNull(name, nameof(name));
KeyRingName keyRingName;
if (KeyRingName.TryParse(name, out keyRingName))
{
result = new KeyNameOneof(OneofType.KeyRingName, keyRingName);
return true;
}
CryptoKeyName cryptoKeyName;
if (CryptoKeyName.TryParse(name, out cryptoKeyName))
{
result = new KeyNameOneof(OneofType.CryptoKeyName, cryptoKeyName);
return true;
}
if (allowUnknown)
{
gax::UnknownResourceName unknownResourceName;
if (gax::UnknownResourceName.TryParse(name, out unknownResourceName))
{
result = new KeyNameOneof(OneofType.Unknown, unknownResourceName);
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Construct a new instance of <see cref="KeyNameOneof"/> from the provided <see cref="KeyRingName"/>
/// </summary>
/// <param name="keyRingName">The <see cref="KeyRingName"/> to be contained within
/// the returned <see cref="KeyNameOneof"/>. Must not be <c>null</c>.</param>
/// <returns>A new <see cref="KeyNameOneof"/>, containing <paramref name="keyRingName"/>.</returns>
public static KeyNameOneof From(KeyRingName keyRingName) => new KeyNameOneof(OneofType.KeyRingName, keyRingName);
/// <summary>
/// Construct a new instance of <see cref="KeyNameOneof"/> from the provided <see cref="CryptoKeyName"/>
/// </summary>
/// <param name="cryptoKeyName">The <see cref="CryptoKeyName"/> to be contained within
/// the returned <see cref="KeyNameOneof"/>. Must not be <c>null</c>.</param>
/// <returns>A new <see cref="KeyNameOneof"/>, containing <paramref name="cryptoKeyName"/>.</returns>
public static KeyNameOneof From(CryptoKeyName cryptoKeyName) => new KeyNameOneof(OneofType.CryptoKeyName, cryptoKeyName);
private static bool IsValid(OneofType type, gax::IResourceName name)
{
switch (type)
{
case OneofType.Unknown: return true; // Anything goes with Unknown.
case OneofType.KeyRingName: return name is KeyRingName;
case OneofType.CryptoKeyName: return name is CryptoKeyName;
default: return false;
}
}
/// <summary>
/// Constructs a new instance of the <see cref="KeyNameOneof"/> resource name class
/// from a suitable <see cref="gax::IResourceName"/> instance.
/// </summary>
public KeyNameOneof(OneofType type, gax::IResourceName name)
{
Type = gax::GaxPreconditions.CheckEnumValue<OneofType>(type, nameof(type));
Name = gax::GaxPreconditions.CheckNotNull(name, nameof(name));
if (!IsValid(type, name))
{
throw new sys::ArgumentException($"Mismatched OneofType '{type}' and resource name '{name}'");
}
}
/// <summary>
/// The <see cref="OneofType"/> of the Name contained in this instance.
/// </summary>
public OneofType Type { get; }
/// <summary>
/// The <see cref="gax::IResourceName"/> contained in this instance.
/// </summary>
public gax::IResourceName Name { get; }
private T CheckAndReturn<T>(OneofType type)
{
if (Type != type)
{
throw new sys::InvalidOperationException($"Requested type {type}, but this one-of contains type {Type}");
}
return (T)Name;
}
/// <summary>
/// Get the contained <see cref="gax::IResourceName"/> as <see cref="KeyRingName"/>.
/// </summary>
/// <remarks>
/// An <see cref="sys::InvalidOperationException"/> will be thrown if this does not
/// contain an instance of <see cref="KeyRingName"/>.
/// </remarks>
public KeyRingName KeyRingName => CheckAndReturn<KeyRingName>(OneofType.KeyRingName);
/// <summary>
/// Get the contained <see cref="gax::IResourceName"/> as <see cref="CryptoKeyName"/>.
/// </summary>
/// <remarks>
/// An <see cref="sys::InvalidOperationException"/> will be thrown if this does not
/// contain an instance of <see cref="CryptoKeyName"/>.
/// </remarks>
public CryptoKeyName CryptoKeyName => CheckAndReturn<CryptoKeyName>(OneofType.CryptoKeyName);
/// <inheritdoc />
public gax::ResourceNameKind Kind => gax::ResourceNameKind.Oneof;
/// <inheritdoc />
public override string ToString() => Name.ToString();
/// <inheritdoc />
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc />
public override bool Equals(object obj) => Equals(obj as KeyNameOneof);
/// <inheritdoc />
public bool Equals(KeyNameOneof other) => ToString() == other?.ToString();
/// <inheritdoc />
public static bool operator ==(KeyNameOneof a, KeyNameOneof b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc />
public static bool operator !=(KeyNameOneof a, KeyNameOneof b) => !(a == b);
}
public partial class AsymmetricDecryptRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class AsymmetricSignRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class CreateCryptoKeyRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.KeyRingName ParentAsKeyRingName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.KeyRingName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CreateCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName ParentAsCryptoKeyName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CreateKeyRingRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.LocationName ParentAsLocationName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.LocationName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class CryptoKey
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName CryptoKeyName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class CryptoKeyVersion
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DecryptRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName CryptoKeyName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class DestroyCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class EncryptRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyPathName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyPathName CryptoKeyPathName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyPathName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetCryptoKeyRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName CryptoKeyName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetKeyRingRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.KeyRingName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.KeyRingName KeyRingName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.KeyRingName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class GetPublicKeyRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class KeyRing
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.KeyRingName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.KeyRingName KeyRingName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.KeyRingName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class ListCryptoKeyVersionsRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName ParentAsCryptoKeyName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListCryptoKeysRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.KeyRingName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.KeyRingName ParentAsKeyRingName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.KeyRingName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class ListKeyRingsRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.LocationName"/>-typed view over the <see cref="Parent"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.LocationName ParentAsLocationName
{
get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Kms.V1.LocationName.Parse(Parent); }
set { Parent = value != null ? value.ToString() : ""; }
}
}
public partial class RestoreCryptoKeyVersionRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyVersionName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyVersionName CryptoKeyVersionName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyVersionName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
public partial class UpdateCryptoKeyPrimaryVersionRequest
{
/// <summary>
/// <see cref="Google.Cloud.Kms.V1.CryptoKeyName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public Google.Cloud.Kms.V1.CryptoKeyName CryptoKeyName
{
get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Kms.V1.CryptoKeyName.Parse(Name); }
set { Name = value != null ? value.ToString() : ""; }
}
}
}
| |
using System;
using System.Linq;
using System.IO;
using NUnit.Framework;
using FastCgiNet;
using FastCgiNet.Requests;
using System.Net;
using System.Net.Sockets;
namespace FastCgiNet.Tests
{
[TestFixture]
public class SocketRequestTests
{
private System.Net.IPAddress ListenAddr = System.Net.IPAddress.Loopback;
private int ListenPort = 9007;
/// <summary>
/// Maximum Poll or Select time to wait for new connections or data in loopback sockets before it is considered
/// an error.
/// </summary>
private int MaxPollTime = 100000;
private Socket GetListenSocket()
{
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(new IPEndPoint(ListenAddr, ListenPort));
sock.Listen(1);
return sock;
}
private Socket GetWebserverConnectedSocket()
{
var sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.ConnectAsync(new SocketAsyncEventArgs {
RemoteEndPoint = new System.Net.IPEndPoint(ListenAddr, ListenPort),
SocketFlags = SocketFlags.None
});
return sock;
}
[Test]
public void WebserverAndApplicationConnectAndBeginRequestBasicProperties()
{
using (var listenSocket = GetListenSocket())
{
using (var webserverSocket = GetWebserverConnectedSocket())
{
// Wait for the connection
if (!listenSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Connection took too long");
using (var applicationSocket = listenSocket.Accept())
{
byte[] buf = new byte[128];
ushort requestId = 2;
using (var webserverRequest = new WebServerSocketRequest(webserverSocket, requestId))
{
Assert.AreEqual(requestId, webserverRequest.RequestId);
webserverRequest.SendBeginRequest(Role.Responder, true);
using (var nvpWriter = new FastCgiNet.Streams.NvpWriter(webserverRequest.Params))
{
nvpWriter.Write("HELLO", "WORLD");
}
if (!applicationSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Data took too long");
using (var applicationRequest = new ApplicationSocketRequest(applicationSocket))
{
int bytesRead;
bool beginRequestReceived = false;
while (true)
{
if (beginRequestReceived)
break;
bytesRead = applicationSocket.Receive(buf);
if (bytesRead == 0)
throw new Exception("BeginRequest was not received");
foreach (var rec in applicationRequest.FeedBytes(buf, 0, bytesRead))
{
if (rec is BeginRequestRecord)
{
Assert.AreEqual(requestId, applicationRequest.RequestId);
Assert.AreEqual(Role.Responder, applicationRequest.Role);
Assert.IsTrue(applicationRequest.ApplicationMustCloseConnection);
beginRequestReceived = true;
}
}
}
applicationRequest.SendEndRequest(0, ProtocolStatus.RequestComplete);
applicationSocket.Close();
}
if (!webserverSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Data took too long");
bool endRequestReceived = false;
while (true)
{
if (endRequestReceived)
break;
int bytesRead = webserverSocket.Receive(buf);
if (bytesRead == 0)
throw new Exception("EndRequest was not received");
foreach (var rec in webserverRequest.FeedBytes(buf, 0, bytesRead))
{
var endRec = rec as EndRequestRecord;
if (endRec != null)
{
Assert.AreEqual(requestId, rec.RequestId);
Assert.AreEqual(0, endRec.AppStatus);
Assert.AreEqual(ProtocolStatus.RequestComplete, endRec.ProtocolStatus);
endRequestReceived = true;
}
}
}
}
}
}
}
}
[Test]
public void WebserverAndApplicationLongStdoutCommunication()
{
// The stdout stream will have the following written: "abcdefghijklmnopq " over and over again
// Make sure this amounts to more than one Record
var stdoutContentsBuilder = new System.Text.StringBuilder();
for (int i = 0; i < 10000; ++i)
{
stdoutContentsBuilder.Append("abcdefghijklmnopq ");
}
string stdoutContents = stdoutContentsBuilder.ToString();
using (var listenSocket = GetListenSocket())
{
using (var webserverSocket = GetWebserverConnectedSocket())
{
// Wait for the connection
if (!listenSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Connection took too long");
using (var applicationSocket = listenSocket.Accept())
{
byte[] buf = new byte[128];
ushort requestId = 2;
using (var webserverRequest = new WebServerSocketRequest(webserverSocket, requestId))
{
webserverRequest.SendBeginRequest(Role.Responder, true);
using (var nvpWriter = new FastCgiNet.Streams.NvpWriter(webserverRequest.Params))
{
nvpWriter.WriteParamsFromUri(new Uri("http://github.com/mzabani"), "GET");
}
if (!applicationSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Data took too long");
using (var applicationRequest = new ApplicationSocketRequest(applicationSocket))
{
int bytesRead;
bool beginRequestReceived = false;
while (true)
{
if (beginRequestReceived && applicationRequest.Params.IsComplete)
break;
bytesRead = applicationSocket.Receive(buf);
if (bytesRead == 0)
throw new Exception("Read 0 bytes");
foreach (var rec in applicationRequest.FeedBytes(buf, 0, bytesRead))
{
if (rec.RecordType == RecordType.FCGIBeginRequest)
beginRequestReceived = true;
}
}
// Write a whole bunch to Stdout.
using (var writer = new StreamWriter(applicationRequest.Stdout))
{
writer.Write(stdoutContents);
}
applicationRequest.SendEndRequest(0, ProtocolStatus.RequestComplete);
applicationSocket.Close();
}
if (!webserverSocket.Poll(MaxPollTime, SelectMode.SelectRead))
throw new Exception("Data took too long");
bool endRequestReceived = false;
while (true)
{
if (endRequestReceived)
break;
int bytesRead = webserverSocket.Receive(buf);
if (bytesRead == 0)
throw new Exception("Read 0 bytes");
foreach (var rec in webserverRequest.FeedBytes(buf, 0, bytesRead))
{
var endRec = rec as EndRequestRecord;
if (endRec != null)
{
endRequestReceived = true;
}
}
}
// Read stdout and make sure it got here in one piece!
Assert.IsTrue(webserverRequest.Stdout.IsComplete);
using (var reader = new StreamReader(webserverRequest.Stdout))
{
Assert.AreEqual(stdoutContents, reader.ReadToEnd());
}
}
}
}
}
}
}
}
| |
/*
Copyright 2019 Esri
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.IO;
using System.Windows.Forms;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS;
namespace MetadataViewer
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.Button buttonLoad;
private System.Windows.Forms.ComboBox cboStyleSheets;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private ITOCControl m_tocControl;
private string m_tempFile;
private string m_tempDir;
private ILayer m_layer;
private ESRI.ArcGIS.Controls.AxTOCControl axTOCControl1;
private ESRI.ArcGIS.Controls.AxPageLayoutControl axPageLayoutControl1;
private ESRI.ArcGIS.Controls.AxLicenseControl axLicenseControl1;
private WebBrowser webBrowser1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
//Release COM objects
ESRI.ArcGIS.ADF.COMSupport.AOUninitialize.Shutdown();
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.buttonLoad = new System.Windows.Forms.Button();
this.cboStyleSheets = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.axTOCControl1 = new ESRI.ArcGIS.Controls.AxTOCControl();
this.axPageLayoutControl1 = new ESRI.ArcGIS.Controls.AxPageLayoutControl();
this.axLicenseControl1 = new ESRI.ArcGIS.Controls.AxLicenseControl();
this.webBrowser1 = new System.Windows.Forms.WebBrowser();
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).BeginInit();
this.SuspendLayout();
//
// buttonLoad
//
this.buttonLoad.Location = new System.Drawing.Point(8, 8);
this.buttonLoad.Name = "buttonLoad";
this.buttonLoad.Size = new System.Drawing.Size(176, 48);
this.buttonLoad.TabIndex = 2;
this.buttonLoad.Text = "Load Document";
this.buttonLoad.Click += new System.EventHandler(this.button1_Click);
//
// cboStyleSheets
//
this.cboStyleSheets.Location = new System.Drawing.Point(550, 23);
this.cboStyleSheets.Name = "cboStyleSheets";
this.cboStyleSheets.Size = new System.Drawing.Size(326, 21);
this.cboStyleSheets.TabIndex = 6;
this.cboStyleSheets.SelectedIndexChanged += new System.EventHandler(this.cboStyleSheets_SelectedIndexChanged);
//
// label1
//
this.label1.ForeColor = System.Drawing.SystemColors.Highlight;
this.label1.Location = new System.Drawing.Point(192, 8);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(296, 16);
this.label1.TabIndex = 8;
this.label1.Text = "1) Load a map document into the PageLayoutControl";
//
// label2
//
this.label2.ForeColor = System.Drawing.SystemColors.Highlight;
this.label2.Location = new System.Drawing.Point(192, 24);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(296, 16);
this.label2.TabIndex = 9;
this.label2.Text = "2) Select a style sheet or enter the file path to style sheet";
//
// label3
//
this.label3.ForeColor = System.Drawing.SystemColors.Highlight;
this.label3.Location = new System.Drawing.Point(192, 40);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(336, 16);
this.label3.TabIndex = 10;
this.label3.Text = "3) Right click a layer on the TOCControl to display its metadata";
//
// axTOCControl1
//
this.axTOCControl1.Location = new System.Drawing.Point(12, 62);
this.axTOCControl1.Name = "axTOCControl1";
this.axTOCControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axTOCControl1.OcxState")));
this.axTOCControl1.Size = new System.Drawing.Size(178, 412);
this.axTOCControl1.TabIndex = 12;
this.axTOCControl1.OnMouseDown += new ESRI.ArcGIS.Controls.ITOCControlEvents_Ax_OnMouseDownEventHandler(this.axTOCControl1_OnMouseDown);
//
// axPageLayoutControl1
//
this.axPageLayoutControl1.Location = new System.Drawing.Point(196, 64);
this.axPageLayoutControl1.Name = "axPageLayoutControl1";
this.axPageLayoutControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axPageLayoutControl1.OcxState")));
this.axPageLayoutControl1.Size = new System.Drawing.Size(348, 410);
this.axPageLayoutControl1.TabIndex = 13;
//
// axLicenseControl1
//
this.axLicenseControl1.Enabled = true;
this.axLicenseControl1.Location = new System.Drawing.Point(128, 96);
this.axLicenseControl1.Name = "axLicenseControl1";
this.axLicenseControl1.OcxState = ((System.Windows.Forms.AxHost.State)(resources.GetObject("axLicenseControl1.OcxState")));
this.axLicenseControl1.Size = new System.Drawing.Size(32, 32);
this.axLicenseControl1.TabIndex = 14;
//
// webBrowser1
//
this.webBrowser1.Location = new System.Drawing.Point(550, 61);
this.webBrowser1.MinimumSize = new System.Drawing.Size(20, 20);
this.webBrowser1.Name = "webBrowser1";
this.webBrowser1.Size = new System.Drawing.Size(326, 413);
this.webBrowser1.TabIndex = 15;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(888, 486);
this.Controls.Add(this.webBrowser1);
this.Controls.Add(this.axLicenseControl1);
this.Controls.Add(this.axPageLayoutControl1);
this.Controls.Add(this.axTOCControl1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.cboStyleSheets);
this.Controls.Add(this.buttonLoad);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "Form1";
this.Text = "MetadataViewer";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.axTOCControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axPageLayoutControl1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.axLicenseControl1)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
if (!RuntimeManager.Bind(ProductCode.Engine))
{
if (!RuntimeManager.Bind(ProductCode.Desktop))
{
MessageBox.Show("Unable to bind to ArcGIS runtime. Application will be shut down.");
return;
}
}
Application.Run(new Form1());
}
private void Form1_Load(object sender, System.EventArgs e)
{
m_tocControl = (ITOCControl) axTOCControl1.Object;
//Set buddy control
m_tocControl.SetBuddyControl(axPageLayoutControl1);
//Get the directory of the executable
m_tempDir = System.Reflection.Assembly.GetExecutingAssembly().Location;
m_tempDir = Path.GetDirectoryName(m_tempDir);
//The location to save the temporary metadata
m_tempFile = m_tempDir + "metadata.htm";
//Add style sheets to the combo box
cboStyleSheets.Items.Insert(0, @"Brief.xsl");
cboStyleSheets.Items.Insert(1, @"Attributes.xsl");
cboStyleSheets.Items.Insert(2, @"DataDictionTable.xsl");
cboStyleSheets.Items.Insert(3, @"DataDictionPage.xsl");
cboStyleSheets.SelectedIndex = 0;
}
private void ShowMetadata (ILayer layer)
{
if (layer is IDataLayer)
{
//Check style sheet exists
if (File.Exists(cboStyleSheets.Text)== false)
{
System.Windows.Forms.MessageBox.Show("The selected style sheet does not exist!","Missing Style Sheet");
return;
}
//QI for IDataLayer
IDataLayer dataLayer = (IDataLayer) layer;
//Get the metadata
IMetadata metaData = (IMetadata) dataLayer.DataSourceName;
//Get the xml property set from the metadata
IXmlPropertySet2 xml = (IXmlPropertySet2) metaData.Metadata;
//Save the xml to a temporary file and transforms it using the selected style sheet
xml.SaveAsFile(cboStyleSheets.Text,"",false, ref m_tempFile );
//Navigate the web browser to the temporary file
object obj = null;
webBrowser1.Navigate(m_tempFile);
}
else
{
System.Windows.Forms.MessageBox.Show("Metadata shown for IDataLayer objects only", "IDataLayer objects only");
}
}
private void button1_Click(object sender, System.EventArgs e)
{
//Open a file dialog for selecting map documents
openFileDialog1.Title = "Select Map Document";
openFileDialog1.Filter = "Map Documents (*.mxd)|*.mxd";
openFileDialog1.ShowDialog();
// Exit if no map document is selected
string sFilePath = openFileDialog1.FileName;
if (sFilePath == "") return;
// Load the specified mxd
if (axPageLayoutControl1.CheckMxFile(sFilePath) == false)
{
System.Windows.Forms.MessageBox.Show("This document cannot be loaded!");
return;
}
axPageLayoutControl1.LoadMxFile(sFilePath, "");
//Set the current directory to the that of the executable
Directory.SetCurrentDirectory(m_tempDir);
}
private void cboStyleSheets_SelectedIndexChanged(object sender, System.EventArgs e)
{
//Show the metadata for the layer
if (m_layer == null) return;
ShowMetadata(m_layer);
}
private void axTOCControl1_OnMouseDown(object sender, ESRI.ArcGIS.Controls.ITOCControlEvents_OnMouseDownEvent e)
{
//Exit not a right mouse click
if (e.button != 2) return;
//Determine what kind of item has been clicked on
esriTOCControlItem item = esriTOCControlItem.esriTOCControlItemNone;
IBasicMap map = null;
object other = null; object index = null;
m_tocControl.HitTest(e.x, e.y, ref item, ref map, ref m_layer, ref other, ref index);
//Show the metadata for the layer
if (m_layer == null) return;
ShowMetadata(m_layer);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Versioning;
using Fubu.CsProjFile.FubuCsProjFile.MSBuild;
using FubuCore;
namespace Fubu.CsProjFile.FubuCsProjFile
{
public class CsProjFile
{
private const string PROJECTGUID = "ProjectGuid";
private const string ROOT_NAMESPACE = "RootNamespace";
private const string ASSEMBLY_NAME = "AssemblyName";
private readonly string _fileName;
private readonly MSBuildProject _project;
private readonly Dictionary<string, ProjectItem> _projectItemCache = new Dictionary<string, ProjectItem>();
public static readonly Guid ClassLibraryType = Guid.Parse("FAE04EC0-301F-11D3-BF4B-00C04F79EFBC");
public static readonly Guid WebSiteLibraryType = new Guid("E24C65DC-7377-472B-9ABA-BC803B73C61A");
public static readonly Guid VisualStudioSetupLibraryType = new Guid("54435603-DBB4-11D2-8724-00A0C9A8B90C");
private AssemblyInfo assemblyInfo;
public Guid ProjectGuid
{
get
{
string raw = (from x in this._project.PropertyGroups
select x.GetPropertyValue("ProjectGuid")).FirstOrDefault((string x) => FubuCore.StringExtensions.IsNotEmpty(x));
if (!FubuCore.StringExtensions.IsEmpty(raw))
{
return Guid.Parse(raw.TrimStart(new char[]
{
'{'
}).TrimEnd(new char[]
{
'}'
}));
}
return Guid.Empty;
}
internal set
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "ProjectGuid"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
group.SetPropertyValue("ProjectGuid", value.ToString().ToUpper(), true);
}
}
public string AssemblyName
{
get
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "AssemblyName"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
return group.GetPropertyValue("AssemblyName");
}
set
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "AssemblyName"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
group.SetPropertyValue("AssemblyName", value, true);
}
}
public string RootNamespace
{
get
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "RootNamespace"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
return group.GetPropertyValue("RootNamespace");
}
set
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "RootNamespace"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
group.SetPropertyValue("RootNamespace", value, true);
}
}
public string ProjectName
{
get
{
return Path.GetFileNameWithoutExtension(this._fileName);
}
}
public MSBuildProject BuildProject
{
get
{
return this._project;
}
}
public string FileName
{
get
{
return this._fileName;
}
}
public string ProjectDirectory
{
get
{
return FubuCore.StringExtensions.ParentDirectory(this._fileName);
}
}
public FrameworkName FrameworkName
{
get
{
return this._project.FrameworkName;
}
}
public string DotNetVersion
{
get
{
return (from x in this._project.PropertyGroups
select x.GetPropertyValue("TargetFrameworkVersion")).FirstOrDefault((string x) => FubuCore.StringExtensions.IsNotEmpty(x));
}
set
{
MSBuildPropertyGroup arg_51_0;
if ((arg_51_0 = this._project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "TargetFrameworkVersion"))) == null)
{
arg_51_0 = (this._project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? this._project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_51_0;
group.SetPropertyValue("TargetFrameworkVersion", value, true);
}
}
public SourceControlInformation SourceControlInformation
{
get;
set;
}
public AssemblyInfo AssemblyInfo
{
get
{
if (this.assemblyInfo == null)
{
CodeFile codeFile = this.All<CodeFile>().FirstOrDefault((CodeFile item) => item.Include.EndsWith("AssemblyInfo.cs"));
if (codeFile != null)
{
this.assemblyInfo = new AssemblyInfo(codeFile, this);
this._projectItemCache.Add("AssemblyInfo+" + codeFile.Include, this.assemblyInfo);
}
}
return this.assemblyInfo;
}
}
public TargetFrameworkVersion TargetFrameworkVersion
{
get
{
return this.BuildProject.GetGlobalPropertyGroup().GetPropertyValue("TargetFrameworkVersion");
}
set
{
this.BuildProject.GetGlobalPropertyGroup().SetPropertyValue("TargetFrameworkVersion", value, false);
}
}
public string Platform
{
get
{
return this.BuildProject.GetGlobalPropertyGroup().GetPropertyValue("Platform");
}
set
{
this.BuildProject.GetGlobalPropertyGroup().SetPropertyValue("Platform", value, false);
}
}
public CsProjFile(string fileName) : this(fileName, MSBuildProject.LoadFrom(fileName))
{
}
public CsProjFile(string fileName, MSBuildProject project)
{
this._fileName = fileName;
this._project = project;
}
public void Add<T>(T item) where T : ProjectItem
{
MSBuildItemGroup arg_58_0;
if ((arg_58_0 = this._project.FindGroup(new Func<MSBuildItem, bool>(item.Matches))) == null)
{
arg_58_0 = (this._project.FindGroup((MSBuildItem x) => x.Name == item.Name) ?? this._project.AddNewItemGroup());
}
MSBuildItemGroup group = arg_58_0;
item.Configure(group);
}
public T Add<T>(string include) where T : ProjectItem, new()
{
T t = Activator.CreateInstance<T>();
t.Include = include;
T item = t;
this._projectItemCache.Remove(item.Include);
this._projectItemCache.Add(include, item);
this.Add<T>(item);
return item;
}
public IEnumerable<T> All<T>() where T : ProjectItem, new()
{
T t = Activator.CreateInstance<T>();
string name = t.Name;
return (from x in this._project.GetAllItems(new string[]
{
name
})
orderby x.Include
select x).Select(delegate(MSBuildItem item)
{
T projectItem;
if (this._projectItemCache.ContainsKey(item.Include))
{
projectItem = (T)((object)this._projectItemCache[item.Include]);
}
else
{
projectItem = Activator.CreateInstance<T>();
projectItem.Read(item);
this._projectItemCache.Add(item.Include, projectItem);
}
return projectItem;
});
}
public static CsProjFile CreateAtSolutionDirectory(string assemblyName, string directory)
{
string fileName = FubuCore.StringExtensions.AppendPath(FubuCore.StringExtensions.AppendPath(directory, new string[]
{
assemblyName
}), new string[]
{
assemblyName
}) + ".csproj";
MSBuildProject project = MSBuildProject.Create(assemblyName);
return CsProjFile.CreateCore(project, fileName);
}
public static CsProjFile CreateAtLocation(string fileName, string assemblyName)
{
return CsProjFile.CreateCore(MSBuildProject.Create(assemblyName), fileName);
}
private static CsProjFile CreateCore(MSBuildProject project, string fileName)
{
MSBuildPropertyGroup arg_42_0;
if ((arg_42_0 = project.PropertyGroups.FirstOrDefault((MSBuildPropertyGroup x) => x.Properties.Any((MSBuildProperty p) => p.Name == "ProjectGuid"))) == null)
{
arg_42_0 = (project.PropertyGroups.FirstOrDefault<MSBuildPropertyGroup>() ?? project.AddNewPropertyGroup(true));
}
MSBuildPropertyGroup group = arg_42_0;
group.SetPropertyValue("ProjectGuid", Guid.NewGuid().ToString().ToUpper(), true);
CsProjFile file = new CsProjFile(fileName, project);
file.AssemblyName = (file.RootNamespace = file.ProjectName);
return file;
}
public static CsProjFile LoadFrom(string filename)
{
MSBuildProject project = MSBuildProject.LoadFrom(filename);
return new CsProjFile(filename, project);
}
public void Save()
{
this.Save(this._fileName);
}
public void Save(string file)
{
foreach (KeyValuePair<string, ProjectItem> item in this._projectItemCache)
{
item.Value.Save();
}
this._project.Save(file);
}
public IEnumerable<Guid> ProjectTypes()
{
IEnumerable<string> enumerable = from x in this._project.PropertyGroups
select x.GetPropertyValue("ProjectTypeGuids") into x
where FubuCore.StringExtensions.IsNotEmpty(x)
select x;
if (enumerable.Any<string>())
{
foreach (string current in enumerable)
{
try
{
string[] array = current.Split(new char[]
{
';'
});
for (int i = 0; i < array.Length; i++)
{
string text = array[i];
yield return Guid.Parse(text.TrimStart(new char[]
{
'{'
}).TrimEnd(new char[]
{
'}'
}));
}
}
finally
{
}
}
}
else
{
yield return CsProjFile.ClassLibraryType;
}
yield break;
}
public void CopyFileTo(string source, string relativePath)
{
string target = FubuCore.StringExtensions.AppendPath(FubuCore.StringExtensions.ParentDirectory(this._fileName), new string[]
{
relativePath
});
new FileSystem().Copy(source, target);
}
public T Find<T>(string include) where T : ProjectItem, new()
{
return this.All<T>().FirstOrDefault((T x) => x.Include == include);
}
public string PathTo(CodeFile codeFile)
{
string path = codeFile.Include;
if (FubuCore.Platform.IsUnix())
{
path = path.Replace('\\', Path.DirectorySeparatorChar);
}
return FubuCore.StringExtensions.AppendPath(FubuCore.StringExtensions.ParentDirectory(this._fileName), new string[]
{
path
});
}
public void Remove<T>(string include) where T : ProjectItem, new()
{
T t = Activator.CreateInstance<T>();
string name = t.Name;
this._projectItemCache.Remove(include);
MSBuildItem element = this._project.GetAllItems(new string[]
{
name
}).FirstOrDefault((MSBuildItem x) => x.Include == include);
if (element != null)
{
element.Remove();
}
}
public void Remove<T>(T item) where T : ProjectItem, new()
{
this._projectItemCache.Remove(item.Include);
MSBuildItem element = this._project.GetAllItems(new string[]
{
item.Name
}).FirstOrDefault((MSBuildItem x) => x.Include == item.Include);
if (element != null)
{
element.Remove();
}
}
public override string ToString()
{
return string.Format("{0}", this.FileName);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace Python.Runtime
{
/// <summary>
/// Implements the "import hook" used to integrate Python with the CLR.
/// </summary>
internal class ImportHook
{
private static IntPtr py_import;
private static CLRModule root;
private static MethodWrapper hook;
private static IntPtr py_clr_module;
#if PYTHON3
private static IntPtr module_def = IntPtr.Zero;
internal static void InitializeModuleDef()
{
if (module_def == IntPtr.Zero)
{
module_def = ModuleDefOffset.AllocModuleDef("clr");
}
}
#endif
/// <summary>
/// Initialization performed on startup of the Python runtime.
/// </summary>
internal static void Initialize()
{
// Initialize the Python <--> CLR module hook. We replace the
// built-in Python __import__ with our own. This isn't ideal,
// but it provides the most "Pythonic" way of dealing with CLR
// modules (Python doesn't provide a way to emulate packages).
IntPtr dict = Runtime.PyImport_GetModuleDict();
IntPtr mod = Runtime.IsPython3
? Runtime.PyImport_ImportModule("builtins")
: Runtime.PyDict_GetItemString(dict, "__builtin__");
py_import = Runtime.PyObject_GetAttrString(mod, "__import__");
hook = new MethodWrapper(typeof(ImportHook), "__import__", "TernaryFunc");
Runtime.PyObject_SetAttrString(mod, "__import__", hook.ptr);
Runtime.XDecref(hook.ptr);
root = new CLRModule();
#if PYTHON3
// create a python module with the same methods as the clr module-like object
InitializeModuleDef();
py_clr_module = Runtime.PyModule_Create2(module_def, 3);
// both dicts are borrowed references
IntPtr mod_dict = Runtime.PyModule_GetDict(py_clr_module);
IntPtr clr_dict = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject**
clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr));
Runtime.PyDict_Update(mod_dict, clr_dict);
#elif PYTHON2
Runtime.XIncref(root.pyHandle); // we are using the module two times
py_clr_module = root.pyHandle; // Alias handle for PY2/PY3
#endif
Runtime.PyDict_SetItemString(dict, "CLR", py_clr_module);
Runtime.PyDict_SetItemString(dict, "clr", py_clr_module);
}
/// <summary>
/// Cleanup resources upon shutdown of the Python runtime.
/// </summary>
internal static void Shutdown()
{
if (Runtime.Py_IsInitialized() != 0)
{
Runtime.XDecref(py_clr_module);
Runtime.XDecref(root.pyHandle);
Runtime.XDecref(py_import);
}
}
/// <summary>
/// Return the clr python module (new reference)
/// </summary>
public static IntPtr GetCLRModule(IntPtr? fromList = null)
{
root.InitializePreload();
if (Runtime.IsPython2)
{
Runtime.XIncref(py_clr_module);
return py_clr_module;
}
// Python 3
// update the module dictionary with the contents of the root dictionary
root.LoadNames();
IntPtr py_mod_dict = Runtime.PyModule_GetDict(py_clr_module);
IntPtr clr_dict = Runtime._PyObject_GetDictPtr(root.pyHandle); // PyObject**
clr_dict = (IntPtr)Marshal.PtrToStructure(clr_dict, typeof(IntPtr));
Runtime.PyDict_Update(py_mod_dict, clr_dict);
// find any items from the from list and get them from the root if they're not
// already in the module dictionary
if (fromList != null && fromList != IntPtr.Zero)
{
if (Runtime.PyTuple_Check(fromList.GetValueOrDefault()))
{
Runtime.XIncref(py_mod_dict);
using (var mod_dict = new PyDict(py_mod_dict))
{
Runtime.XIncref(fromList.GetValueOrDefault());
using (var from = new PyTuple(fromList.GetValueOrDefault()))
{
foreach (PyObject item in from)
{
if (mod_dict.HasKey(item))
{
continue;
}
var s = item.AsManagedObject(typeof(string)) as string;
if (s == null)
{
continue;
}
ManagedType attr = root.GetAttribute(s, true);
if (attr == null)
{
continue;
}
Runtime.XIncref(attr.pyHandle);
using (var obj = new PyObject(attr.pyHandle))
{
mod_dict.SetItem(s, obj);
}
}
}
}
}
}
Runtime.XIncref(py_clr_module);
return py_clr_module;
}
/// <summary>
/// The actual import hook that ties Python to the managed world.
/// </summary>
public static IntPtr __import__(IntPtr self, IntPtr args, IntPtr kw)
{
// Replacement for the builtin __import__. The original import
// hook is saved as this.py_import. This version handles CLR
// import and defers to the normal builtin for everything else.
var num_args = Runtime.PyTuple_Size(args);
if (num_args < 1)
{
return Exceptions.RaiseTypeError("__import__() takes at least 1 argument (0 given)");
}
// borrowed reference
IntPtr py_mod_name = Runtime.PyTuple_GetItem(args, 0);
if (py_mod_name == IntPtr.Zero ||
!Runtime.IsStringType(py_mod_name))
{
return Exceptions.RaiseTypeError("string expected");
}
// Check whether the import is of the form 'from x import y'.
// This determines whether we return the head or tail module.
IntPtr fromList = IntPtr.Zero;
var fromlist = false;
if (num_args >= 4)
{
fromList = Runtime.PyTuple_GetItem(args, 3);
if (fromList != IntPtr.Zero &&
Runtime.PyObject_IsTrue(fromList) == 1)
{
fromlist = true;
}
}
string mod_name = Runtime.GetManagedString(py_mod_name);
// Check these BEFORE the built-in import runs; may as well
// do the Incref()ed return here, since we've already found
// the module.
if (mod_name == "clr")
{
IntPtr clr_module = GetCLRModule(fromList);
if (clr_module != IntPtr.Zero)
{
IntPtr sys_modules = Runtime.PyImport_GetModuleDict();
if (sys_modules != IntPtr.Zero)
{
Runtime.PyDict_SetItemString(sys_modules, "clr", clr_module);
}
}
return clr_module;
}
if (mod_name == "CLR")
{
Exceptions.deprecation("The CLR module is deprecated. Please use 'clr'.");
IntPtr clr_module = GetCLRModule(fromList);
if (clr_module != IntPtr.Zero)
{
IntPtr sys_modules = Runtime.PyImport_GetModuleDict();
if (sys_modules != IntPtr.Zero)
{
Runtime.PyDict_SetItemString(sys_modules, "clr", clr_module);
}
}
return clr_module;
}
string realname = mod_name;
string clr_prefix = null;
if (mod_name.StartsWith("CLR."))
{
clr_prefix = "CLR."; // prepend when adding the module to sys.modules
realname = mod_name.Substring(4);
string msg = $"Importing from the CLR.* namespace is deprecated. Please import '{realname}' directly.";
Exceptions.deprecation(msg);
}
else
{
// 2010-08-15: Always seemed smart to let python try first...
// This shaves off a few tenths of a second on test_module.py
// and works around a quirk where 'sys' is found by the
// LoadImplicit() deprecation logic.
// Turns out that the AssemblyManager.ResolveHandler() checks to see if any
// Assembly's FullName.ToLower().StartsWith(name.ToLower()), which makes very
// little sense to me.
IntPtr res = Runtime.PyObject_Call(py_import, args, kw);
if (res != IntPtr.Zero)
{
// There was no error.
if (fromlist && IsLoadAll(fromList))
{
var mod = ManagedType.GetManagedObject(res) as ModuleObject;
mod?.LoadNames();
}
return res;
}
// There was an error
if (!Exceptions.ExceptionMatches(Exceptions.ImportError))
{
// and it was NOT an ImportError; bail out here.
return IntPtr.Zero;
}
if (mod_name == string.Empty)
{
// Most likely a missing relative import.
// For example site-packages\bs4\builder\__init__.py uses it to check if a package exists:
// from . import _html5lib
// We don't support them anyway
return IntPtr.Zero;
}
// Otherwise, just clear the it.
Exceptions.Clear();
}
string[] names = realname.Split('.');
// Now we need to decide if the name refers to a CLR module,
// and may have to do an implicit load (for b/w compatibility)
// using the AssemblyManager. The assembly manager tries
// really hard not to use Python objects or APIs, because
// parts of it can run recursively and on strange threads.
//
// It does need an opportunity from time to time to check to
// see if sys.path has changed, in a context that is safe. Here
// we know we have the GIL, so we'll let it update if needed.
AssemblyManager.UpdatePath();
if (!AssemblyManager.IsValidNamespace(realname))
{
if (!AssemblyManager.LoadImplicit(realname))
{
// May be called when a module being imported imports a module.
// In particular, I've seen decimal import copy import org.python.core
return Runtime.PyObject_Call(py_import, args, kw);
}
}
// See if sys.modules for this interpreter already has the
// requested module. If so, just return the existing module.
IntPtr modules = Runtime.PyImport_GetModuleDict();
IntPtr module = Runtime.PyDict_GetItem(modules, py_mod_name);
if (module != IntPtr.Zero)
{
if (fromlist)
{
if (IsLoadAll(fromList))
{
var mod = ManagedType.GetManagedObject(module) as ModuleObject;
mod?.LoadNames();
}
Runtime.XIncref(module);
return module;
}
if (clr_prefix != null)
{
return GetCLRModule(fromList);
}
module = Runtime.PyDict_GetItemString(modules, names[0]);
Runtime.XIncref(module);
return module;
}
Exceptions.Clear();
// Traverse the qualified module name to get the named module
// and place references in sys.modules as we go. Note that if
// we are running in interactive mode we pre-load the names in
// each module, which is often useful for introspection. If we
// are not interactive, we stick to just-in-time creation of
// objects at lookup time, which is much more efficient.
// NEW: The clr got a new module variable preload. You can
// enable preloading in a non-interactive python processing by
// setting clr.preload = True
ModuleObject head = mod_name == realname ? null : root;
ModuleObject tail = root;
root.InitializePreload();
foreach (string name in names)
{
ManagedType mt = tail.GetAttribute(name, true);
if (!(mt is ModuleObject))
{
Exceptions.SetError(Exceptions.ImportError, $"No module named {name}");
return IntPtr.Zero;
}
if (head == null)
{
head = (ModuleObject)mt;
}
tail = (ModuleObject)mt;
if (CLRModule.preload)
{
tail.LoadNames();
}
// Add the module to sys.modules
Runtime.PyDict_SetItemString(modules, tail.moduleName, tail.pyHandle);
// If imported from CLR add CLR.<modulename> to sys.modules as well
if (clr_prefix != null)
{
Runtime.PyDict_SetItemString(modules, clr_prefix + tail.moduleName, tail.pyHandle);
}
}
{
var mod = fromlist ? tail : head;
if (fromlist && IsLoadAll(fromList))
{
mod.LoadNames();
}
Runtime.XIncref(mod.pyHandle);
return mod.pyHandle;
}
}
private static bool IsLoadAll(IntPtr fromList)
{
if (CLRModule.preload)
{
return false;
}
if (Runtime.PySequence_Size(fromList) != 1)
{
return false;
}
IntPtr fp = Runtime.PySequence_GetItem(fromList, 0);
bool res = Runtime.GetManagedString(fp) == "*";
Runtime.XDecref(fp);
return res;
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Text;
namespace EduHub.Data.Entities
{
/// <summary>
/// Medicare Levy Parameters Data Set
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class PMLDataSet : EduHubDataSet<PML>
{
/// <inheritdoc />
public override string Name { get { return "PML"; } }
/// <inheritdoc />
public override bool SupportsEntityLastModified { get { return true; } }
internal PMLDataSet(EduHubContext Context)
: base(Context)
{
Index_SCALE = new Lazy<Dictionary<short, PML>>(() => this.ToDictionary(i => i.SCALE));
}
/// <summary>
/// Matches CSV file headers to actions, used to deserialize <see cref="PML" />
/// </summary>
/// <param name="Headers">The CSV column headers</param>
/// <returns>An array of actions which deserialize <see cref="PML" /> fields for each CSV column header</returns>
internal override Action<PML, string>[] BuildMapper(IReadOnlyList<string> Headers)
{
var mapper = new Action<PML, string>[Headers.Count];
for (var i = 0; i < Headers.Count; i++) {
switch (Headers[i]) {
case "SCALE":
mapper[i] = (e, v) => e.SCALE = short.Parse(v);
break;
case "WEEKLY_EARNING_THRESHOLD":
mapper[i] = (e, v) => e.WEEKLY_EARNING_THRESHOLD = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "WEEKLY_SHADEIN_THRESHOLD":
mapper[i] = (e, v) => e.WEEKLY_SHADEIN_THRESHOLD = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "MEDLEVY_FAMILY_THRESHOLD":
mapper[i] = (e, v) => e.MEDLEVY_FAMILY_THRESHOLD = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "WFT_DIVISOR":
mapper[i] = (e, v) => e.WFT_DIVISOR = v == null ? (double?)null : double.Parse(v);
break;
case "ADDITIONAL_CHILD":
mapper[i] = (e, v) => e.ADDITIONAL_CHILD = v == null ? (decimal?)null : decimal.Parse(v);
break;
case "SOP_MULTIPLIER":
mapper[i] = (e, v) => e.SOP_MULTIPLIER = v == null ? (double?)null : double.Parse(v);
break;
case "SOP_DIVISOR":
mapper[i] = (e, v) => e.SOP_DIVISOR = v == null ? (double?)null : double.Parse(v);
break;
case "WLA_FALCTOR":
mapper[i] = (e, v) => e.WLA_FALCTOR = v == null ? (double?)null : double.Parse(v);
break;
case "MEDICARE_LEVY":
mapper[i] = (e, v) => e.MEDICARE_LEVY = v == null ? (double?)null : double.Parse(v);
break;
case "LW_DATE":
mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);
break;
case "LW_TIME":
mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v);
break;
case "LW_USER":
mapper[i] = (e, v) => e.LW_USER = v;
break;
default:
mapper[i] = MapperNoOp;
break;
}
}
return mapper;
}
/// <summary>
/// Merges <see cref="PML" /> delta entities
/// </summary>
/// <param name="Entities">Iterator for base <see cref="PML" /> entities</param>
/// <param name="DeltaEntities">List of delta <see cref="PML" /> entities</param>
/// <returns>A merged <see cref="IEnumerable{PML}"/> of entities</returns>
internal override IEnumerable<PML> ApplyDeltaEntities(IEnumerable<PML> Entities, List<PML> DeltaEntities)
{
HashSet<short> Index_SCALE = new HashSet<short>(DeltaEntities.Select(i => i.SCALE));
using (var deltaIterator = DeltaEntities.GetEnumerator())
{
using (var entityIterator = Entities.GetEnumerator())
{
while (deltaIterator.MoveNext())
{
var deltaClusteredKey = deltaIterator.Current.SCALE;
bool yieldEntity = false;
while (entityIterator.MoveNext())
{
var entity = entityIterator.Current;
bool overwritten = Index_SCALE.Remove(entity.SCALE);
if (entity.SCALE.CompareTo(deltaClusteredKey) <= 0)
{
if (!overwritten)
{
yield return entity;
}
}
else
{
yieldEntity = !overwritten;
break;
}
}
yield return deltaIterator.Current;
if (yieldEntity)
{
yield return entityIterator.Current;
}
}
while (entityIterator.MoveNext())
{
yield return entityIterator.Current;
}
}
}
}
#region Index Fields
private Lazy<Dictionary<short, PML>> Index_SCALE;
#endregion
#region Index Methods
/// <summary>
/// Find PML by SCALE field
/// </summary>
/// <param name="SCALE">SCALE value used to find PML</param>
/// <returns>Related PML entity</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PML FindBySCALE(short SCALE)
{
return Index_SCALE.Value[SCALE];
}
/// <summary>
/// Attempt to find PML by SCALE field
/// </summary>
/// <param name="SCALE">SCALE value used to find PML</param>
/// <param name="Value">Related PML entity</param>
/// <returns>True if the related PML entity is found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public bool TryFindBySCALE(short SCALE, out PML Value)
{
return Index_SCALE.Value.TryGetValue(SCALE, out Value);
}
/// <summary>
/// Attempt to find PML by SCALE field
/// </summary>
/// <param name="SCALE">SCALE value used to find PML</param>
/// <returns>Related PML entity, or null if not found</returns>
/// <exception cref="ArgumentOutOfRangeException">No match was found</exception>
public PML TryFindBySCALE(short SCALE)
{
PML value;
if (Index_SCALE.Value.TryGetValue(SCALE, out value))
{
return value;
}
else
{
return null;
}
}
#endregion
#region SQL Integration
/// <summary>
/// Returns a <see cref="SqlCommand"/> which checks for the existence of a PML table, and if not found, creates the table and associated indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection)
{
return new SqlCommand(
connection: SqlConnection,
cmdText:
@"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PML]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[PML](
[SCALE] smallint NOT NULL,
[WEEKLY_EARNING_THRESHOLD] money NULL,
[WEEKLY_SHADEIN_THRESHOLD] money NULL,
[MEDLEVY_FAMILY_THRESHOLD] money NULL,
[WFT_DIVISOR] float NULL,
[ADDITIONAL_CHILD] money NULL,
[SOP_MULTIPLIER] float NULL,
[SOP_DIVISOR] float NULL,
[WLA_FALCTOR] float NULL,
[MEDICARE_LEVY] float NULL,
[LW_DATE] datetime NULL,
[LW_TIME] smallint NULL,
[LW_USER] varchar(128) NULL,
CONSTRAINT [PML_Index_SCALE] PRIMARY KEY CLUSTERED (
[SCALE] ASC
)
);
END");
}
/// <summary>
/// Returns null as <see cref="PMLDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns null as <see cref="PMLDataSet"/> has no non-clustered indexes.
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <returns>null</returns>
public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection)
{
return null;
}
/// <summary>
/// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PML"/> entities passed
/// </summary>
/// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param>
/// <param name="Entities">The <see cref="PML"/> entities to be deleted</param>
public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PML> Entities)
{
SqlCommand command = new SqlCommand();
int parameterIndex = 0;
StringBuilder builder = new StringBuilder();
List<short> Index_SCALE = new List<short>();
foreach (var entity in Entities)
{
Index_SCALE.Add(entity.SCALE);
}
builder.AppendLine("DELETE [dbo].[PML] WHERE");
// Index_SCALE
builder.Append("[SCALE] IN (");
for (int index = 0; index < Index_SCALE.Count; index++)
{
if (index != 0)
builder.Append(", ");
// SCALE
var parameterSCALE = $"@p{parameterIndex++}";
builder.Append(parameterSCALE);
command.Parameters.Add(parameterSCALE, SqlDbType.SmallInt).Value = Index_SCALE[index];
}
builder.Append(");");
command.Connection = SqlConnection;
command.CommandText = builder.ToString();
return command;
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PML data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PML data set</returns>
public override EduHubDataSetDataReader<PML> GetDataSetDataReader()
{
return new PMLDataReader(Load());
}
/// <summary>
/// Provides a <see cref="IDataReader"/> for the PML data set
/// </summary>
/// <returns>A <see cref="IDataReader"/> for the PML data set</returns>
public override EduHubDataSetDataReader<PML> GetDataSetDataReader(List<PML> Entities)
{
return new PMLDataReader(new EduHubDataSetLoadedReader<PML>(this, Entities));
}
// Modest implementation to primarily support SqlBulkCopy
private class PMLDataReader : EduHubDataSetDataReader<PML>
{
public PMLDataReader(IEduHubDataSetReader<PML> Reader)
: base (Reader)
{
}
public override int FieldCount { get { return 13; } }
public override object GetValue(int i)
{
switch (i)
{
case 0: // SCALE
return Current.SCALE;
case 1: // WEEKLY_EARNING_THRESHOLD
return Current.WEEKLY_EARNING_THRESHOLD;
case 2: // WEEKLY_SHADEIN_THRESHOLD
return Current.WEEKLY_SHADEIN_THRESHOLD;
case 3: // MEDLEVY_FAMILY_THRESHOLD
return Current.MEDLEVY_FAMILY_THRESHOLD;
case 4: // WFT_DIVISOR
return Current.WFT_DIVISOR;
case 5: // ADDITIONAL_CHILD
return Current.ADDITIONAL_CHILD;
case 6: // SOP_MULTIPLIER
return Current.SOP_MULTIPLIER;
case 7: // SOP_DIVISOR
return Current.SOP_DIVISOR;
case 8: // WLA_FALCTOR
return Current.WLA_FALCTOR;
case 9: // MEDICARE_LEVY
return Current.MEDICARE_LEVY;
case 10: // LW_DATE
return Current.LW_DATE;
case 11: // LW_TIME
return Current.LW_TIME;
case 12: // LW_USER
return Current.LW_USER;
default:
throw new ArgumentOutOfRangeException(nameof(i));
}
}
public override bool IsDBNull(int i)
{
switch (i)
{
case 1: // WEEKLY_EARNING_THRESHOLD
return Current.WEEKLY_EARNING_THRESHOLD == null;
case 2: // WEEKLY_SHADEIN_THRESHOLD
return Current.WEEKLY_SHADEIN_THRESHOLD == null;
case 3: // MEDLEVY_FAMILY_THRESHOLD
return Current.MEDLEVY_FAMILY_THRESHOLD == null;
case 4: // WFT_DIVISOR
return Current.WFT_DIVISOR == null;
case 5: // ADDITIONAL_CHILD
return Current.ADDITIONAL_CHILD == null;
case 6: // SOP_MULTIPLIER
return Current.SOP_MULTIPLIER == null;
case 7: // SOP_DIVISOR
return Current.SOP_DIVISOR == null;
case 8: // WLA_FALCTOR
return Current.WLA_FALCTOR == null;
case 9: // MEDICARE_LEVY
return Current.MEDICARE_LEVY == null;
case 10: // LW_DATE
return Current.LW_DATE == null;
case 11: // LW_TIME
return Current.LW_TIME == null;
case 12: // LW_USER
return Current.LW_USER == null;
default:
return false;
}
}
public override string GetName(int ordinal)
{
switch (ordinal)
{
case 0: // SCALE
return "SCALE";
case 1: // WEEKLY_EARNING_THRESHOLD
return "WEEKLY_EARNING_THRESHOLD";
case 2: // WEEKLY_SHADEIN_THRESHOLD
return "WEEKLY_SHADEIN_THRESHOLD";
case 3: // MEDLEVY_FAMILY_THRESHOLD
return "MEDLEVY_FAMILY_THRESHOLD";
case 4: // WFT_DIVISOR
return "WFT_DIVISOR";
case 5: // ADDITIONAL_CHILD
return "ADDITIONAL_CHILD";
case 6: // SOP_MULTIPLIER
return "SOP_MULTIPLIER";
case 7: // SOP_DIVISOR
return "SOP_DIVISOR";
case 8: // WLA_FALCTOR
return "WLA_FALCTOR";
case 9: // MEDICARE_LEVY
return "MEDICARE_LEVY";
case 10: // LW_DATE
return "LW_DATE";
case 11: // LW_TIME
return "LW_TIME";
case 12: // LW_USER
return "LW_USER";
default:
throw new ArgumentOutOfRangeException(nameof(ordinal));
}
}
public override int GetOrdinal(string name)
{
switch (name)
{
case "SCALE":
return 0;
case "WEEKLY_EARNING_THRESHOLD":
return 1;
case "WEEKLY_SHADEIN_THRESHOLD":
return 2;
case "MEDLEVY_FAMILY_THRESHOLD":
return 3;
case "WFT_DIVISOR":
return 4;
case "ADDITIONAL_CHILD":
return 5;
case "SOP_MULTIPLIER":
return 6;
case "SOP_DIVISOR":
return 7;
case "WLA_FALCTOR":
return 8;
case "MEDICARE_LEVY":
return 9;
case "LW_DATE":
return 10;
case "LW_TIME":
return 11;
case "LW_USER":
return 12;
default:
throw new ArgumentOutOfRangeException(nameof(name));
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Elasticsearch.Net;
using Newtonsoft.Json;
namespace Nest
{
/// <summary>
/// Provides the connection settings for NEST's <see cref="ElasticClient"/>
/// </summary>
public class ConnectionSettings : ConnectionSettingsBase<ConnectionSettings>
{
public ConnectionSettings(Uri uri = null)
: this(new SingleNodeConnectionPool(uri ?? new Uri("http://localhost:9200"))) { }
public ConnectionSettings(IConnectionPool connectionPool)
: this(connectionPool, null, new SerializerFactory()) { }
public ConnectionSettings(IConnectionPool connectionPool, IConnection connection)
: this(connectionPool, connection, new SerializerFactory()) { }
public ConnectionSettings(IConnectionPool connectionPool, Func<ConnectionSettings, IElasticsearchSerializer> serializerFactory)
#pragma warning disable CS0618 // Type or member is obsolete
: this(connectionPool, null, serializerFactory) { }
#pragma warning restore CS0618 // Type or member is obsolete
public ConnectionSettings(IConnectionPool connectionPool, IConnection connection, ISerializerFactory serializerFactory)
: base(connectionPool, connection, serializerFactory, s => serializerFactory.Create(s)) { }
[Obsolete("Please use the constructor taking ISerializerFactory instead of a Func")]
public ConnectionSettings(IConnectionPool connectionPool, IConnection connection, Func<ConnectionSettings, IElasticsearchSerializer> serializerFactory)
: base(connectionPool, connection, null, s => serializerFactory?.Invoke(s)) { }
}
/// <summary>
/// Provides the connection settings for NEST's <see cref="ElasticClient"/>
/// </summary>
[Browsable(false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public abstract class ConnectionSettingsBase<TConnectionSettings> : ConnectionConfiguration<TConnectionSettings>, IConnectionSettingsValues
where TConnectionSettings : ConnectionSettingsBase<TConnectionSettings>, IConnectionSettingsValues
{
private string _defaultIndex;
string IConnectionSettingsValues.DefaultIndex => this._defaultIndex;
private readonly Inferrer _inferrer;
Inferrer IConnectionSettingsValues.Inferrer => _inferrer;
private Func<Type, string> _defaultTypeNameInferrer;
Func<Type, string> IConnectionSettingsValues.DefaultTypeNameInferrer => _defaultTypeNameInferrer;
private readonly FluentDictionary<Type, string> _defaultIndices;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultIndices => _defaultIndices;
private readonly FluentDictionary<Type, string> _defaultTypeNames;
FluentDictionary<Type, string> IConnectionSettingsValues.DefaultTypeNames => _defaultTypeNames;
private Func<string, string> _defaultFieldNameInferrer;
Func<string, string> IConnectionSettingsValues.DefaultFieldNameInferrer => _defaultFieldNameInferrer;
private readonly FluentDictionary<Type, string> _idProperties = new FluentDictionary<Type, string>();
FluentDictionary<Type, string> IConnectionSettingsValues.IdProperties => _idProperties;
private readonly FluentDictionary<MemberInfo, IPropertyMapping> _propertyMappings = new FluentDictionary<MemberInfo, IPropertyMapping>();
FluentDictionary<MemberInfo, IPropertyMapping> IConnectionSettingsValues.PropertyMappings => _propertyMappings;
private readonly ISerializerFactory _serializerFactory;
ISerializerFactory IConnectionSettingsValues.SerializerFactory => _serializerFactory;
protected ConnectionSettingsBase(
IConnectionPool connectionPool,
IConnection connection,
ISerializerFactory serializerFactory,
Func<TConnectionSettings, IElasticsearchSerializer> serializerFactoryFunc
)
: base(connectionPool, connection, serializerFactoryFunc)
{
this._defaultTypeNameInferrer = (t => t.Name.ToLowerInvariant());
this._defaultFieldNameInferrer = (p => p.ToCamelCase());
this._defaultIndices = new FluentDictionary<Type, string>();
this._defaultTypeNames = new FluentDictionary<Type, string>();
this._serializerFactory = serializerFactory ?? new SerializerFactory();
this._inferrer = new Inferrer(this);
}
protected ConnectionSettingsBase(
IConnectionPool connectionPool,
IConnection connection,
Func<TConnectionSettings, IElasticsearchSerializer> serializerFactoryFunc
)
: this(connectionPool, connection, null, serializerFactoryFunc) { }
IElasticsearchSerializer IConnectionSettingsValues.StatefulSerializer(JsonConverter converter) =>
this._serializerFactory.CreateStateful(this, converter);
/// <summary>
/// The default serializer for requests and responses
/// </summary>
/// <returns></returns>
protected override IElasticsearchSerializer DefaultSerializer(TConnectionSettings settings) => new JsonNetSerializer(settings);
/// <summary>
/// Pluralize type names when inferring from POCO type names.
/// <para></para>
/// This calls <see cref="DefaultTypeNameInferrer"/> with an implementation that will pluralize type names.
/// This used to be the default prior to Nest 0.90
/// </summary>
public TConnectionSettings PluralizeTypeNames()
{
this._defaultTypeNameInferrer = this.LowerCaseAndPluralizeTypeNameInferrer;
return (TConnectionSettings)this;
}
/// <summary>
/// The default index to use when no index is specified.
/// </summary>
/// <param name="defaultIndex">When null/empty/not set might throw
/// <see cref="NullReferenceException"/> later on when not specifying index explicitly while indexing.
/// </param>
public TConnectionSettings DefaultIndex(string defaultIndex)
{
this._defaultIndex = defaultIndex;
return (TConnectionSettings)this;
}
private string LowerCaseAndPluralizeTypeNameInferrer(Type type)
{
type.ThrowIfNull(nameof(type));
return type.Name.MakePlural().ToLowerInvariant();
}
/// <summary>
/// Specify how field names are inferred from POCO property names.
/// <para></para>
/// By default, NEST camel cases property names
/// e.g. EmailAddress POCO property => "emailAddress" Elasticsearch document field name
/// </summary>
public TConnectionSettings DefaultFieldNameInferrer(Func<string, string> fieldNameInferrer)
{
this._defaultFieldNameInferrer = fieldNameInferrer;
return (TConnectionSettings)this;
}
/// <summary>
/// Specify how type names are inferred from POCO types.
/// By default, type names are inferred by calling <see cref="string.ToLowerInvariant"/>
/// on the type's name.
/// </summary>
public TConnectionSettings DefaultTypeNameInferrer(Func<Type, string> typeNameInferrer)
{
typeNameInferrer.ThrowIfNull(nameof(typeNameInferrer));
this._defaultTypeNameInferrer = typeNameInferrer;
return (TConnectionSettings)this;
}
/// <summary>
/// Specify the default index names for a given POCO type.
/// Takes precedence over the global <see cref="DefaultIndex"/>
/// </summary>
public TConnectionSettings MapDefaultTypeIndices(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull(nameof(mappingSelector));
mappingSelector(this._defaultIndices);
return (TConnectionSettings)this;
}
/// <summary>
/// Specify the default type names for a given POCO type.
/// Takes precedence over the global <see cref="DefaultTypeNameInferrer"/>
/// </summary>
public TConnectionSettings MapDefaultTypeNames(Action<FluentDictionary<Type, string>> mappingSelector)
{
mappingSelector.ThrowIfNull(nameof(mappingSelector));
mappingSelector(this._defaultTypeNames);
return (TConnectionSettings)this;
}
/// <summary>
/// Specify which property on a given POCO should be used to infer the id of the document when
/// indexed in Elasticsearch.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <param name="objectPath">The object path.</param>
/// <returns></returns>
public TConnectionSettings MapIdPropertyFor<TDocument>(Expression<Func<TDocument, object>> objectPath)
{
objectPath.ThrowIfNull(nameof(objectPath));
var memberInfo = new MemberInfoResolver(objectPath);
var fieldName = memberInfo.Members.Single().Name;
if (this._idProperties.ContainsKey(typeof(TDocument)))
{
if (this._idProperties[typeof(TDocument)].Equals(fieldName))
return (TConnectionSettings)this;
throw new ArgumentException($"Cannot map '{fieldName}' as the id property for type '{typeof(TDocument).Name}': it already has '{this._idProperties[typeof(TDocument)]}' mapped.");
}
this._idProperties.Add(typeof(TDocument), fieldName);
return (TConnectionSettings)this;
}
/// <summary>
/// Specify how the properties are mapped for a given POCO type.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <param name="propertiesSelector">The properties selector.</param>
/// <returns></returns>
public TConnectionSettings MapPropertiesFor<TDocument>(Action<PropertyMappingDescriptor<TDocument>> propertiesSelector)
where TDocument : class
{
propertiesSelector.ThrowIfNull(nameof(propertiesSelector));
var mapper = new PropertyMappingDescriptor<TDocument>();
propertiesSelector(mapper);
ApplyPropertyMappings(mapper.Mappings);
return (TConnectionSettings)this;
}
private void ApplyPropertyMappings<TDocument>(IList<IClrTypePropertyMapping<TDocument>> mappings)
where TDocument : class
{
foreach (var mapping in mappings)
{
var e = mapping.Property;
var memberInfoResolver = new MemberInfoResolver(e);
if (memberInfoResolver.Members.Count > 1)
throw new ArgumentException($"{nameof(ApplyPropertyMappings)} can only map direct properties");
if (memberInfoResolver.Members.Count < 1)
throw new ArgumentException($"Expression {e} does contain any member access");
var memberInfo = memberInfoResolver.Members.Last();
if (_propertyMappings.ContainsKey(memberInfo))
{
var newName = mapping.NewName;
var mappedAs = _propertyMappings[memberInfo].Name;
var typeName = typeof(TDocument).Name;
if (mappedAs.IsNullOrEmpty() && newName.IsNullOrEmpty())
throw new ArgumentException($"Property mapping '{e}' on type is already ignored");
if (mappedAs.IsNullOrEmpty())
throw new ArgumentException($"Property mapping '{e}' on type {typeName} can not be mapped to '{newName}' it already has an ignore mapping");
if (newName.IsNullOrEmpty())
throw new ArgumentException($"Property mapping '{e}' on type {typeName} can not be ignored it already has a mapping to '{mappedAs}'");
throw new ArgumentException($"Property mapping '{e}' on type {typeName} can not be mapped to '{newName}' already mapped as '{mappedAs}'");
}
_propertyMappings.Add(memberInfo, mapping.ToPropertyMapping());
}
}
/// <summary>
/// Specify how the mapping is inferred for a given POCO type.
/// Can be used to infer the index, type, id property and properties for the POCO.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
/// <param name="selector">The selector.</param>
/// <returns></returns>
public TConnectionSettings InferMappingFor<TDocument>(Func<ClrTypeMappingDescriptor<TDocument>, IClrTypeMapping<TDocument>> selector)
where TDocument : class
{
var inferMapping = selector(new ClrTypeMappingDescriptor<TDocument>());
if (!inferMapping.IndexName.IsNullOrEmpty())
this._defaultIndices.Add(inferMapping.Type, inferMapping.IndexName);
if (!inferMapping.TypeName.IsNullOrEmpty())
this._defaultTypeNames.Add(inferMapping.Type, inferMapping.TypeName);
if (inferMapping.IdProperty != null)
#pragma warning disable CS0618 // Type or member is obsolete but will be private in the future OK to call here
this.MapIdPropertyFor<TDocument>(inferMapping.IdProperty);
#pragma warning restore CS0618
if (inferMapping.Properties != null)
this.ApplyPropertyMappings<TDocument>(inferMapping.Properties);
return (TConnectionSettings)this;
}
}
}
| |
/*
* Copyright (c) 2015, InWorldz Halcyon Developers
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of halcyon nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenMetaverse;
using OpenSim.Region.Framework.Scenes;
namespace InWorldz.Region.Data.Thoosa.Tests
{
internal class Util
{
private readonly static Random rand = new Random();
public static Vector3 RandomVector()
{
return new Vector3((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
public static Quaternion RandomQuat()
{
return new Quaternion((float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble(), (float)rand.NextDouble());
}
internal static byte RandomByte()
{
return (byte)rand.Next(byte.MaxValue);
}
public static SceneObjectPart RandomSOP(string name, uint localId)
{
var shape = new OpenSim.Framework.PrimitiveBaseShape();
shape.ExtraParams = new byte[] { 0xA, 0x9, 0x8, 0x7, 0x6, 0x5 };
shape.FlexiDrag = 0.3f;
shape.FlexiEntry = true;
shape.FlexiForceX = 1.0f;
shape.FlexiForceY = 2.0f;
shape.FlexiForceZ = 3.0f;
shape.FlexiGravity = 10.0f;
shape.FlexiSoftness = 1;
shape.FlexiTension = 999.4f;
shape.FlexiWind = 9292.33f;
shape.HollowShape = OpenSim.Framework.HollowShape.Square;
shape.LightColorA = 0.3f;
shape.LightColorB = 0.22f;
shape.LightColorG = 0.44f;
shape.LightColorR = 0.77f;
shape.LightCutoff = 0.4f;
shape.LightEntry = true;
shape.LightFalloff = 7474;
shape.LightIntensity = 0.0f;
shape.LightRadius = 10.0f;
shape.Media = new OpenSim.Framework.PrimitiveBaseShape.PrimMedia();
shape.Media.New(2);
shape.Media[0] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "bam.com",
EnableAlterntiveImage = true,
EnableWhiteList = false,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "yo mamma" },
Width = 5
};
shape.Media[1] = new MediaEntry
{
AutoLoop = true,
AutoPlay = true,
AutoScale = true,
AutoZoom = true,
ControlPermissions = MediaPermission.All,
Controls = MediaControls.Standard,
CurrentURL = "kabam.com",
EnableAlterntiveImage = true,
EnableWhiteList = true,
Height = 1,
HomeURL = "anotherbam.com",
InteractOnFirstClick = true,
InteractPermissions = MediaPermission.Group,
WhiteList = new string[] { "ur mamma" },
Width = 5
};
shape.PathBegin = 3;
shape.PathCurve = 127;
shape.PathEnd = 10;
shape.PathRadiusOffset = 127;
shape.PathRevolutions = 2;
shape.PathScaleX = 50;
shape.PathScaleY = 100;
shape.PathShearX = 33;
shape.PathShearY = 44;
shape.PathSkew = 126;
shape.PathTaperX = 110;
shape.PathTaperY = 66;
shape.PathTwist = 99;
shape.PathTwistBegin = 3;
shape.PCode = 3;
shape.PreferredPhysicsShape = PhysicsShapeType.Prim;
shape.ProfileBegin = 77;
shape.ProfileCurve = 5;
shape.ProfileEnd = 7;
shape.ProfileHollow = 9;
shape.ProfileShape = OpenSim.Framework.ProfileShape.IsometricTriangle;
shape.ProjectionAmbiance = 0.1f;
shape.ProjectionEntry = true;
shape.ProjectionFocus = 3.4f;
shape.ProjectionFOV = 4.0f;
shape.ProjectionTextureUUID = UUID.Random();
shape.Scale = Util.RandomVector();
shape.SculptEntry = true;
shape.SculptTexture = UUID.Random();
shape.SculptType = 40;
shape.VertexCount = 1;
shape.HighLODBytes = 2;
shape.MidLODBytes = 3;
shape.LowLODBytes = 4;
shape.LowestLODBytes = 5;
SceneObjectPart part = new SceneObjectPart(UUID.Zero, shape, new Vector3(1, 2, 3), new Quaternion(4, 5, 6, 7), Vector3.Zero, false);
part.Name = name;
part.Description = "Desc";
part.AngularVelocity = Util.RandomVector();
part.BaseMask = 0x0876;
part.Category = 10;
part.ClickAction = 5;
part.CollisionSound = UUID.Random();
part.CollisionSoundVolume = 1.1f;
part.CreationDate = OpenSim.Framework.Util.UnixTimeSinceEpoch();
part.CreatorID = UUID.Random();
part.EveryoneMask = 0x0543;
part.Flags = PrimFlags.CameraSource | PrimFlags.DieAtEdge;
part.GroupID = UUID.Random();
part.GroupMask = 0x0210;
part.LastOwnerID = UUID.Random();
part.LinkNum = 4;
part.LocalId = localId;
part.Material = 0x1;
part.MediaUrl = "http://bam";
part.NextOwnerMask = 0x0234;
part.CreatorID = UUID.Random();
part.ObjectFlags = 10101;
part.OwnerID = UUID.Random();
part.OwnerMask = 0x0567;
part.OwnershipCost = 5;
part.ParentID = 0202;
part.ParticleSystem = new byte[] { 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.PassTouches = true;
part.PhysicalAngularVelocity = Util.RandomVector();
part.RegionHandle = 1234567;
part.RegionID = UUID.Random();
part.RotationOffset = Util.RandomQuat();
part.SalePrice = 42;
part.SavedAttachmentPoint = 6;
part.SavedAttachmentPos = Util.RandomVector();
part.SavedAttachmentRot = Util.RandomQuat();
part.ScriptAccessPin = 87654;
part.SerializedPhysicsData = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, };
part.ServerWeight = 3.0f;
part.StreamingCost = 2.0f;
part.SitName = "Sitting";
part.SitTargetOrientation = Util.RandomQuat();
part.SitTargetPosition = Util.RandomVector();
part.Sound = UUID.Random();
part.SoundGain = 3.4f;
part.SoundOptions = 9;
part.SoundRadius = 10.3f;
part.Text = "Test";
part.TextColor = System.Drawing.Color.FromArgb(1, 2, 3, 4);
part.TextureAnimation = new byte[] { 0xA, 0xB, 0xC, 0xD, 0xE, 0x6, 0x7, 0x8, 0x9, 0xA, 0xB, 0xC, 0xD };
part.TouchName = "DoIt";
part.UUID = UUID.Random();
part.Velocity = Util.RandomVector();
part.FromItemID = UUID.Random();
return part;
}
}
}
| |
// 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.Security;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace System.Net.Security
{
// SecureChannel - a wrapper on SSPI based functionality.
// Provides an additional abstraction layer over SSPI for SslStream.
internal class SecureChannel
{
// When reading a frame from the wire first read this many bytes for the header.
internal const int ReadHeaderSize = 5;
private SafeFreeCredentials _credentialsHandle;
private SafeDeleteContext _securityContext;
private readonly string _destination;
private readonly string _hostName;
private readonly bool _serverMode;
private readonly bool _remoteCertRequired;
private readonly SslProtocols _sslProtocols;
private readonly EncryptionPolicy _encryptionPolicy;
private SslConnectionInfo _connectionInfo;
private X509Certificate _serverCertificate;
private X509Certificate _selectedClientCertificate;
private bool _isRemoteCertificateAvailable;
private readonly X509CertificateCollection _clientCertificates;
private LocalCertSelectionCallback _certSelectionDelegate;
// These are the MAX encrypt buffer output sizes, not the actual sizes.
private int _headerSize = 5; //ATTN must be set to at least 5 by default
private int _trailerSize = 16;
private int _maxDataSize = 16354;
private bool _checkCertRevocation;
private bool _checkCertName;
private bool _refreshCredentialNeeded;
internal SecureChannel(string hostname, bool serverMode, SslProtocols sslProtocols, X509Certificate serverCertificate, X509CertificateCollection clientCertificates, bool remoteCertRequired, bool checkCertName,
bool checkCertRevocationStatus, EncryptionPolicy encryptionPolicy, LocalCertSelectionCallback certSelectionDelegate)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor", "hostname:" + hostname + " #clientCertificates=" + ((clientCertificates == null) ? "0" : clientCertificates.Count.ToString(NumberFormatInfo.InvariantInfo)));
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.SecureChannelCtor(this, hostname, clientCertificates, encryptionPolicy);
}
SslStreamPal.VerifyPackageInfo();
_destination = hostname;
if (hostname == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.AssertFormat("SecureChannel#{0}::.ctor()|hostname == null", LoggingHash.HashString(this));
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor()|hostname == null");
}
_hostName = hostname;
_serverMode = serverMode;
_sslProtocols = sslProtocols;
_serverCertificate = serverCertificate;
_clientCertificates = clientCertificates;
_remoteCertRequired = remoteCertRequired;
_securityContext = null;
_checkCertRevocation = checkCertRevocationStatus;
_checkCertName = checkCertName;
_certSelectionDelegate = certSelectionDelegate;
_refreshCredentialNeeded = true;
_encryptionPolicy = encryptionPolicy;
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::.ctor");
}
}
//
// SecureChannel properties
//
// LocalServerCertificate - local certificate for server mode channel
// LocalClientCertificate - selected certificated used in the client channel mode otherwise null
// IsRemoteCertificateAvailable - true if the remote side has provided a certificate
// HeaderSize - Header & trailer sizes used in the TLS stream
// TrailerSize -
//
internal X509Certificate LocalServerCertificate
{
get
{
return _serverCertificate;
}
}
internal X509Certificate LocalClientCertificate
{
get
{
return _selectedClientCertificate;
}
}
internal bool IsRemoteCertificateAvailable
{
get
{
return _isRemoteCertificateAvailable;
}
}
internal ChannelBinding GetChannelBinding(ChannelBindingKind kind)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", kind.ToString());
}
ChannelBinding result = null;
if (_securityContext != null)
{
result = SslStreamPal.QueryContextChannelBinding(_securityContext, kind);
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GetChannelBindingToken", LoggingHash.HashString(result));
}
return result;
}
internal bool CheckCertRevocationStatus
{
get
{
return _checkCertRevocation;
}
}
internal X509CertificateCollection ClientCertificates
{
get
{
return _clientCertificates;
}
}
internal int HeaderSize
{
get
{
return _headerSize;
}
}
internal int MaxDataSize
{
get
{
return _maxDataSize;
}
}
internal SslConnectionInfo ConnectionInfo
{
get
{
return _connectionInfo;
}
}
internal bool IsValidContext
{
get
{
return !(_securityContext == null || _securityContext.IsInvalid);
}
}
internal bool IsServer
{
get
{
return _serverMode;
}
}
internal bool RemoteCertRequired
{
get
{
return _remoteCertRequired;
}
}
internal void SetRefreshCredentialNeeded()
{
_refreshCredentialNeeded = true;
}
internal void Close()
{
if (_securityContext != null)
{
_securityContext.Dispose();
}
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
}
//
// SECURITY: we open a private key container on behalf of the caller
// and we require the caller to have permission associated with that operation.
//
private X509Certificate2 EnsurePrivateKey(X509Certificate certificate)
{
if (certificate == null)
{
return null;
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.LocatingPrivateKey(certificate.ToString(true), LoggingHash.HashInt(this));
}
try
{
string certHash = null;
// Protecting from X509Certificate2 derived classes.
X509Certificate2 certEx = MakeEx(certificate);
certHash = certEx.Thumbprint;
if (certEx != null)
{
if (certEx.HasPrivateKey)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.CertIsType2(LoggingHash.HashInt(this));
}
return certEx;
}
if ((object)certificate != (object)certEx)
{
certEx.Dispose();
}
}
X509Certificate2Collection collectionEx;
// ELSE Try the MY user and machine stores for private key check.
// For server side mode MY machine store takes priority.
X509Store store = CertificateValidationPal.EnsureStoreOpened(_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this));
}
return collectionEx[0];
}
}
store = CertificateValidationPal.EnsureStoreOpened(!_serverMode);
if (store != null)
{
collectionEx = store.Certificates.Find(X509FindType.FindByThumbprint, certHash, false);
if (collectionEx.Count > 0 && collectionEx[0].HasPrivateKey)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.FoundCertInStore((_serverMode ? "LocalMachine" : "CurrentUser"), LoggingHash.HashInt(this));
}
return collectionEx[0];
}
}
}
catch (CryptographicException)
{
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.NotFoundCertInStore(LoggingHash.HashInt(this));
}
return null;
}
private static X509Certificate2 MakeEx(X509Certificate certificate)
{
Debug.Assert(certificate != null, "certificate != null");
if (certificate.GetType() == typeof(X509Certificate2))
{
return (X509Certificate2)certificate;
}
X509Certificate2 certificateEx = null;
try
{
if (certificate.Handle != IntPtr.Zero)
{
certificateEx = new X509Certificate2(certificate.Handle);
}
}
catch (SecurityException) { }
catch (CryptographicException) { }
return certificateEx;
}
//
// Get certificate_authorities list, according to RFC 5246, Section 7.4.4.
// Used only by client SSL code, never returns null.
//
private string[] GetRequestCertificateAuthorities()
{
string[] issuers = Array.Empty<string>();
if (IsValidContext)
{
issuers = CertificateValidationPal.GetRequestCertificateAuthorities(_securityContext);
}
return issuers;
}
/*++
AcquireCredentials - Attempts to find Client Credential
Information, that can be sent to the server. In our case,
this is only Client Certificates, that we have Credential Info.
How it works:
case 0: Cert Selection delegate is present
Always use its result as the client cert answer.
Try to use cached credential handle whenever feasible.
Do not use cached anonymous creds if the delegate has returned null
and the collection is not empty (allow responding with the cert later).
case 1: Certs collection is empty
Always use the same statically acquired anonymous SSL Credential
case 2: Before our Connection with the Server
If we have a cached credential handle keyed by first X509Certificate
**content** in the passed collection, then we use that cached
credential and hoping to restart a session.
Otherwise create a new anonymous (allow responding with the cert later).
case 3: After our Connection with the Server (i.e. during handshake or re-handshake)
The server has requested that we send it a Certificate then
we Enumerate a list of server sent Issuers trying to match against
our list of Certificates, the first match is sent to the server.
Once we got a cert we again try to match cached credential handle if possible.
This will not restart a session but helps minimizing the number of handles we create.
In the case of an error getting a Certificate or checking its private Key we fall back
to the behavior of having no certs, case 1.
Returns: True if cached creds were used, false otherwise.
--*/
private bool AcquireClientCredentials(ref byte[] thumbPrint)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials");
}
// Acquire possible Client Certificate information and set it on the handle.
X509Certificate clientCertificate = null; // This is a candidate that can come from the user callback or be guessed when targeting a session restart.
var filteredCerts = new List<X509Certificate>(); // This is an intermediate client certs collection that try to use if no selectedCert is available yet.
string[] issuers = null; // This is a list of issuers sent by the server, only valid is we do know what the server cert is.
bool sessionRestartAttempt = false; // If true and no cached creds we will use anonymous creds.
if (_certSelectionDelegate != null)
{
issuers = GetRequestCertificateAuthorities();
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() calling CertificateSelectionCallback");
}
X509Certificate2 remoteCert = null;
try
{
X509Certificate2Collection dummyCollection;
remoteCert = CertificateValidationPal.GetRemoteCertificate(_securityContext, out dummyCollection);
clientCertificate = _certSelectionDelegate(_hostName, ClientCertificates, remoteCert, issuers);
}
finally
{
if (remoteCert != null)
{
remoteCert.Dispose();
}
}
if (clientCertificate != null)
{
if (_credentialsHandle == null)
{
sessionRestartAttempt = true;
}
filteredCerts.Add(clientCertificate);
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.CertificateFromDelegate(LoggingHash.HashInt(this));
}
}
else
{
if (ClientCertificates.Count == 0)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.NoDelegateNoClientCert(LoggingHash.HashInt(this));
}
sessionRestartAttempt = true;
}
else
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.NoDelegateButClientCert(LoggingHash.HashInt(this));
}
}
}
}
else if (_credentialsHandle == null && _clientCertificates != null && _clientCertificates.Count > 0)
{
// This is where we attempt to restart a session by picking the FIRST cert from the collection.
// Otherwise it is either server sending a client cert request or the session is renegotiated.
clientCertificate = ClientCertificates[0];
sessionRestartAttempt = true;
if (clientCertificate != null)
{
filteredCerts.Add(clientCertificate);
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.AttemptingRestartUsingCert(clientCertificate == null ? "null" : clientCertificate.ToString(true), LoggingHash.HashInt(this));
}
}
else if (_clientCertificates != null && _clientCertificates.Count > 0)
{
//
// This should be a server request for the client cert sent over currently anonymous sessions.
//
issuers = GetRequestCertificateAuthorities();
if (SecurityEventSource.Log.IsEnabled())
{
if (issuers == null || issuers.Length == 0)
{
SecurityEventSource.Log.NoIssuersTryAllCerts(LoggingHash.HashInt(this));
}
else
{
SecurityEventSource.Log.LookForMatchingCerts(issuers.Length, LoggingHash.HashInt(this));
}
}
for (int i = 0; i < _clientCertificates.Count; ++i)
{
//
// Make sure we add only if the cert matches one of the issuers.
// If no issuers were sent and then try all client certs starting with the first one.
//
if (issuers != null && issuers.Length != 0)
{
X509Certificate2 certificateEx = null;
X509Chain chain = null;
try
{
certificateEx = MakeEx(_clientCertificates[i]);
if (certificateEx == null)
{
continue;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() root cert:" + certificateEx.Issuer);
}
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreInvalidName;
chain.Build(certificateEx);
bool found = false;
//
// We ignore any errors happened with chain.
//
if (chain.ChainElements.Count > 0)
{
for (int ii = 0; ii < chain.ChainElements.Count; ++ii)
{
string issuer = chain.ChainElements[ii].Certificate.Issuer;
found = Array.IndexOf(issuers, issuer) != -1;
if (found)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() matched:" + issuer);
}
break;
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() no match:" + issuer);
}
}
}
if (!found)
{
continue;
}
}
finally
{
if (chain != null)
{
chain.Dispose();
}
if (certificateEx != null && (object)certificateEx != (object)_clientCertificates[i])
{
certificateEx.Dispose();
}
}
}
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.SelectedCert(_clientCertificates[i].ToString(true), LoggingHash.HashInt(this));
}
filteredCerts.Add(_clientCertificates[i]);
}
}
bool cachedCred = false; // This is a return result from this method.
X509Certificate2 selectedCert = null; // This is a final selected cert (ensured that it does have private key with it).
clientCertificate = null;
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.CertsAfterFiltering(filteredCerts.Count, LoggingHash.HashInt(this));
if (filteredCerts.Count != 0)
{
SecurityEventSource.Log.FindingMatchingCerts(LoggingHash.HashInt(this));
}
}
//
// ATTN: When the client cert was returned by the user callback OR it was guessed AND it has no private key,
// THEN anonymous (no client cert) credential will be used.
//
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
for (int i = 0; i < filteredCerts.Count; ++i)
{
clientCertificate = filteredCerts[i];
if ((selectedCert = EnsurePrivateKey(clientCertificate)) != null)
{
break;
}
clientCertificate = null;
selectedCert = null;
}
if ((object)clientCertificate != (object)selectedCert && !clientCertificate.Equals(selectedCert))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");
}
Debug.Fail("AcquireClientCredentials()|'selectedCert' does not match 'clientCertificate'.");
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Selected Cert = " + (selectedCert == null ? "null" : selectedCert.Subject));
}
try
{
// Try to locate cached creds first.
//
// SECURITY: selectedCert ref if not null is a safe object that does not depend on possible **user** inherited X509Certificate type.
//
byte[] guessedThumbPrint = selectedCert == null ? null : selectedCert.GetCertHash();
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
// We can probably do some optimization here. If the selectedCert is returned by the delegate
// we can always go ahead and use the certificate to create our credential
// (instead of going anonymous as we do here).
if (sessionRestartAttempt &&
cachedCredentialHandle == null &&
selectedCert != null &&
SslStreamPal.StartMutualAuthAsAnonymous)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials() Reset to anonymous session.");
}
// IIS does not renegotiate a restarted session if client cert is needed.
// So we don't want to reuse **anonymous** cached credential for a new SSL connection if the client has passed some certificate.
// The following block happens if client did specify a certificate but no cached creds were found in the cache.
// Since we don't restart a session the server side can still challenge for a client cert.
if ((object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
guessedThumbPrint = null;
selectedCert = null;
clientCertificate = null;
}
if (cachedCredentialHandle != null)
{
if (SecurityEventSource.Log.IsEnabled())
{
SecurityEventSource.Log.UsingCachedCredential(LoggingHash.HashInt(this));
}
_credentialsHandle = cachedCredentialHandle;
_selectedClientCertificate = clientCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
thumbPrint = guessedThumbPrint; // Delay until here in case something above threw.
_selectedClientCertificate = clientCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if (selectedCert != null && (object)clientCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireClientCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle));
}
return cachedCred;
}
//
// Acquire Server Side Certificate information and set it on the class.
//
private bool AcquireServerCredentials(ref byte[] thumbPrint)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials");
}
X509Certificate localCertificate = null;
bool cachedCred = false;
if (_certSelectionDelegate != null)
{
X509CertificateCollection tempCollection = new X509CertificateCollection();
tempCollection.Add(_serverCertificate);
localCertificate = _certSelectionDelegate(string.Empty, tempCollection, null, Array.Empty<string>());
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials() Use delegate selected Cert");
}
}
else
{
localCertificate = _serverCertificate;
}
if (localCertificate == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
// SECURITY: Accessing X509 cert Credential is disabled for semitrust.
// We no longer need to demand for unmanaged code permissions.
// EnsurePrivateKey should do the right demand for us.
X509Certificate2 selectedCert = EnsurePrivateKey(localCertificate);
if (selectedCert == null)
{
throw new NotSupportedException(SR.net_ssl_io_no_server_cert);
}
if (!localCertificate.Equals(selectedCert))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");
}
Debug.Fail("AcquireServerCredentials()|'selectedCert' does not match 'localCertificate'.");
}
//
// Note selectedCert is a safe ref possibly cloned from the user passed Cert object
//
byte[] guessedThumbPrint = selectedCert.GetCertHash();
try
{
SafeFreeCredentials cachedCredentialHandle = SslSessionsCache.TryCachedCredential(guessedThumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
if (cachedCredentialHandle != null)
{
_credentialsHandle = cachedCredentialHandle;
_serverCertificate = localCertificate;
cachedCred = true;
}
else
{
_credentialsHandle = SslStreamPal.AcquireCredentialsHandle(selectedCert, _sslProtocols, _encryptionPolicy, _serverMode);
thumbPrint = guessedThumbPrint;
_serverCertificate = localCertificate;
}
}
finally
{
// An extra cert could have been created, dispose it now.
if ((object)localCertificate != (object)selectedCert)
{
selectedCert.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::AcquireServerCredentials, cachedCreds = " + cachedCred.ToString(), LoggingHash.ObjectToString(_credentialsHandle));
}
return cachedCred;
}
//
internal ProtocolToken NextMessage(byte[] incoming, int offset, int count)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage");
}
byte[] nextmsg = null;
SecurityStatusPal status = GenerateToken(incoming, offset, count, ref nextmsg);
if (!_serverMode && status.ErrorCode == SecurityStatusPalErrorCode.CredentialsNeeded)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage() returned SecurityStatusPal.CredentialsNeeded");
}
SetRefreshCredentialNeeded();
status = GenerateToken(incoming, offset, count, ref nextmsg);
}
ProtocolToken token = new ProtocolToken(nextmsg, status);
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::NextMessage", token.ToString());
}
return token;
}
/*++
GenerateToken - Called after each successive state
in the Client - Server handshake. This function
generates a set of bytes that will be sent next to
the server. The server responds, each response,
is pass then into this function, again, and the cycle
repeats until successful connection, or failure.
Input:
input - bytes from the wire
output - ref to byte [], what we will send to the
server in response
Return:
status - error information
--*/
private SecurityStatusPal GenerateToken(byte[] input, int offset, int count, ref byte[] output)
{
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken, _refreshCredentialNeeded = " + _refreshCredentialNeeded);
}
#endif
if (offset < 0 || offset > (input == null ? 0 : input.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (input == null ? 0 : input.Length - offset))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
SecurityBuffer incomingSecurity = null;
SecurityBuffer[] incomingSecurityBuffers = null;
if (input != null)
{
incomingSecurity = new SecurityBuffer(input, offset, count, SecurityBufferType.Token);
incomingSecurityBuffers = new SecurityBuffer[]
{
incomingSecurity,
new SecurityBuffer(null, 0, 0, SecurityBufferType.Empty)
};
}
SecurityBuffer outgoingSecurity = new SecurityBuffer(null, SecurityBufferType.Token);
SecurityStatusPal status = default(SecurityStatusPal);
bool cachedCreds = false;
byte[] thumbPrint = null;
//
// Looping through ASC or ISC with potentially cached credential that could have been
// already disposed from a different thread before ISC or ASC dir increment a cred ref count.
//
try
{
do
{
thumbPrint = null;
if (_refreshCredentialNeeded)
{
cachedCreds = _serverMode
? AcquireServerCredentials(ref thumbPrint)
: AcquireClientCredentials(ref thumbPrint);
}
if (_serverMode)
{
status = SslStreamPal.AcceptSecurityContext(
ref _credentialsHandle,
ref _securityContext,
incomingSecurity,
outgoingSecurity,
_remoteCertRequired);
}
else
{
if (incomingSecurity == null)
{
status = SslStreamPal.InitializeSecurityContext(
ref _credentialsHandle,
ref _securityContext,
_destination,
incomingSecurity,
outgoingSecurity);
}
else
{
status = SslStreamPal.InitializeSecurityContext(
_credentialsHandle,
ref _securityContext,
_destination,
incomingSecurityBuffers,
outgoingSecurity);
}
}
} while (cachedCreds && _credentialsHandle == null);
}
finally
{
if (_refreshCredentialNeeded)
{
_refreshCredentialNeeded = false;
//
// Assuming the ISC or ASC has referenced the credential,
// we want to call dispose so to decrement the effective ref count.
//
if (_credentialsHandle != null)
{
_credentialsHandle.Dispose();
}
//
// This call may bump up the credential reference count further.
// Note that thumbPrint is retrieved from a safe cert object that was possible cloned from the user passed cert.
//
if (!cachedCreds && _securityContext != null && !_securityContext.IsInvalid && _credentialsHandle != null && !_credentialsHandle.IsInvalid)
{
SslSessionsCache.CacheCredential(_credentialsHandle, thumbPrint, _sslProtocols, _serverMode, _encryptionPolicy);
}
}
}
output = outgoingSecurity.token;
#if TRACE_VERBOSE
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::GenerateToken()", Interop.MapSecurityStatus((uint)errorCode));
}
#endif
return status;
}
/*++
ProcessHandshakeSuccess -
Called on successful completion of Handshake -
used to set header/trailer sizes for encryption use
Fills in the information about established protocol
--*/
internal void ProcessHandshakeSuccess()
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess");
}
StreamSizes streamSizes;
SslStreamPal.QueryContextStreamSizes(_securityContext, out streamSizes);
if (streamSizes != null)
{
try
{
_headerSize = streamSizes.header;
_trailerSize = streamSizes.trailer;
_maxDataSize = checked(streamSizes.maximumMessage - (_headerSize + _trailerSize));
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess", "StreamSizes out of range.");
}
throw;
}
}
SslStreamPal.QueryContextConnectionInfo(_securityContext, out _connectionInfo);
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::ProcessHandshakeSuccess");
}
}
/*++
Encrypt - Encrypts our bytes before we send them over the wire
PERF: make more efficient, this does an extra copy when the offset
is non-zero.
Input:
buffer - bytes for sending
offset -
size -
output - Encrypted bytes
--*/
internal SecurityStatusPal Encrypt(byte[] buffer, int offset, int size, ref byte[] output, out int resultSize)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt");
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() - offset: " + offset.ToString() + " size: " + size.ToString() + " buffersize: " + buffer.Length.ToString());
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt() buffer:");
GlobalLog.Dump(buffer, Math.Min(buffer.Length, 128));
}
byte[] writeBuffer;
try
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (size < 0 || size > (buffer == null ? 0 : buffer.Length - offset))
{
throw new ArgumentOutOfRangeException(nameof(size));
}
resultSize = 0;
int bufferSizeNeeded = checked(size + _headerSize + _trailerSize);
if (output != null && bufferSizeNeeded <= output.Length)
{
writeBuffer = output;
}
else
{
writeBuffer = new byte[bufferSizeNeeded];
}
Buffer.BlockCopy(buffer, offset, writeBuffer, _headerSize, size);
}
catch (Exception e)
{
if (!ExceptionCheck.IsFatal(e))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Arguments out of range.");
}
throw;
}
SecurityStatusPal secStatus = SslStreamPal.EncryptMessage(_securityContext, writeBuffer, size, _headerSize, _trailerSize, out resultSize);
if (secStatus.ErrorCode != SecurityStatusPalErrorCode.OK)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt ERROR", secStatus.ToString());
}
}
else
{
output = writeBuffer;
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt OK", "data size:" + resultSize.ToString());
}
}
return secStatus;
}
internal SecurityStatusPal Decrypt(byte[] payload, ref int offset, ref int count)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::Decrypt() - offset: " + offset.ToString() + " size: " + count.ToString() + " buffersize: " + payload.Length.ToString());
}
if (offset < 0 || offset > (payload == null ? 0 : payload.Length))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (payload == null ? 0 : payload.Length - offset))
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Assert("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range.");
}
Debug.Fail("SecureChannel#" + LoggingHash.HashString(this) + "::Encrypt", "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
SecurityStatusPal secStatus = SslStreamPal.DecryptMessage(_securityContext, payload, ref offset, ref count);
return secStatus;
}
/*++
VerifyRemoteCertificate - Validates the content of a Remote Certificate
checkCRL if true, checks the certificate revocation list for validity.
checkCertName, if true checks the CN field of the certificate
--*/
//This method validates a remote certificate.
//SECURITY: The scenario is allowed in semitrust StorePermission is asserted for Chain.Build
// A user callback has unique signature so it is safe to call it under permission assert.
//
internal bool VerifyRemoteCertificate(RemoteCertValidationCallback remoteCertValidationCallback)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Enter("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate");
}
SslPolicyErrors sslPolicyErrors = SslPolicyErrors.None;
// We don't catch exceptions in this method, so it's safe for "accepted" be initialized with true.
bool success = false;
X509Chain chain = null;
X509Certificate2 remoteCertificateEx = null;
try
{
X509Certificate2Collection remoteCertificateStore;
remoteCertificateEx = CertificateValidationPal.GetRemoteCertificate(_securityContext, out remoteCertificateStore);
_isRemoteCertificateAvailable = remoteCertificateEx != null;
if (remoteCertificateEx == null)
{
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate (no remote cert)", (!_remoteCertRequired).ToString());
}
sslPolicyErrors |= SslPolicyErrors.RemoteCertificateNotAvailable;
}
else
{
chain = new X509Chain();
chain.ChainPolicy.RevocationMode = _checkCertRevocation ? X509RevocationMode.Online : X509RevocationMode.NoCheck;
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot;
if (remoteCertificateStore != null)
{
chain.ChainPolicy.ExtraStore.AddRange(remoteCertificateStore);
}
sslPolicyErrors |= CertificateValidationPal.VerifyCertificateProperties(
chain,
remoteCertificateEx,
_checkCertName,
_serverMode,
_hostName);
}
if (remoteCertValidationCallback != null)
{
success = remoteCertValidationCallback(_hostName, remoteCertificateEx, chain, sslPolicyErrors);
}
else
{
if (sslPolicyErrors == SslPolicyErrors.RemoteCertificateNotAvailable && !_remoteCertRequired)
{
success = true;
}
else
{
success = (sslPolicyErrors == SslPolicyErrors.None);
}
}
if (SecurityEventSource.Log.IsEnabled())
{
if (sslPolicyErrors != SslPolicyErrors.None)
{
SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_has_errors);
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != 0)
{
SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_not_available);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateNameMismatch) != 0)
{
SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), SR.net_log_remote_cert_name_mismatch);
}
if ((sslPolicyErrors & SslPolicyErrors.RemoteCertificateChainErrors) != 0)
{
string chainStatusString = "ChainStatus: ";
foreach (X509ChainStatus chainStatus in chain.ChainStatus)
{
chainStatusString += "\t" + chainStatus.StatusInformation;
}
SecurityEventSource.Log.RemoteCertificateError(LoggingHash.HashInt(this), chainStatusString);
}
}
if (success)
{
if (remoteCertValidationCallback != null)
{
SecurityEventSource.Log.RemoteCertDeclaredValid(LoggingHash.HashInt(this));
}
else
{
SecurityEventSource.Log.RemoteCertHasNoErrors(LoggingHash.HashInt(this));
}
}
else
{
if (remoteCertValidationCallback != null)
{
SecurityEventSource.Log.RemoteCertUserDeclaredInvalid(LoggingHash.HashInt(this));
}
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Print("Cert Validation, remote cert = " + (remoteCertificateEx == null ? "<null>" : remoteCertificateEx.ToString(true)));
}
}
finally
{
// At least on Win2k server the chain is found to have dependencies on the original cert context.
// So it should be closed first.
if (chain != null)
{
chain.Dispose();
}
if (remoteCertificateEx != null)
{
remoteCertificateEx.Dispose();
}
}
if (GlobalLog.IsEnabled)
{
GlobalLog.Leave("SecureChannel#" + LoggingHash.HashString(this) + "::VerifyRemoteCertificate", success.ToString());
}
return success;
}
}
// ProtocolToken - used to process and handle the return codes from the SSPI wrapper
internal class ProtocolToken
{
internal SecurityStatusPal Status;
internal byte[] Payload;
internal int Size;
internal bool Failed
{
get
{
return ((Status.ErrorCode != SecurityStatusPalErrorCode.OK) && (Status.ErrorCode != SecurityStatusPalErrorCode.ContinueNeeded));
}
}
internal bool Done
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.OK);
}
}
internal bool Renegotiate
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.Renegotiate);
}
}
internal bool CloseConnection
{
get
{
return (Status.ErrorCode == SecurityStatusPalErrorCode.ContextExpired);
}
}
internal ProtocolToken(byte[] data, SecurityStatusPal status)
{
Status = status;
Payload = data;
Size = data != null ? data.Length : 0;
}
internal Exception GetException()
{
// If it's not done, then there's got to be an error, even if it's
// a Handshake message up, and we only have a Warning message.
return this.Done ? null : SslStreamPal.GetException(Status);
}
#if TRACE_VERBOSE
public override string ToString()
{
return "Status=" + Status.ToString() + ", data size=" + Size;
}
#endif
}
}
| |
// Copyright (c) DotSpatial Team. All rights reserved.
// Licensed under the MIT license. See License.txt file in the project root for full license information.
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Xml.Serialization;
using DotSpatial.Data;
using DotSpatial.Serialization;
namespace DotSpatial.Symbology
{
/// <summary>
/// PictureSymbol.
/// </summary>
public class PictureSymbol : OutlinedSymbol, IPictureSymbol
{
#region Fields
private Image _image;
private string _imageFilename;
private float _opacity;
private Image _original; // Non-transparent version
#endregion
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="PictureSymbol"/> class.
/// </summary>
public PictureSymbol()
{
SymbolType = SymbolType.Picture;
_opacity = 1F;
}
/// <summary>
/// Initializes a new instance of the <see cref="PictureSymbol"/> class from the specified image.
/// </summary>
/// <param name="image">The image to use when creating the symbol.</param>
public PictureSymbol(Image image)
{
SymbolType = SymbolType.Picture;
_opacity = 1F;
Image = image;
}
/// <summary>
/// Initializes a new instance of the <see cref="PictureSymbol"/> class from the specified image.
/// The larger dimension from the image will be adjusted to fit the size,
/// while the smaller dimension will be kept proportional.
/// </summary>
/// <param name="image">The image to use for this symbol.</param>
/// <param name="size">The double size to use for the larger of the two dimensions of the image.</param>
public PictureSymbol(Image image, double size)
{
SymbolType = SymbolType.Picture;
_opacity = 1F;
Image = image;
if (image == null) return;
double scale;
if (image.Width > image.Height)
{
scale = size / image.Width;
}
else
{
scale = size / image.Height;
}
Size = new Size2D(scale * image.Width, scale * image.Height);
}
/// <summary>
/// Initializes a new instance of the <see cref="PictureSymbol"/> class from the specified icon.
/// </summary>
/// <param name="icon">The icon to use when creating this symbol.</param>
public PictureSymbol(Icon icon)
{
SymbolType = SymbolType.Picture;
_opacity = 1F;
_original = icon.ToBitmap();
_image = MakeTransparent(_original, _opacity);
}
/// <summary>
/// Initializes a new instance of the <see cref="PictureSymbol"/> class given an existing imageData object.
/// </summary>
/// <param name="imageData">The imageData object to use.</param>
public PictureSymbol(IImageData imageData)
{
SymbolType = SymbolType.Picture;
_opacity = 1F;
_image = imageData.GetBitmap();
_original = _image;
_imageFilename = imageData.Filename;
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the image to use when the PictureMode is set to Image.
/// </summary>
[XmlIgnore]
public Image Image
{
get
{
return _image;
}
set
{
if (_original != null && _original != value)
{
_original.Dispose();
_original = null;
}
if (_image != null && _image != _original && _image != value)
{
_image.Dispose();
_image = null;
}
_original = value;
_image = MakeTransparent(value, _opacity);
if (_original != null) IsDisposed = false;
}
}
/// <summary>
/// Gets or sets the image in 'base64' string format.
/// This can be used if the image file name is not set.
/// </summary>
[Serialize("ImageBase64String")]
public string ImageBase64String
{
get
{
if (string.IsNullOrEmpty(ImageFilename))
{
return ConvertImageToBase64(Image);
}
return string.Empty;
}
set
{
if (!string.IsNullOrEmpty(value))
{
_original?.Dispose();
_original = null;
_image?.Dispose();
_image = null;
Image = ConvertBase64ToImage(value);
if (_opacity < 1)
{
_image = MakeTransparent(_original, _opacity);
}
}
}
}
/// <summary>
/// Gets or sets the string image fileName to use.
/// </summary>
[Serialize("ImageFilename")]
public string ImageFilename
{
get
{
return _imageFilename;
}
set
{
_imageFilename = value;
_original?.Dispose();
_original = null;
_image?.Dispose();
_image = null;
if (_imageFilename == null || !File.Exists(_imageFilename)) return;
_original = Path.GetExtension(_imageFilename) == ".ico" ? new Icon(_imageFilename).ToBitmap() : Image.FromFile(_imageFilename);
_image = MakeTransparent(_original, _opacity);
}
}
/// <summary>
/// Gets or sets a value indicating whether the symbol is disposed. This is set to true when the dispose method is called.
/// This will be set to false again if the image is set after that.
/// </summary>
public bool IsDisposed { get; set; }
/// <summary>
/// Gets or sets the opacity for this image. Setting this will automatically change the image in memory.
/// </summary>
[Serialize("Opacity")]
public float Opacity
{
get
{
return _opacity;
}
set
{
_opacity = value;
if (_image != null && _image != _original) _image.Dispose();
_image = MakeTransparent(_original, _opacity);
}
}
#endregion
#region Methods
/// <summary>
/// Disposes the current images.
/// </summary>
public void Dispose()
{
OnDisposing();
IsDisposed = true;
}
/// <inheritdoc />
public override void SetColor(Color color)
{
Bitmap bm = new Bitmap(_image.Width, _image.Height);
Graphics g = Graphics.FromImage(bm);
float r = (color.R / 255f) / 2;
float gr = (color.G / 255f) / 2;
float b = (color.B / 255f) / 2;
ColorMatrix cm = new ColorMatrix(new[] { new[] { r, gr, b, 0, 0 }, new[] { r, gr, b, 0, 0 }, new[] { r, gr, b, 0, 0 }, new float[] { 0, 0, 0, 1, 0, 0 }, new float[] { 0, 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 0, 1 } });
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
g.DrawImage(_image, new Rectangle(0, 0, _image.Width, _image.Height), 0, 0, _image.Width, _image.Height, GraphicsUnit.Pixel, ia);
g.Dispose();
_image = bm;
}
/// <summary>
/// This helps the copy process by preparing the internal variables after memberwiseclone has created this.
/// </summary>
/// <param name="copy">The copy.</param>
protected override void OnCopy(Descriptor copy)
{
// Setting the image property has a built in check to dispose the older reference.
// After a MemberwiseClone, however, this older reference is still in use in the original PictureSymbol.
// We must, therefore, set the private variables to null before doing the cloning.
PictureSymbol duplicate = copy as PictureSymbol;
if (duplicate != null)
{
duplicate._image = null;
duplicate._original = null;
}
base.OnCopy(copy);
if (duplicate != null)
{
duplicate._image = _image.Copy();
duplicate._original = _original.Copy();
}
}
/// <summary>
/// Overrideable functions for handling the basic disposal of image classes in this object.
/// </summary>
protected virtual void OnDisposing()
{
_image.Dispose();
_original.Dispose();
}
/// <summary>
/// OnDraw.
/// </summary>
/// <param name="g">Graphics object.</param>
/// <param name="scaleSize">The double scale Size.</param>
protected override void OnDraw(Graphics g, double scaleSize)
{
float dx = (float)(scaleSize * Size.Width / 2);
float dy = (float)(scaleSize * Size.Height / 2);
GraphicsPath gp = new GraphicsPath();
gp.AddRectangle(new RectangleF(-dx, -dy, dx * 2, dy * 2));
if (_image != null)
{
g.DrawImage(_image, new RectangleF(-dx, -dy, dx * 2, dy * 2));
}
OnDrawOutline(g, scaleSize, gp);
gp.Dispose();
}
/// <summary>
/// We can randomize the opacity.
/// </summary>
/// <param name="generator">The generator used for randomization.</param>
protected override void OnRandomize(Random generator)
{
base.OnRandomize(generator);
Opacity = generator.NextFloat();
}
private static Image MakeTransparent(Image image, float opacity)
{
if (image == null) return null;
if (opacity == 1F) return image.Clone() as Image;
Bitmap bmp = new Bitmap(image.Width, image.Height);
Graphics g = Graphics.FromImage(bmp);
float[][] ptsArray =
{
new float[] { 1, 0, 0, 0, 0 }, // R
new float[] { 0, 1, 0, 0, 0 }, // G
new float[] { 0, 0, 1, 0, 0 }, // B
new[] { 0, 0, 0, opacity, 0 }, // A
new float[] { 0, 0, 0, 0, 1 }
};
ColorMatrix clrMatrix = new ColorMatrix(ptsArray);
ImageAttributes att = new ImageAttributes();
att.SetColorMatrix(clrMatrix);
g.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, att);
g.Dispose();
return bmp;
}
private Image ConvertBase64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
private string ConvertImageToBase64(Image image)
{
if (image == null) return string.Empty;
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, ImageFormat.Png);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
#endregion
}
}
| |
/************************************************************************************
Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved.
Licensed under the Oculus SDK License Version 3.4.1 (the "License");
you may not use the Oculus SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
https://developer.oculus.com/licenses/sdk-3.4.1
Unless required by applicable law or agreed to in writing, the Oculus SDK
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;
namespace UnityEngine.EventSystems
{
/// <summary>
/// VR extension of PointerInputModule which supports gaze and controller pointing.
/// </summary>
public class OVRInputModule : PointerInputModule
{
[Tooltip("Object which points with Z axis. E.g. CentreEyeAnchor from OVRCameraRig")]
public Transform rayTransform;
[Tooltip("Gamepad button to act as gaze click")]
public OVRInput.Button joyPadClickButton = OVRInput.Button.One;
[Tooltip("Keyboard button to act as gaze click")]
public KeyCode gazeClickKey = KeyCode.Space;
[Header("Physics")]
[Tooltip("Perform an sphere cast to determine correct depth for gaze pointer")]
public bool performSphereCastForGazepointer;
[Tooltip("Match the gaze pointer normal to geometry normal for physics colliders")]
public bool matchNormalOnPhysicsColliders;
[Header("Gamepad Stick Scroll")]
[Tooltip("Enable scrolling with the right stick on a gamepad")]
public bool useRightStickScroll = true;
[Tooltip("Deadzone for right stick to prevent accidental scrolling")]
public float rightStickDeadZone = 0.15f;
[Header("Touchpad Swipe Scroll")]
[Tooltip("Enable scrolling by swiping the GearVR touchpad")]
public bool useSwipeScroll = true;
[Tooltip("Minimum trackpad movement in pixels to start swiping")]
public float swipeDragThreshold = 2;
[Tooltip("Distance scrolled when swipe scroll occurs")]
public float swipeDragScale = 1f;
/* It's debatable which way left and right are on the Gear VR touchpad since it's facing away from you
* the following bool allows this to be swapped*/
[Tooltip("Invert X axis on touchpad")]
public bool InvertSwipeXAxis = false;
// The raycaster that gets to do pointer interaction (e.g. with a mouse), gaze interaction always works
[NonSerialized]
public OVRRaycaster activeGraphicRaycaster;
[Header("Dragging")]
[Tooltip("Minimum pointer movement in degrees to start dragging")]
public float angleDragThreshold = 1;
// The following region contains code exactly the same as the implementation
// of StandaloneInputModule. It is copied here rather than inheriting from StandaloneInputModule
// because most of StandaloneInputModule is private so it isn't possible to easily derive from.
// Future changes from Unity to StandaloneInputModule will make it possible for this class to
// derive from StandaloneInputModule instead of PointerInput module.
//
// The following functions are not present in the following region since they have modified
// versions in the next region:
// Process
// ProcessMouseEvent
// UseMouse
#region StandaloneInputModule code
private float m_NextAction;
private Vector2 m_LastMousePosition;
private Vector2 m_MousePosition;
protected OVRInputModule()
{}
#if UNITY_EDITOR
protected override void Reset()
{
allowActivationOnMobileDevice = true;
}
#endif
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public enum InputMode
{
Mouse,
Buttons
}
[Obsolete("Mode is no longer needed on input module as it handles both mouse and keyboard simultaneously.", false)]
public InputMode inputMode
{
get { return InputMode.Mouse; }
}
[Header("Standalone Input Module")]
[SerializeField]
private string m_HorizontalAxis = "Horizontal";
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
[SerializeField]
private string m_VerticalAxis = "Vertical";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_SubmitButton = "Submit";
/// <summary>
/// Name of the submit button.
/// </summary>
[SerializeField]
private string m_CancelButton = "Cancel";
[SerializeField]
private float m_InputActionsPerSecond = 10;
[SerializeField]
private bool m_AllowActivationOnMobileDevice;
public bool allowActivationOnMobileDevice
{
get { return m_AllowActivationOnMobileDevice; }
set { m_AllowActivationOnMobileDevice = value; }
}
public float inputActionsPerSecond
{
get { return m_InputActionsPerSecond; }
set { m_InputActionsPerSecond = value; }
}
/// <summary>
/// Name of the horizontal axis for movement (if axis events are used).
/// </summary>
public string horizontalAxis
{
get { return m_HorizontalAxis; }
set { m_HorizontalAxis = value; }
}
/// <summary>
/// Name of the vertical axis for movement (if axis events are used).
/// </summary>
public string verticalAxis
{
get { return m_VerticalAxis; }
set { m_VerticalAxis = value; }
}
public string submitButton
{
get { return m_SubmitButton; }
set { m_SubmitButton = value; }
}
public string cancelButton
{
get { return m_CancelButton; }
set { m_CancelButton = value; }
}
public override void UpdateModule()
{
m_LastMousePosition = m_MousePosition;
m_MousePosition = Input.mousePosition;
}
public override bool IsModuleSupported()
{
// Check for mouse presence instead of whether touch is supported,
// as you can connect mouse to a tablet and in that case we'd want
// to use StandaloneInputModule for non-touch input events.
return m_AllowActivationOnMobileDevice || Input.mousePresent;
}
public override bool ShouldActivateModule()
{
if (!base.ShouldActivateModule())
return false;
var shouldActivate = Input.GetButtonDown(m_SubmitButton);
shouldActivate |= Input.GetButtonDown(m_CancelButton);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_HorizontalAxis), 0.0f);
shouldActivate |= !Mathf.Approximately(Input.GetAxisRaw(m_VerticalAxis), 0.0f);
shouldActivate |= (m_MousePosition - m_LastMousePosition).sqrMagnitude > 0.0f;
shouldActivate |= Input.GetMouseButtonDown(0);
return shouldActivate;
}
public override void ActivateModule()
{
base.ActivateModule();
m_MousePosition = Input.mousePosition;
m_LastMousePosition = Input.mousePosition;
var toSelect = eventSystem.currentSelectedGameObject;
if (toSelect == null)
toSelect = eventSystem.firstSelectedGameObject;
eventSystem.SetSelectedGameObject(toSelect, GetBaseEventData());
}
public override void DeactivateModule()
{
base.DeactivateModule();
ClearSelection();
}
/// <summary>
/// Process submit keys.
/// </summary>
private bool SendSubmitEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
if (Input.GetButtonDown(m_SubmitButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.submitHandler);
if (Input.GetButtonDown(m_CancelButton))
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.cancelHandler);
return data.used;
}
private bool AllowMoveEventProcessing(float time)
{
bool allow = Input.GetButtonDown(m_HorizontalAxis);
allow |= Input.GetButtonDown(m_VerticalAxis);
allow |= (time > m_NextAction);
return allow;
}
private Vector2 GetRawMoveVector()
{
Vector2 move = Vector2.zero;
move.x = Input.GetAxisRaw(m_HorizontalAxis);
move.y = Input.GetAxisRaw(m_VerticalAxis);
if (Input.GetButtonDown(m_HorizontalAxis))
{
if (move.x < 0)
move.x = -1f;
if (move.x > 0)
move.x = 1f;
}
if (Input.GetButtonDown(m_VerticalAxis))
{
if (move.y < 0)
move.y = -1f;
if (move.y > 0)
move.y = 1f;
}
return move;
}
/// <summary>
/// Process keyboard events.
/// </summary>
private bool SendMoveEventToSelectedObject()
{
float time = Time.unscaledTime;
if (!AllowMoveEventProcessing(time))
return false;
Vector2 movement = GetRawMoveVector();
// Debug.Log(m_ProcessingEvent.rawType + " axis:" + m_AllowAxisEvents + " value:" + "(" + x + "," + y + ")");
var axisEventData = GetAxisEventData(movement.x, movement.y, 0.6f);
if (!Mathf.Approximately(axisEventData.moveVector.x, 0f)
|| !Mathf.Approximately(axisEventData.moveVector.y, 0f))
{
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, axisEventData, ExecuteEvents.moveHandler);
}
m_NextAction = time + 1f / m_InputActionsPerSecond;
return axisEventData.used;
}
private bool SendUpdateEventToSelectedObject()
{
if (eventSystem.currentSelectedGameObject == null)
return false;
var data = GetBaseEventData();
ExecuteEvents.Execute(eventSystem.currentSelectedGameObject, data, ExecuteEvents.updateSelectedHandler);
return data.used;
}
/// <summary>
/// Process the current mouse press.
/// </summary>
private void ProcessMousePress(MouseButtonEventData data)
{
var pointerEvent = data.buttonData;
var currentOverGo = pointerEvent.pointerCurrentRaycast.gameObject;
// PointerDown notification
if (data.PressedThisFrame())
{
pointerEvent.eligibleForClick = true;
pointerEvent.delta = Vector2.zero;
pointerEvent.dragging = false;
pointerEvent.useDragThreshold = true;
pointerEvent.pressPosition = pointerEvent.position;
if (pointerEvent.IsVRPointer())
{
pointerEvent.SetSwipeStart(Input.mousePosition);
}
pointerEvent.pointerPressRaycast = pointerEvent.pointerCurrentRaycast;
DeselectIfSelectionChanged(currentOverGo, pointerEvent);
// search for the control that will receive the press
// if we can't find a press handler set the press
// handler to be what would receive a click.
var newPressed = ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.pointerDownHandler);
// didnt find a press handler... search for a click handler
if (newPressed == null)
newPressed = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// Debug.Log("Pressed: " + newPressed);
float time = Time.unscaledTime;
if (newPressed == pointerEvent.lastPress)
{
var diffTime = time - pointerEvent.clickTime;
if (diffTime < 0.3f)
++pointerEvent.clickCount;
else
pointerEvent.clickCount = 1;
pointerEvent.clickTime = time;
}
else
{
pointerEvent.clickCount = 1;
}
pointerEvent.pointerPress = newPressed;
pointerEvent.rawPointerPress = currentOverGo;
pointerEvent.clickTime = time;
// Save the drag handler as well
pointerEvent.pointerDrag = ExecuteEvents.GetEventHandler<IDragHandler>(currentOverGo);
if (pointerEvent.pointerDrag != null)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.initializePotentialDrag);
}
// PointerUp notification
if (data.ReleasedThisFrame())
{
// Debug.Log("Executing pressup on: " + pointer.pointerPress);
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
// Debug.Log("KeyCode: " + pointer.eventData.keyCode);
// see if we mouse up on the same element that we clicked on...
var pointerUpHandler = ExecuteEvents.GetEventHandler<IPointerClickHandler>(currentOverGo);
// PointerClick and Drop events
if (pointerEvent.pointerPress == pointerUpHandler && pointerEvent.eligibleForClick)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerClickHandler);
}
else if (pointerEvent.pointerDrag != null)
{
ExecuteEvents.ExecuteHierarchy(currentOverGo, pointerEvent, ExecuteEvents.dropHandler);
}
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
if (pointerEvent.pointerDrag != null && pointerEvent.dragging)
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.endDragHandler);
pointerEvent.dragging = false;
pointerEvent.pointerDrag = null;
// redo pointer enter / exit to refresh state
// so that if we moused over somethign that ignored it before
// due to having pressed on something else
// it now gets it.
if (currentOverGo != pointerEvent.pointerEnter)
{
HandlePointerExitAndEnter(pointerEvent, null);
HandlePointerExitAndEnter(pointerEvent, currentOverGo);
}
}
}
#endregion
#region Modified StandaloneInputModule methods
/// <summary>
/// Process all mouse events. This is the same as the StandaloneInputModule version except that
/// it takes MouseState as a parameter, allowing it to be used for both Gaze and Mouse
/// pointerss.
/// </summary>
private void ProcessMouseEvent(MouseState mouseData)
{
var pressed = mouseData.AnyPressesThisFrame();
var released = mouseData.AnyReleasesThisFrame();
var leftButtonData = mouseData.GetButtonState(PointerEventData.InputButton.Left).eventData;
if (!UseMouse(pressed, released, leftButtonData.buttonData))
return;
// Process the first mouse button fully
ProcessMousePress(leftButtonData);
ProcessMove(leftButtonData.buttonData);
ProcessDrag(leftButtonData.buttonData);
// Now process right / middle clicks
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Right).eventData.buttonData);
ProcessMousePress(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData);
ProcessDrag(mouseData.GetButtonState(PointerEventData.InputButton.Middle).eventData.buttonData);
if (!Mathf.Approximately(leftButtonData.buttonData.scrollDelta.sqrMagnitude, 0.0f))
{
var scrollHandler = ExecuteEvents.GetEventHandler<IScrollHandler>(leftButtonData.buttonData.pointerCurrentRaycast.gameObject);
ExecuteEvents.ExecuteHierarchy(scrollHandler, leftButtonData.buttonData, ExecuteEvents.scrollHandler);
}
}
/// <summary>
/// Process this InputModule. Same as the StandaloneInputModule version, except that it calls
/// ProcessMouseEvent twice, once for gaze pointers, and once for mouse pointers.
/// </summary>
public override void Process()
{
bool usedEvent = SendUpdateEventToSelectedObject();
if (eventSystem.sendNavigationEvents)
{
if (!usedEvent)
usedEvent |= SendMoveEventToSelectedObject();
if (!usedEvent)
SendSubmitEventToSelectedObject();
}
ProcessMouseEvent(GetGazePointerData());
#if !UNITY_ANDROID
ProcessMouseEvent(GetCanvasPointerData());
#endif
}
/// <summary>
/// Decide if mouse events need to be processed this frame. Same as StandloneInputModule except
/// that the IsPointerMoving method from this class is used, instead of the method on PointerEventData
/// </summary>
private static bool UseMouse(bool pressed, bool released, PointerEventData pointerData)
{
if (pressed || released || IsPointerMoving(pointerData) || pointerData.IsScrolling())
return true;
return false;
}
#endregion
/// <summary>
/// Convenience function for cloning PointerEventData
/// </summary>
/// <param name="from">Copy this value</param>
/// <param name="to">to this object</param>
protected void CopyFromTo(OVRPointerEventData @from, OVRPointerEventData @to)
{
@to.position = @from.position;
@to.delta = @from.delta;
@to.scrollDelta = @from.scrollDelta;
@to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
@to.pointerEnter = @from.pointerEnter;
@to.worldSpaceRay = @from.worldSpaceRay;
}
/// <summary>
/// Convenience function for cloning PointerEventData
/// </summary>
/// <param name="from">Copy this value</param>
/// <param name="to">to this object</param>
protected new void CopyFromTo(PointerEventData @from, PointerEventData @to)
{
@to.position = @from.position;
@to.delta = @from.delta;
@to.scrollDelta = @from.scrollDelta;
@to.pointerCurrentRaycast = @from.pointerCurrentRaycast;
@to.pointerEnter = @from.pointerEnter;
}
// In the following region we extend the PointerEventData system implemented in PointerInputModule
// We define an additional dictionary for ray(e.g. gaze) based pointers. Mouse pointers still use the dictionary
// in PointerInputModule
#region PointerEventData pool
// Pool for OVRRayPointerEventData for ray based pointers
protected Dictionary<int, OVRPointerEventData> m_VRRayPointerData = new Dictionary<int, OVRPointerEventData>();
protected bool GetPointerData(int id, out OVRPointerEventData data, bool create)
{
if (!m_VRRayPointerData.TryGetValue(id, out data) && create)
{
data = new OVRPointerEventData(eventSystem)
{
pointerId = id,
};
m_VRRayPointerData.Add(id, data);
return true;
}
return false;
}
/// <summary>
/// Clear pointer state for both types of pointer
/// </summary>
protected new void ClearSelection()
{
var baseEventData = GetBaseEventData();
foreach (var pointer in m_PointerData.Values)
{
// clear all selection
HandlePointerExitAndEnter(pointer, null);
}
foreach (var pointer in m_VRRayPointerData.Values)
{
// clear all selection
HandlePointerExitAndEnter(pointer, null);
}
m_PointerData.Clear();
eventSystem.SetSelectedGameObject(null, baseEventData);
}
#endregion
/// <summary>
/// For RectTransform, calculate it's normal in world space
/// </summary>
static Vector3 GetRectTransformNormal(RectTransform rectTransform)
{
Vector3[] corners = new Vector3[4];
rectTransform.GetWorldCorners(corners);
Vector3 BottomEdge = corners[3] - corners[0];
Vector3 LeftEdge = corners[1] - corners[0];
rectTransform.GetWorldCorners(corners);
return Vector3.Cross(BottomEdge, LeftEdge).normalized;
}
private readonly MouseState m_MouseState = new MouseState();
// The following 2 functions are equivalent to PointerInputModule.GetMousePointerEventData but are customized to
// get data for ray pointers and canvas mouse pointers.
/// <summary>
/// State for a pointer controlled by a world space ray. E.g. gaze pointer
/// </summary>
/// <returns></returns>
virtual protected MouseState GetGazePointerData()
{
// Get the OVRRayPointerEventData reference
OVRPointerEventData leftData;
GetPointerData(kMouseLeftId, out leftData, true );
leftData.Reset();
//Now set the world space ray. This ray is what the user uses to point at UI elements
leftData.worldSpaceRay = new Ray(rayTransform.position, rayTransform.forward);
leftData.scrollDelta = GetExtraScrollDelta();
//Populate some default values
leftData.button = PointerEventData.InputButton.Left;
leftData.useDragThreshold = true;
// Perform raycast to find intersections with world
eventSystem.RaycastAll(leftData, m_RaycastResultCache);
var raycast = FindFirstRaycast(m_RaycastResultCache);
leftData.pointerCurrentRaycast = raycast;
m_RaycastResultCache.Clear();
OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
// We're only interested in intersections from OVRRaycasters
if (ovrRaycaster)
{
// The Unity UI system expects event data to have a screen position
// so even though this raycast came from a world space ray we must get a screen
// space position for the camera attached to this raycaster for compatability
leftData.position = ovrRaycaster.GetScreenPosition(raycast);
// Find the world position and normal the Graphic the ray intersected
RectTransform graphicRect = raycast.gameObject.GetComponent<RectTransform>();
if (graphicRect != null)
{
// Set are gaze indicator with this world position and normal
Vector3 worldPos = raycast.worldPosition;
Vector3 normal = GetRectTransformNormal(graphicRect);
OVRGazePointer.instance.SetPosition(worldPos, normal);
// Make sure it's being shown
OVRGazePointer.instance.RequestShow();
}
}
// Now process physical raycast intersections
OVRPhysicsRaycaster physicsRaycaster = raycast.module as OVRPhysicsRaycaster;
if (physicsRaycaster)
{
Vector3 position = raycast.worldPosition;
if (performSphereCastForGazepointer)
{
// Here we cast a sphere into the scene rather than a ray. This gives a more accurate depth
// for positioning a circular gaze pointer
List<RaycastResult> results = new List<RaycastResult>();
physicsRaycaster.Spherecast(leftData, results, OVRGazePointer.instance.GetCurrentRadius());
if (results.Count > 0 && results[0].distance < raycast.distance)
{
position = results[0].worldPosition;
}
}
leftData.position = physicsRaycaster.GetScreenPos(raycast.worldPosition);
// Show the cursor while pointing at an interactable object
OVRGazePointer.instance.RequestShow();
if (matchNormalOnPhysicsColliders)
{
OVRGazePointer.instance.SetPosition(position, raycast.worldNormal);
}
else
{
OVRGazePointer.instance.SetPosition(position);
}
}
// Stick default data values in right and middle slots for compatability
// copy the apropriate data into right and middle slots
OVRPointerEventData rightData;
GetPointerData(kMouseRightId, out rightData, true );
CopyFromTo(leftData, rightData);
rightData.button = PointerEventData.InputButton.Right;
OVRPointerEventData middleData;
GetPointerData(kMouseMiddleId, out middleData, true );
CopyFromTo(leftData, middleData);
middleData.button = PointerEventData.InputButton.Middle;
m_MouseState.SetButtonState(PointerEventData.InputButton.Left, GetGazeButtonState(), leftData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Right, PointerEventData.FramePressState.NotChanged, rightData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, PointerEventData.FramePressState.NotChanged, middleData);
return m_MouseState;
}
/// <summary>
/// Get state for pointer which is a pointer moving in world space across the surface of a world space canvas.
/// </summary>
/// <returns></returns>
protected MouseState GetCanvasPointerData()
{
// Get the OVRRayPointerEventData reference
PointerEventData leftData;
GetPointerData(kMouseLeftId, out leftData, true );
leftData.Reset();
// Setup default values here. Set position to zero because we don't actually know the pointer
// positions. Each canvas knows the position of its canvas pointer.
leftData.position = Vector2.zero;
leftData.scrollDelta = Input.mouseScrollDelta;
leftData.button = PointerEventData.InputButton.Left;
if (activeGraphicRaycaster)
{
// Let the active raycaster find intersections on its canvas
activeGraphicRaycaster.RaycastPointer(leftData, m_RaycastResultCache);
var raycast = FindFirstRaycast(m_RaycastResultCache);
leftData.pointerCurrentRaycast = raycast;
m_RaycastResultCache.Clear();
OVRRaycaster ovrRaycaster = raycast.module as OVRRaycaster;
if (ovrRaycaster) // raycast may not actually contain a result
{
// The Unity UI system expects event data to have a screen position
// so even though this raycast came from a world space ray we must get a screen
// space position for the camera attached to this raycaster for compatability
Vector2 position = ovrRaycaster.GetScreenPosition(raycast);
leftData.delta = position - leftData.position;
leftData.position = position;
}
}
// copy the apropriate data into right and middle slots
PointerEventData rightData;
GetPointerData(kMouseRightId, out rightData, true );
CopyFromTo(leftData, rightData);
rightData.button = PointerEventData.InputButton.Right;
PointerEventData middleData;
GetPointerData(kMouseMiddleId, out middleData, true );
CopyFromTo(leftData, middleData);
middleData.button = PointerEventData.InputButton.Middle;
m_MouseState.SetButtonState(PointerEventData.InputButton.Left, StateForMouseButton(0), leftData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Right, StateForMouseButton(1), rightData);
m_MouseState.SetButtonState(PointerEventData.InputButton.Middle, StateForMouseButton(2), middleData);
return m_MouseState;
}
/// <summary>
/// New version of ShouldStartDrag implemented first in PointerInputModule. This version differs in that
/// for ray based pointers it makes a decision about whether a drag should start based on the angular change
/// the pointer has made so far, as seen from the camera. This also works when the world space ray is
/// translated rather than rotated, since the beginning and end of the movement are considered as angle from
/// the same point.
/// </summary>
private bool ShouldStartDrag(PointerEventData pointerEvent)
{
if (!pointerEvent.useDragThreshold)
return true;
if (!pointerEvent.IsVRPointer())
{
// Same as original behaviour for canvas based pointers
return (pointerEvent.pressPosition - pointerEvent.position).sqrMagnitude >= eventSystem.pixelDragThreshold * eventSystem.pixelDragThreshold;
}
else
{
#if UNITY_ANDROID && !UNITY_EDITOR // On android allow swiping to start drag
if (useSwipeScroll && ((Vector3)pointerEvent.GetSwipeStart() - Input.mousePosition).magnitude > swipeDragThreshold)
{
return true;
}
#endif
// When it's not a screen space pointer we have to look at the angle it moved rather than the pixels distance
// For gaze based pointing screen-space distance moved will always be near 0
Vector3 cameraPos = pointerEvent.pressEventCamera.transform.position;
Vector3 pressDir = (pointerEvent.pointerPressRaycast.worldPosition - cameraPos).normalized;
Vector3 currentDir = (pointerEvent.pointerCurrentRaycast.worldPosition - cameraPos).normalized;
return Vector3.Dot(pressDir, currentDir) < Mathf.Cos(Mathf.Deg2Rad * (angleDragThreshold));
}
}
/// <summary>
/// The purpose of this function is to allow us to switch between using the standard IsPointerMoving
/// method for mouse driven pointers, but to always return true when it's a ray based pointer.
/// All real-world ray-based input devices are always moving so for simplicity we just return true
/// for them.
///
/// If PointerEventData.IsPointerMoving was virtual we could just override that in
/// OVRRayPointerEventData.
/// </summary>
/// <param name="pointerEvent"></param>
/// <returns></returns>
static bool IsPointerMoving(PointerEventData pointerEvent)
{
if (pointerEvent.IsVRPointer())
return true;
else
return pointerEvent.IsPointerMoving();
}
protected Vector2 SwipeAdjustedPosition(Vector2 originalPosition, PointerEventData pointerEvent)
{
#if UNITY_ANDROID && !UNITY_EDITOR
// On android we use the touchpad position (accessed through Input.mousePosition) to modify
// the effective cursor position for events related to dragging. This allows the user to
// use the touchpad to drag draggable UI elements
if (useSwipeScroll)
{
Vector2 delta = (Vector2)Input.mousePosition - pointerEvent.GetSwipeStart();
if (InvertSwipeXAxis)
delta.x *= -1;
return originalPosition + delta * swipeDragScale;
}
#endif
// If not Gear VR or swipe scroll isn't enabled just return original position
return originalPosition;
}
/// <summary>
/// Exactly the same as the code from PointerInputModule, except that we call our own
/// IsPointerMoving.
///
/// This would also not be necessary if PointerEventData.IsPointerMoving was virtual
/// </summary>
/// <param name="pointerEvent"></param>
protected override void ProcessDrag(PointerEventData pointerEvent)
{
Vector2 originalPosition = pointerEvent.position;
bool moving = IsPointerMoving(pointerEvent);
if (moving && pointerEvent.pointerDrag != null
&& !pointerEvent.dragging
&& ShouldStartDrag(pointerEvent))
{
if (pointerEvent.IsVRPointer())
{
//adjust the position used based on swiping action. Allowing the user to
//drag items by swiping on the GearVR touchpad
pointerEvent.position = SwipeAdjustedPosition (originalPosition, pointerEvent);
}
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.beginDragHandler);
pointerEvent.dragging = true;
}
// Drag notification
if (pointerEvent.dragging && moving && pointerEvent.pointerDrag != null)
{
if (pointerEvent.IsVRPointer())
{
pointerEvent.position = SwipeAdjustedPosition(originalPosition, pointerEvent);
}
// Before doing drag we should cancel any pointer down state
// And clear selection!
if (pointerEvent.pointerPress != pointerEvent.pointerDrag)
{
ExecuteEvents.Execute(pointerEvent.pointerPress, pointerEvent, ExecuteEvents.pointerUpHandler);
pointerEvent.eligibleForClick = false;
pointerEvent.pointerPress = null;
pointerEvent.rawPointerPress = null;
}
ExecuteEvents.Execute(pointerEvent.pointerDrag, pointerEvent, ExecuteEvents.dragHandler);
}
}
/// <summary>
/// Get state of button corresponding to gaze pointer
/// </summary>
/// <returns></returns>
virtual protected PointerEventData.FramePressState GetGazeButtonState()
{
var pressed = Input.GetKeyDown(gazeClickKey) || OVRInput.GetDown(joyPadClickButton);
var released = Input.GetKeyUp(gazeClickKey) || OVRInput.GetUp(joyPadClickButton);
#if UNITY_ANDROID && !UNITY_EDITOR
// On Gear VR the mouse button events correspond to touch pad events. We only use these as gaze pointer clicks
// on Gear VR because on PC the mouse clicks are used for actual mouse pointer interactions.
pressed |= Input.GetMouseButtonDown(0);
released |= Input.GetMouseButtonUp(0);
#endif
if (pressed && released)
return PointerEventData.FramePressState.PressedAndReleased;
if (pressed)
return PointerEventData.FramePressState.Pressed;
if (released)
return PointerEventData.FramePressState.Released;
return PointerEventData.FramePressState.NotChanged;
}
/// <summary>
/// Get extra scroll delta from gamepad
/// </summary>
protected Vector2 GetExtraScrollDelta()
{
Vector2 scrollDelta = new Vector2();
if (useRightStickScroll)
{
Vector2 s = OVRInput.Get(OVRInput.Axis2D.SecondaryThumbstick);
if (Mathf.Abs(s.x) < rightStickDeadZone) s.x = 0;
if (Mathf.Abs(s.y) < rightStickDeadZone) s.y = 0;
scrollDelta = s;
}
return scrollDelta;
}
};
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// See the LICENSE file in the project root for more information.
//
// System.Drawing.Drawing2D.GraphicsPath.cs
//
// Authors:
//
// Miguel de Icaza (miguel@ximian.com)
// Duncan Mak (duncan@ximian.com)
// Jordi Mas i Hernandez (jordi@ximian.com)
// Ravindra (rkumar@novell.com)
// Sebastien Pouliot <sebastien@ximian.com>
//
// Copyright (C) 2004,2006-2007 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.ComponentModel;
using System.Runtime.InteropServices;
using Gdip = System.Drawing.SafeNativeMethods.Gdip;
namespace System.Drawing.Drawing2D
{
public sealed class GraphicsPath : MarshalByRefObject, ICloneable, IDisposable
{
// 1/4 is the FlatnessDefault as defined in GdiPlusEnums.h
private const float FlatnessDefault = 1.0f / 4.0f;
internal IntPtr _nativePath = IntPtr.Zero;
GraphicsPath(IntPtr ptr)
{
_nativePath = ptr;
}
public GraphicsPath()
{
int status = Gdip.GdipCreatePath(FillMode.Alternate, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(FillMode fillMode)
{
int status = Gdip.GdipCreatePath(fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(Point[] pts, byte[] types)
: this(pts, types, FillMode.Alternate)
{
}
public GraphicsPath(PointF[] pts, byte[] types)
: this(pts, types, FillMode.Alternate)
{
}
public GraphicsPath(Point[] pts, byte[] types, FillMode fillMode)
{
if (pts == null)
throw new ArgumentNullException(nameof(pts));
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
int status = Gdip.GdipCreatePath2I(pts, types, pts.Length, fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public GraphicsPath(PointF[] pts, byte[] types, FillMode fillMode)
{
if (pts == null)
throw new ArgumentNullException(nameof(pts));
if (pts.Length != types.Length)
throw new ArgumentException("Invalid parameter passed. Number of points and types must be same.");
int status = Gdip.GdipCreatePath2(pts, types, pts.Length, fillMode, out _nativePath);
Gdip.CheckStatus(status);
}
public object Clone()
{
IntPtr clone;
int status = Gdip.GdipClonePath(_nativePath, out clone);
Gdip.CheckStatus(status);
return new GraphicsPath(clone);
}
public void Dispose()
{
Dispose(true);
System.GC.SuppressFinalize(this);
}
~GraphicsPath()
{
Dispose(false);
}
void Dispose(bool disposing)
{
int status;
if (_nativePath != IntPtr.Zero)
{
status = Gdip.GdipDeletePath(new HandleRef(this, _nativePath));
Gdip.CheckStatus(status);
_nativePath = IntPtr.Zero;
}
}
public FillMode FillMode
{
get
{
FillMode mode;
int status = Gdip.GdipGetPathFillMode(_nativePath, out mode);
Gdip.CheckStatus(status);
return mode;
}
set
{
if ((value < FillMode.Alternate) || (value > FillMode.Winding))
throw new InvalidEnumArgumentException("FillMode", (int)value, typeof(FillMode));
int status = Gdip.GdipSetPathFillMode(_nativePath, value);
Gdip.CheckStatus(status);
}
}
public PathData PathData
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
PointF[] points = new PointF[count];
byte[] types = new byte[count];
// status would fail if we ask points or types with a 0 count
// anyway that would only mean two unrequired unmanaged calls
if (count > 0)
{
status = Gdip.GdipGetPathPoints(_nativePath, points, count);
Gdip.CheckStatus(status);
status = Gdip.GdipGetPathTypes(_nativePath, types, count);
Gdip.CheckStatus(status);
}
PathData pdata = new PathData();
pdata.Points = points;
pdata.Types = types;
return pdata;
}
}
public PointF[] PathPoints
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathPoints");
PointF[] points = new PointF[count];
status = Gdip.GdipGetPathPoints(_nativePath, points, count);
Gdip.CheckStatus(status);
return points;
}
}
public byte[] PathTypes
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
if (count == 0)
throw new ArgumentException("PathTypes");
byte[] types = new byte[count];
status = Gdip.GdipGetPathTypes(_nativePath, types, count);
Gdip.CheckStatus(status);
return types;
}
}
public int PointCount
{
get
{
int count;
int status = Gdip.GdipGetPointCount(_nativePath, out count);
Gdip.CheckStatus(status);
return count;
}
}
internal IntPtr NativeObject
{
get
{
return _nativePath;
}
set
{
_nativePath = value;
}
}
//
// AddArc
//
public void AddArc(Rectangle rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArcI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(RectangleF rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArc(_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArcI(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddArc(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathArc(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
//
// AddBezier
//
public void AddBezier(Point pt1, Point pt2, Point pt3, Point pt4)
{
int status = Gdip.GdipAddPathBezierI(_nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
Gdip.CheckStatus(status);
}
public void AddBezier(PointF pt1, PointF pt2, PointF pt3, PointF pt4)
{
int status = Gdip.GdipAddPathBezier(_nativePath, pt1.X, pt1.Y,
pt2.X, pt2.Y, pt3.X, pt3.Y, pt4.X, pt4.Y);
Gdip.CheckStatus(status);
}
public void AddBezier(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4)
{
int status = Gdip.GdipAddPathBezierI(_nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
Gdip.CheckStatus(status);
}
public void AddBezier(float x1, float y1, float x2, float y2, float x3, float y3, float x4, float y4)
{
int status = Gdip.GdipAddPathBezier(_nativePath, x1, y1, x2, y2, x3, y3, x4, y4);
Gdip.CheckStatus(status);
}
//
// AddBeziers
//
public void AddBeziers(params Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathBeziersI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddBeziers(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathBeziers(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddEllipse
//
public void AddEllipse(RectangleF rect)
{
int status = Gdip.GdipAddPathEllipse(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddEllipse(float x, float y, float width, float height)
{
int status = Gdip.GdipAddPathEllipse(_nativePath, x, y, width, height);
Gdip.CheckStatus(status);
}
public void AddEllipse(Rectangle rect)
{
int status = Gdip.GdipAddPathEllipseI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddEllipse(int x, int y, int width, int height)
{
int status = Gdip.GdipAddPathEllipseI(_nativePath, x, y, width, height);
Gdip.CheckStatus(status);
}
//
// AddLine
//
public void AddLine(Point pt1, Point pt2)
{
int status = Gdip.GdipAddPathLineI(_nativePath, pt1.X, pt1.Y, pt2.X, pt2.Y);
Gdip.CheckStatus(status);
}
public void AddLine(PointF pt1, PointF pt2)
{
int status = Gdip.GdipAddPathLine(_nativePath, pt1.X, pt1.Y, pt2.X,
pt2.Y);
Gdip.CheckStatus(status);
}
public void AddLine(int x1, int y1, int x2, int y2)
{
int status = Gdip.GdipAddPathLineI(_nativePath, x1, y1, x2, y2);
Gdip.CheckStatus(status);
}
public void AddLine(float x1, float y1, float x2, float y2)
{
int status = Gdip.GdipAddPathLine(_nativePath, x1, y1, x2,
y2);
Gdip.CheckStatus(status);
}
//
// AddLines
//
public void AddLines(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Length == 0)
throw new ArgumentException(nameof(points));
int status = Gdip.GdipAddPathLine2I(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddLines(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
if (points.Length == 0)
throw new ArgumentException(nameof(points));
int status = Gdip.GdipAddPathLine2(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddPie
//
public void AddPie(Rectangle rect, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPie(
_nativePath, rect.X, rect.Y, rect.Width, rect.Height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddPie(int x, int y, int width, int height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPieI(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
public void AddPie(float x, float y, float width, float height, float startAngle, float sweepAngle)
{
int status = Gdip.GdipAddPathPie(_nativePath, x, y, width, height, startAngle, sweepAngle);
Gdip.CheckStatus(status);
}
//
// AddPolygon
//
public void AddPolygon(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathPolygonI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddPolygon(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathPolygon(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
//
// AddRectangle
//
public void AddRectangle(Rectangle rect)
{
int status = Gdip.GdipAddPathRectangleI(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
public void AddRectangle(RectangleF rect)
{
int status = Gdip.GdipAddPathRectangle(_nativePath, rect.X, rect.Y, rect.Width, rect.Height);
Gdip.CheckStatus(status);
}
//
// AddRectangles
//
public void AddRectangles(Rectangle[] rects)
{
if (rects == null)
throw new ArgumentNullException(nameof(rects));
if (rects.Length == 0)
throw new ArgumentException(nameof(rects));
int status = Gdip.GdipAddPathRectanglesI(_nativePath, rects, rects.Length);
Gdip.CheckStatus(status);
}
public void AddRectangles(RectangleF[] rects)
{
if (rects == null)
throw new ArgumentNullException(nameof(rects));
if (rects.Length == 0)
throw new ArgumentException(nameof(rects));
int status = Gdip.GdipAddPathRectangles(_nativePath, rects, rects.Length);
Gdip.CheckStatus(status);
}
//
// AddPath
//
public void AddPath(GraphicsPath addingPath, bool connect)
{
if (addingPath == null)
throw new ArgumentNullException(nameof(addingPath));
int status = Gdip.GdipAddPathPath(_nativePath, addingPath._nativePath, connect);
Gdip.CheckStatus(status);
}
public PointF GetLastPoint()
{
PointF pt;
int status = Gdip.GdipGetPathLastPoint(_nativePath, out pt);
Gdip.CheckStatus(status);
return pt;
}
//
// AddClosedCurve
//
public void AddClosedCurve(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurveI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(Point[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve2I(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddClosedCurve(PointF[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathClosedCurve2(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
//
// AddCurve
//
public void AddCurve(Point[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurveI(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve(_nativePath, points, points.Length);
Gdip.CheckStatus(status);
}
public void AddCurve(Point[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve2I(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve2(_nativePath, points, points.Length, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(Point[] points, int offset, int numberOfSegments, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve3I(_nativePath, points, points.Length,
offset, numberOfSegments, tension);
Gdip.CheckStatus(status);
}
public void AddCurve(PointF[] points, int offset, int numberOfSegments, float tension)
{
if (points == null)
throw new ArgumentNullException(nameof(points));
int status = Gdip.GdipAddPathCurve3(_nativePath, points, points.Length,
offset, numberOfSegments, tension);
Gdip.CheckStatus(status);
}
public void Reset()
{
int status = Gdip.GdipResetPath(_nativePath);
Gdip.CheckStatus(status);
}
public void Reverse()
{
int status = Gdip.GdipReversePath(_nativePath);
Gdip.CheckStatus(status);
}
public void Transform(Matrix matrix)
{
if (matrix == null)
throw new ArgumentNullException(nameof(matrix));
int status = Gdip.GdipTransformPath(_nativePath, matrix.NativeMatrix);
Gdip.CheckStatus(status);
}
public void AddString(string s, FontFamily family, int style, float emSize, Point origin, StringFormat format)
{
Rectangle layout = new Rectangle();
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
}
public void AddString(string s, FontFamily family, int style, float emSize, PointF origin, StringFormat format)
{
RectangleF layout = new RectangleF();
layout.X = origin.X;
layout.Y = origin.Y;
AddString(s, family, style, emSize, layout, format);
}
public void AddString(string s, FontFamily family, int style, float emSize, Rectangle layoutRect, StringFormat format)
{
if (family == null)
throw new ArgumentException(nameof(family));
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
int status = Gdip.GdipAddPathStringI(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
Gdip.CheckStatus(status);
}
public void AddString(string s, FontFamily family, int style, float emSize, RectangleF layoutRect, StringFormat format)
{
if (family == null)
throw new ArgumentException(nameof(family));
IntPtr sformat = (format == null) ? IntPtr.Zero : format.nativeFormat;
// note: the NullReferenceException on s.Length is the expected (MS) exception
int status = Gdip.GdipAddPathString(_nativePath, s, s.Length, family.NativeFamily, style, emSize, ref layoutRect, sformat);
Gdip.CheckStatus(status);
}
public void ClearMarkers()
{
int s = Gdip.GdipClearPathMarkers(_nativePath);
Gdip.CheckStatus(s);
}
public void CloseAllFigures()
{
int s = Gdip.GdipClosePathFigures(_nativePath);
Gdip.CheckStatus(s);
}
public void CloseFigure()
{
int s = Gdip.GdipClosePathFigure(_nativePath);
Gdip.CheckStatus(s);
}
public void Flatten()
{
Flatten(null, FlatnessDefault);
}
public void Flatten(Matrix matrix)
{
Flatten(matrix, FlatnessDefault);
}
public void Flatten(Matrix matrix, float flatness)
{
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int status = Gdip.GdipFlattenPath(_nativePath, m, flatness);
Gdip.CheckStatus(status);
}
public RectangleF GetBounds()
{
return GetBounds(null, null);
}
public RectangleF GetBounds(Matrix matrix)
{
return GetBounds(matrix, null);
}
public RectangleF GetBounds(Matrix matrix, Pen pen)
{
RectangleF retval;
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
IntPtr p = (pen == null) ? IntPtr.Zero : pen.NativePen;
int s = Gdip.GdipGetPathWorldBounds(_nativePath, out retval, m, p);
Gdip.CheckStatus(s);
return retval;
}
public bool IsOutlineVisible(Point point, Pen pen)
{
return IsOutlineVisible(point.X, point.Y, pen, null);
}
public bool IsOutlineVisible(PointF point, Pen pen)
{
return IsOutlineVisible(point.X, point.Y, pen, null);
}
public bool IsOutlineVisible(int x, int y, Pen pen)
{
return IsOutlineVisible(x, y, pen, null);
}
public bool IsOutlineVisible(float x, float y, Pen pen)
{
return IsOutlineVisible(x, y, pen, null);
}
public bool IsOutlineVisible(Point pt, Pen pen, Graphics graphics)
{
return IsOutlineVisible(pt.X, pt.Y, pen, graphics);
}
public bool IsOutlineVisible(PointF pt, Pen pen, Graphics graphics)
{
return IsOutlineVisible(pt.X, pt.Y, pen, graphics);
}
public bool IsOutlineVisible(int x, int y, Pen pen, Graphics graphics)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsOutlineVisiblePathPointI(_nativePath, x, y, pen.NativePen, g, out result);
Gdip.CheckStatus(s);
return result;
}
public bool IsOutlineVisible(float x, float y, Pen pen, Graphics graphics)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
bool result;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsOutlineVisiblePathPoint(_nativePath, x, y, pen.NativePen, g, out result);
Gdip.CheckStatus(s);
return result;
}
public bool IsVisible(Point point)
{
return IsVisible(point.X, point.Y, null);
}
public bool IsVisible(PointF point)
{
return IsVisible(point.X, point.Y, null);
}
public bool IsVisible(int x, int y)
{
return IsVisible(x, y, null);
}
public bool IsVisible(float x, float y)
{
return IsVisible(x, y, null);
}
public bool IsVisible(Point pt, Graphics graphics)
{
return IsVisible(pt.X, pt.Y, graphics);
}
public bool IsVisible(PointF pt, Graphics graphics)
{
return IsVisible(pt.X, pt.Y, graphics);
}
public bool IsVisible(int x, int y, Graphics graphics)
{
bool retval;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsVisiblePathPointI(_nativePath, x, y, g, out retval);
Gdip.CheckStatus(s);
return retval;
}
public bool IsVisible(float x, float y, Graphics graphics)
{
bool retval;
IntPtr g = (graphics == null) ? IntPtr.Zero : graphics.NativeGraphics;
int s = Gdip.GdipIsVisiblePathPoint(_nativePath, x, y, g, out retval);
Gdip.CheckStatus(s);
return retval;
}
public void SetMarkers()
{
int s = Gdip.GdipSetPathMarker(_nativePath);
Gdip.CheckStatus(s);
}
public void StartFigure()
{
int s = Gdip.GdipStartPathFigure(_nativePath);
Gdip.CheckStatus(s);
}
public void Warp(PointF[] destPoints, RectangleF srcRect)
{
Warp(destPoints, srcRect, null, WarpMode.Perspective, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix)
{
Warp(destPoints, srcRect, matrix, WarpMode.Perspective, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode)
{
Warp(destPoints, srcRect, matrix, warpMode, FlatnessDefault);
}
public void Warp(PointF[] destPoints, RectangleF srcRect, Matrix matrix, WarpMode warpMode, float flatness)
{
if (destPoints == null)
throw new ArgumentNullException(nameof(destPoints));
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int s = Gdip.GdipWarpPath(_nativePath, m, destPoints, destPoints.Length,
srcRect.X, srcRect.Y, srcRect.Width, srcRect.Height, warpMode, flatness);
Gdip.CheckStatus(s);
}
public void Widen(Pen pen)
{
Widen(pen, null, FlatnessDefault);
}
public void Widen(Pen pen, Matrix matrix)
{
Widen(pen, matrix, FlatnessDefault);
}
public void Widen(Pen pen, Matrix matrix, float flatness)
{
if (pen == null)
throw new ArgumentNullException(nameof(pen));
if (PointCount == 0)
return;
IntPtr m = (matrix == null) ? IntPtr.Zero : matrix.NativeMatrix;
int s = Gdip.GdipWidenPath(_nativePath, pen.NativePen, m, flatness);
Gdip.CheckStatus(s);
}
}
}
| |
using System;
/// <summary>
/// Convert.ToUInt16(object)
/// </summary>
public class ConvertToUInt1613
{
public static int Main()
{
ConvertToUInt1613 convertToUInt1613 = new ConvertToUInt1613();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt1613");
if (convertToUInt1613.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;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1:Convert to UInt16 from object 1");
try
{
TestClass2 objVal = new TestClass2();
ushort unshortVal = Convert.ToUInt16(objVal);
if (unshortVal != UInt16.MaxValue)
{
TestLibrary.TestFramework.LogError("001", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2:Convert to UInt16 from object 2");
try
{
object objVal = true;
ushort unshortVal = Convert.ToUInt16(objVal);
if (unshortVal != 1)
{
TestLibrary.TestFramework.LogError("003", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3:Convert to UInt16 from object 3");
try
{
object objVal = false;
ushort unshortVal = Convert.ToUInt16(objVal);
if (unshortVal != 0)
{
TestLibrary.TestFramework.LogError("005", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4:Convert to UInt16 from object 4");
try
{
object objVal = null;
ushort unshortVal = Convert.ToUInt16(objVal);
if (unshortVal != 0)
{
TestLibrary.TestFramework.LogError("007", "the ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1:The object does not implement IConvertible");
try
{
TestClass1 objVal = new TestClass1();
ushort unshortVal = Convert.ToUInt16(objVal);
TestLibrary.TestFramework.LogError("N001", "The object does not implement IConvertible but not throw exception");
retVal = false;
}
catch (InvalidCastException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region ForTestClass
public class TestClass1 { }
public class TestClass2 : IConvertible
{
public TypeCode GetTypeCode()
{
throw new Exception("The method or operation is not implemented.");
}
public bool ToBoolean(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public byte ToByte(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public char ToChar(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public DateTime ToDateTime(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public decimal ToDecimal(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public double ToDouble(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public short ToInt16(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public int ToInt32(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public long ToInt64(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public sbyte ToSByte(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public float ToSingle(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public string ToString(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public object ToType(Type conversionType, IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public ushort ToUInt16(IFormatProvider provider)
{
return UInt16.MaxValue;
}
public uint ToUInt32(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
public ulong ToUInt64(IFormatProvider provider)
{
throw new Exception("The method or operation is not implemented.");
}
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Creates and manages instances of <see cref="T:NLog.Logger" /> objects.
/// </summary>
public static class LogManager
{
/// <remarks>
/// Internal for unit tests
/// </remarks>
internal static readonly LogFactory factory = new LogFactory();
private static ICollection<Assembly> _hiddenAssemblies;
private static readonly object lockObject = new object();
/// <summary>
/// Delegate used to set/get the culture in use.
/// </summary>
/// <remarks>This delegate marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Marked obsolete before v4.3.11")]
public delegate CultureInfo GetCultureInfo();
/// <summary>
/// Gets the <see cref="NLog.LogFactory" /> instance used in the <see cref="LogManager"/>.
/// </summary>
/// <remarks>Could be used to pass the to other methods</remarks>
public static LogFactory LogFactory => factory;
/// <summary>
/// Occurs when logging <see cref="Configuration" /> changes.
/// </summary>
public static event EventHandler<LoggingConfigurationChangedEventArgs> ConfigurationChanged
{
add => factory.ConfigurationChanged += value;
remove => factory.ConfigurationChanged -= value;
}
#if !SILVERLIGHT && !__IOS__ && !__ANDROID__ && !NETSTANDARD1_3
/// <summary>
/// Occurs when logging <see cref="Configuration" /> gets reloaded.
/// </summary>
public static event EventHandler<LoggingConfigurationReloadedEventArgs> ConfigurationReloaded
{
add => factory.ConfigurationReloaded += value;
remove => factory.ConfigurationReloaded -= value;
}
#endif
/// <summary>
/// Gets or sets a value indicating whether NLog should throw exceptions.
/// By default exceptions are not thrown under any circumstances.
/// </summary>
public static bool ThrowExceptions
{
get => factory.ThrowExceptions;
set => factory.ThrowExceptions = value;
}
/// <summary>
/// Gets or sets a value indicating whether <see cref="NLogConfigurationException"/> should be thrown.
/// </summary>
/// <value>A value of <c>true</c> if exception should be thrown; otherwise, <c>false</c>.</value>
/// <remarks>
/// This option is for backwards-compatibility.
/// By default exceptions are not thrown under any circumstances.
///
/// </remarks>
public static bool? ThrowConfigExceptions
{
get => factory.ThrowConfigExceptions;
set => factory.ThrowConfigExceptions = value;
}
/// <summary>
/// Gets or sets a value indicating whether Variables should be kept on configuration reload.
/// Default value - false.
/// </summary>
public static bool KeepVariablesOnReload
{
get => factory.KeepVariablesOnReload;
set => factory.KeepVariablesOnReload = value;
}
/// <summary>
/// Gets or sets a value indicating whether to automatically call <see cref="LogManager.Shutdown"/>
/// on AppDomain.Unload or AppDomain.ProcessExit
/// </summary>
public static bool AutoShutdown
{
get => factory.AutoShutdown;
set => factory.AutoShutdown = value;
}
/// <summary>
/// Gets or sets the current logging configuration.
/// <see cref="NLog.LogFactory.Configuration" />
/// </summary>
public static LoggingConfiguration Configuration
{
get => factory.Configuration;
set => factory.Configuration = value;
}
/// <summary>
/// Begins configuration of the LogFactory options using fluent interface
/// </summary>
public static ISetupBuilder Setup()
{
return LogFactory.Setup();
}
/// <summary>
/// Begins configuration of the LogFactory options using fluent interface
/// </summary>
public static LogFactory Setup(Action<ISetupBuilder> setupBuilder)
{
return LogFactory.Setup(setupBuilder);
}
/// <summary>
/// Loads logging configuration from file (Currently only XML configuration files supported)
/// </summary>
/// <param name="configFile">Configuration file to be read</param>
/// <returns>LogFactory instance for fluent interface</returns>
public static LogFactory LoadConfiguration(string configFile)
{
factory.LoadConfiguration(configFile);
return factory;
}
/// <summary>
/// Gets or sets the global log threshold. Log events below this threshold are not logged.
/// </summary>
public static LogLevel GlobalThreshold
{
get => factory.GlobalThreshold;
set => factory.GlobalThreshold = value;
}
/// <summary>
/// Gets or sets the default culture to use.
/// </summary>
/// <remarks>This property was marked as obsolete before NLog 4.3.11 and it may be removed in a future release.</remarks>
[Obsolete("Use Configuration.DefaultCultureInfo property instead. Marked obsolete before v4.3.11")]
public static GetCultureInfo DefaultCultureInfo
{
get { return () => factory.DefaultCultureInfo ?? CultureInfo.CurrentCulture; }
set => throw new NotSupportedException("Setting the DefaultCultureInfo delegate is no longer supported. Use the Configuration.DefaultCultureInfo property to change the default CultureInfo.");
}
/// <summary>
/// Gets the logger with the full name of the current class, so namespace and class name.
/// </summary>
/// <returns>The logger.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger()
{
return factory.GetLogger(StackTraceUsageUtils.GetClassFullName());
}
internal static bool IsHiddenAssembly(Assembly assembly)
{
return _hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly);
}
/// <summary>
/// Adds the given assembly which will be skipped
/// when NLog is trying to find the calling method on stack trace.
/// </summary>
/// <param name="assembly">The assembly to skip.</param>
[MethodImpl(MethodImplOptions.NoInlining)]
public static void AddHiddenAssembly(Assembly assembly)
{
lock (lockObject)
{
if (_hiddenAssemblies != null && _hiddenAssemblies.Contains(assembly))
return;
_hiddenAssemblies = new HashSet<Assembly>(_hiddenAssemblies ?? Enumerable.Empty<Assembly>())
{
assembly
};
}
InternalLogger.Trace("Assembly '{0}' will be hidden in callsite stacktrace", assembly?.FullName);
}
/// <summary>
/// Gets a custom logger with the full name of the current class, so namespace and class name.
/// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>.
/// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType.
/// </summary>
/// <param name="loggerType">The logger class. This class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>.</returns>
/// <remarks>This is a slow-running method.
/// Make sure you're not doing this in a loop.</remarks>
[CLSCompliant(false)]
[MethodImpl(MethodImplOptions.NoInlining)]
public static Logger GetCurrentClassLogger(Type loggerType)
{
return factory.GetLogger(StackTraceUsageUtils.GetClassFullName(), loggerType);
}
/// <summary>
/// Creates a logger that discards all log messages.
/// </summary>
/// <returns>Null logger which discards all log messages.</returns>
[CLSCompliant(false)]
public static Logger CreateNullLogger()
{
return factory.CreateNullLogger();
}
/// <summary>
/// Gets the specified named logger.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <returns>The logger reference. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
[CLSCompliant(false)]
public static Logger GetLogger(string name)
{
return factory.GetLogger(name);
}
/// <summary>
/// Gets the specified named custom logger.
/// Use <paramref name="loggerType"/> to create instance of a custom <see cref="Logger"/>.
/// If you haven't defined your own <see cref="Logger"/> class, then use the overload without the loggerType.
/// </summary>
/// <param name="name">Name of the logger.</param>
/// <param name="loggerType">The logger class. This class must inherit from <see cref="Logger" />.</param>
/// <returns>The logger of type <paramref name="loggerType"/>. Multiple calls to <c>GetLogger</c> with the same argument aren't guaranteed to return the same logger reference.</returns>
/// <remarks>The generic way for this method is <see cref="NLog.LogFactory{loggerType}.GetLogger(string)"/></remarks>
[CLSCompliant(false)]
public static Logger GetLogger(string name, Type loggerType)
{
return factory.GetLogger(name, loggerType);
}
/// <summary>
/// Loops through all loggers previously returned by GetLogger.
/// and recalculates their target and filter list. Useful after modifying the configuration programmatically
/// to ensure that all loggers have been properly configured.
/// </summary>
public static void ReconfigExistingLoggers()
{
factory.ReconfigExistingLoggers();
}
#if !SILVERLIGHT
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets) with the default timeout of 15 seconds.
/// </summary>
public static void Flush()
{
factory.Flush();
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(TimeSpan timeout)
{
factory.Flush(timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(int timeoutMilliseconds)
{
factory.Flush(timeoutMilliseconds);
}
#endif
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
public static void Flush(AsyncContinuation asyncContinuation)
{
factory.Flush(asyncContinuation);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeout">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, TimeSpan timeout)
{
factory.Flush(asyncContinuation, timeout);
}
/// <summary>
/// Flush any pending log messages (in case of asynchronous targets).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <param name="timeoutMilliseconds">Maximum time to allow for the flush. Any messages after that time will be discarded.</param>
public static void Flush(AsyncContinuation asyncContinuation, int timeoutMilliseconds)
{
factory.Flush(asyncContinuation, timeoutMilliseconds);
}
/// <summary>
/// Decreases the log enable counter and if it reaches -1 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
/// <returns>An object that implements IDisposable whose Dispose() method re-enables logging.
/// To be used with C# <c>using ()</c> statement.</returns>
public static IDisposable DisableLogging()
{
return factory.SuspendLogging();
}
/// <summary>
/// Increases the log enable counter and if it reaches 0 the logs are disabled.
/// </summary>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static void EnableLogging()
{
factory.ResumeLogging();
}
/// <summary>
/// Checks if logging is currently enabled.
/// </summary>
/// <returns><see langword="true" /> if logging is currently enabled, <see langword="false"/>
/// otherwise.</returns>
/// <remarks>Logging is enabled if the number of <see cref="EnableLogging"/> calls is greater
/// than or equal to <see cref="DisableLogging"/> calls.</remarks>
public static bool IsLoggingEnabled()
{
return factory.IsLoggingEnabled();
}
/// <summary>
/// Dispose all targets, and shutdown logging.
/// </summary>
public static void Shutdown()
{
factory.Shutdown();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Orleans.Internal;
namespace Orleans.Runtime.MembershipService
{
internal class MembershipSystemTarget : SystemTarget, IMembershipService
{
private readonly MembershipTableManager membershipTableManager;
private readonly ILogger<MembershipSystemTarget> log;
private readonly IInternalGrainFactory grainFactory;
public MembershipSystemTarget(
MembershipTableManager membershipTableManager,
ILocalSiloDetails localSiloDetails,
ILoggerFactory loggerFactory,
ILogger<MembershipSystemTarget> log,
IInternalGrainFactory grainFactory)
: base(Constants.MembershipServiceType, localSiloDetails.SiloAddress, loggerFactory)
{
this.membershipTableManager = membershipTableManager;
this.log = log;
this.grainFactory = grainFactory;
}
public Task Ping(int pingNumber) => Task.CompletedTask;
public async Task SiloStatusChangeNotification(SiloAddress updatedSilo, SiloStatus status)
{
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace("-Received GOSSIP SiloStatusChangeNotification about {Silo} status {Status}. Going to read the table.", updatedSilo, status);
}
await ReadTable();
}
public async Task MembershipChangeNotification(MembershipTableSnapshot snapshot)
{
if (snapshot.Version != MembershipVersion.MinValue)
{
await this.membershipTableManager.RefreshFromSnapshot(snapshot);
}
else
{
if (this.log.IsEnabled(LogLevel.Trace))
this.log.LogTrace("-Received GOSSIP MembershipChangeNotification with MembershipVersion.MinValue. Going to read the table");
await ReadTable();
}
}
/// <summary>
/// Send a ping to a remote silo. This is intended to be called from a <see cref="SiloHealthMonitor"/>
/// in order to initiate the call from the <see cref="MembershipSystemTarget"/>'s context
/// </summary>
/// <param name="remoteSilo">The remote silo to ping.</param>
/// <param name="probeNumber">The probe number, for diagnostic purposes.</param>
/// <returns>The result of pinging the remote silo.</returns>
public Task ProbeRemoteSilo(SiloAddress remoteSilo, int probeNumber) => this.ScheduleTask(() => ProbeInternal(remoteSilo, probeNumber));
/// <summary>
/// Send a ping to a remote silo via an intermediary silo. This is intended to be called from a <see cref="SiloHealthMonitor"/>
/// in order to initiate the call from the <see cref="MembershipSystemTarget"/>'s context
/// </summary>
/// <param name="intermediary">The intermediary which will directly probe the target.</param>
/// <param name="target">The target which will be probed.</param>
/// <param name="probeTimeout">The timeout for the eventual direct probe request.</param>
/// <param name="probeNumber">The probe number, for diagnostic purposes.</param>
/// <returns>The result of pinging the remote silo.</returns>
public Task<IndirectProbeResponse> ProbeRemoteSiloIndirectly(SiloAddress intermediary, SiloAddress target, TimeSpan probeTimeout, int probeNumber)
{
Task<IndirectProbeResponse> ProbeIndirectly()
{
var remoteOracle = this.grainFactory.GetSystemTarget<IMembershipService>(Constants.MembershipServiceType, intermediary);
return remoteOracle.ProbeIndirectly(target, probeTimeout, probeNumber);
}
return this.ScheduleTask(ProbeIndirectly);
}
public async Task<IndirectProbeResponse> ProbeIndirectly(SiloAddress target, TimeSpan probeTimeout, int probeNumber)
{
IndirectProbeResponse result;
var healthScore = this.ActivationServices.GetRequiredService<LocalSiloHealthMonitor>().GetLocalHealthDegradationScore(DateTime.UtcNow);
var probeResponseTimer = ValueStopwatch.StartNew();
try
{
var probeTask = this.ProbeInternal(target, probeNumber);
await probeTask.WithTimeout(probeTimeout, exceptionMessage: $"Requested probe timeout {probeTimeout} exceeded");
result = new IndirectProbeResponse
{
Succeeded = true,
IntermediaryHealthScore = healthScore,
ProbeResponseTime = probeResponseTimer.Elapsed,
};
}
catch (Exception exception)
{
result = new IndirectProbeResponse
{
Succeeded = false,
IntermediaryHealthScore = healthScore,
FailureMessage = $"Encountered exception {LogFormatter.PrintException(exception)}",
ProbeResponseTime = probeResponseTimer.Elapsed,
};
}
return result;
}
public Task GossipToRemoteSilos(
List<SiloAddress> gossipPartners,
MembershipTableSnapshot snapshot,
SiloAddress updatedSilo,
SiloStatus updatedStatus)
{
async Task Gossip()
{
var tasks = new List<Task>(gossipPartners.Count);
foreach (var silo in gossipPartners)
{
tasks.Add(this.GossipToRemoteSilo(silo, snapshot, updatedSilo, updatedStatus));
}
await Task.WhenAll(tasks);
}
return this.ScheduleTask(Gossip);
}
private async Task GossipToRemoteSilo(
SiloAddress silo,
MembershipTableSnapshot snapshot,
SiloAddress updatedSilo,
SiloStatus updatedStatus)
{
if (this.log.IsEnabled(LogLevel.Trace))
{
this.log.LogTrace(
"-Sending status update GOSSIP notification about silo {UpdatedSilo}, status {UpdatedStatus}, to silo {RemoteSilo}",
updatedSilo,
updatedStatus,
silo);
}
try
{
var remoteOracle = this.grainFactory.GetSystemTarget<IMembershipService>(Constants.MembershipServiceType, silo);
try
{
await remoteOracle.MembershipChangeNotification(snapshot);
}
catch (NotImplementedException)
{
// Fallback to "old" gossip
await remoteOracle.SiloStatusChangeNotification(updatedSilo, updatedStatus);
}
}
catch (Exception exception)
{
this.log.LogError(
(int)ErrorCode.MembershipGossipSendFailure,
exception,
"Exception while sending gossip notification to remote silo {Silo}",
silo);
}
}
private async Task ReadTable()
{
try
{
await this.membershipTableManager.Refresh();
}
catch (Exception exception)
{
this.log.LogError(
(int)ErrorCode.MembershipGossipProcessingFailure,
"Error refreshing membership table: {Exception}",
exception);
}
}
private Task ProbeInternal(SiloAddress remoteSilo, int probeNumber)
{
Task task;
try
{
RequestContext.Set(RequestContext.PING_APPLICATION_HEADER, true);
var remoteOracle = this.grainFactory.GetSystemTarget<IMembershipService>(Constants.MembershipServiceType, remoteSilo);
task = remoteOracle.Ping(probeNumber);
// Update stats counter. Only count Pings that were successfuly sent, but not necessarily replied to.
MessagingStatisticsGroup.OnPingSend(remoteSilo);
}
finally
{
RequestContext.Remove(RequestContext.PING_APPLICATION_HEADER);
}
return task;
}
}
}
| |
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 AppTokenMvcApiService.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.WindowsAzure.Storage.Table;
using Orleans.AzureUtils.Utilities;
using Orleans.AzureUtils;
using Orleans.Reminders.AzureStorage;
namespace Orleans.Runtime.ReminderService
{
internal class ReminderTableEntry : TableEntity
{
public string GrainReference { get; set; } // Part of RowKey
public string ReminderName { get; set; } // Part of RowKey
public string ServiceId { get; set; } // Part of PartitionKey
public string DeploymentId { get; set; }
public string StartAt { get; set; }
public string Period { get; set; }
public string GrainRefConsistentHash { get; set; } // Part of PartitionKey
public static string ConstructRowKey(GrainReference grainRef, string reminderName)
{
var key = String.Format("{0}-{1}", grainRef.ToKeyString(), reminderName); //grainRef.ToString(), reminderName);
return AzureStorageUtils.SanitizeTableProperty(key);
}
public static string ConstructPartitionKey(string serviceId, GrainReference grainRef)
{
return ConstructPartitionKey(serviceId, grainRef.GetUniformHashCode());
}
public static string ConstructPartitionKey(string serviceId, uint number)
{
// IMPORTANT NOTE: Other code using this return data is very sensitive to format changes,
// so take great care when making any changes here!!!
// this format of partition key makes sure that the comparisons in FindReminderEntries(begin, end) work correctly
// the idea is that when converting to string, negative numbers start with 0, and positive start with 1. Now,
// when comparisons will be done on strings, this will ensure that positive numbers are always greater than negative
// string grainHash = number < 0 ? string.Format("0{0}", number.ToString("X")) : string.Format("1{0:d16}", number);
var grainHash = String.Format("{0:X8}", number);
return String.Format("{0}_{1}", serviceId, grainHash);
}
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("Reminder [");
sb.Append(" PartitionKey=").Append(PartitionKey);
sb.Append(" RowKey=").Append(RowKey);
sb.Append(" GrainReference=").Append(GrainReference);
sb.Append(" ReminderName=").Append(ReminderName);
sb.Append(" Deployment=").Append(DeploymentId);
sb.Append(" ServiceId=").Append(ServiceId);
sb.Append(" StartAt=").Append(StartAt);
sb.Append(" Period=").Append(Period);
sb.Append(" GrainRefConsistentHash=").Append(GrainRefConsistentHash);
sb.Append("]");
return sb.ToString();
}
}
internal class RemindersTableManager : AzureTableDataManager<ReminderTableEntry>
{
private const string REMINDERS_TABLE_NAME = "OrleansReminders";
public string ServiceId { get; private set; }
public string ClusterId { get; private set; }
private static readonly TimeSpan initTimeout = AzureTableDefaultPolicies.TableCreationTimeout;
public static async Task<RemindersTableManager> GetManager(string serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory)
{
var singleton = new RemindersTableManager(serviceId, clusterId, storageConnectionString, loggerFactory);
try
{
singleton.Logger.Info("Creating RemindersTableManager for service id {0} and clusterId {1}.", serviceId, clusterId);
await singleton.InitTableAsync()
.WithTimeout(initTimeout);
}
catch (TimeoutException te)
{
string errorMsg = $"Unable to create or connect to the Azure table in {initTimeout}";
singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_38, errorMsg, te);
throw new OrleansException(errorMsg, te);
}
catch (Exception ex)
{
string errorMsg = $"Exception trying to create or connect to the Azure table: {ex.Message}";
singleton.Logger.Error((int)AzureReminderErrorCode.AzureTable_39, errorMsg, ex);
throw new OrleansException(errorMsg, ex);
}
return singleton;
}
private RemindersTableManager(string serviceId, string clusterId, string storageConnectionString, ILoggerFactory loggerFactory)
: base(REMINDERS_TABLE_NAME, storageConnectionString, loggerFactory)
{
ClusterId = clusterId;
ServiceId = serviceId;
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(uint begin, uint end)
{
// TODO: Determine whether or not a single query could be used here while avoiding a table scan
string sBegin = ReminderTableEntry.ConstructPartitionKey(ServiceId, begin);
string sEnd = ReminderTableEntry.ConstructPartitionKey(ServiceId, end);
string serviceIdStr = ServiceId;
string filterOnServiceIdStr = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, serviceIdStr + '_'),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual,
serviceIdStr + (char)('_' + 1)));
if (begin < end)
{
string filterBetweenBeginAndEnd = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual,
sEnd));
string query = TableQuery.CombineFilters(filterOnServiceIdStr, TableOperators.And, filterBetweenBeginAndEnd);
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
if (begin == end)
{
var queryResults = await ReadTableEntriesAndEtagsAsync(filterOnServiceIdStr);
return queryResults.ToList();
}
// (begin > end)
string queryOnSBegin = TableQuery.CombineFilters(
filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.GreaterThan, sBegin));
string queryOnSEnd = TableQuery.CombineFilters(
filterOnServiceIdStr, TableOperators.And, TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.LessThanOrEqual, sEnd));
var resultsOnSBeginQuery = ReadTableEntriesAndEtagsAsync(queryOnSBegin);
var resultsOnSEndQuery = ReadTableEntriesAndEtagsAsync(queryOnSEnd);
IEnumerable<Tuple<ReminderTableEntry, string>>[] results = await Task.WhenAll(resultsOnSBeginQuery, resultsOnSEndQuery);
return results[0].Concat(results[1]).ToList();
}
internal async Task<List<Tuple<ReminderTableEntry, string>>> FindReminderEntries(GrainReference grainRef)
{
var partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string filter = TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.GreaterThan, grainRef.ToKeyString() + '-'),
TableOperators.And,
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.RowKey), QueryComparisons.LessThanOrEqual,
grainRef.ToKeyString() + (char)('-' + 1)));
string query =
TableQuery.CombineFilters(
TableQuery.GenerateFilterCondition(nameof(ReminderTableEntry.PartitionKey), QueryComparisons.Equal, partitionKey),
TableOperators.And,
filter);
var queryResults = await ReadTableEntriesAndEtagsAsync(query);
return queryResults.ToList();
}
internal async Task<Tuple<ReminderTableEntry, string>> FindReminderEntry(GrainReference grainRef, string reminderName)
{
string partitionKey = ReminderTableEntry.ConstructPartitionKey(ServiceId, grainRef);
string rowKey = ReminderTableEntry.ConstructRowKey(grainRef, reminderName);
return await ReadSingleTableEntryAsync(partitionKey, rowKey);
}
private Task<List<Tuple<ReminderTableEntry, string>>> FindAllReminderEntries()
{
return FindReminderEntries(0, 0);
}
internal async Task<string> UpsertRow(ReminderTableEntry reminderEntry)
{
try
{
return await UpsertTableEntryAsync(reminderEntry);
}
catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("UpsertRow failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return null; // false;
}
throw;
}
}
internal async Task<bool> DeleteReminderEntryConditionally(ReminderTableEntry reminderEntry, string eTag)
{
try
{
await DeleteTableEntryAsync(reminderEntry, eTag);
return true;
}catch(Exception exc)
{
HttpStatusCode httpStatusCode;
string restStatus;
if (AzureStorageUtils.EvaluateException(exc, out httpStatusCode, out restStatus))
{
if (Logger.IsEnabled(LogLevel.Trace)) Logger.Trace("DeleteReminderEntryConditionally failed with httpStatusCode={0}, restStatus={1}", httpStatusCode, restStatus);
if (AzureStorageUtils.IsContentionError(httpStatusCode)) return false;
}
throw;
}
}
#region Table operations
internal async Task DeleteTableEntries()
{
if (ServiceId.Equals(Guid.Empty) && ClusterId == null)
{
await DeleteTableAsync();
}
else
{
List<Tuple<ReminderTableEntry, string>> entries = await FindAllReminderEntries();
// return manager.DeleteTableEntries(entries); // this doesnt work as entries can be across partitions, which is not allowed
// group by grain hashcode so each query goes to different partition
var tasks = new List<Task>();
var groupedByHash = entries
.Where(tuple => tuple.Item1.ServiceId.Equals(ServiceId))
.Where(tuple => tuple.Item1.DeploymentId.Equals(ClusterId)) // delete only entries that belong to our DeploymentId.
.GroupBy(x => x.Item1.GrainRefConsistentHash).ToDictionary(g => g.Key, g => g.ToList());
foreach (var entriesPerPartition in groupedByHash.Values)
{
foreach (var batch in entriesPerPartition.BatchIEnumerable(AzureTableDefaultPolicies.MAX_BULK_UPDATE_ROWS))
{
tasks.Add(DeleteTableEntriesAsync(batch));
}
}
await Task.WhenAll(tasks);
}
}
#endregion
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace BoardGameWindmill.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// This source file is machine generated. Please do not change the code manually.
using System;
using System.Collections.Generic;
using System.IO.Packaging;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
namespace DocumentFormat.OpenXml.Office.CoverPageProps
{
/// <summary>
/// <para>Defines the CoverPageProperties Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:CoverPageProperties.</para>
/// </summary>
/// <remarks>
/// The following table lists the possible child types:
/// <list type="bullet">
///<item><description>PublishDate <cppr:PublishDate></description></item>
///<item><description>DocumentAbstract <cppr:Abstract></description></item>
///<item><description>CompanyAddress <cppr:CompanyAddress></description></item>
///<item><description>CompanyPhoneNumber <cppr:CompanyPhone></description></item>
///<item><description>CompanyFaxNumber <cppr:CompanyFax></description></item>
///<item><description>CompanyEmailAddress <cppr:CompanyEmail></description></item>
/// </list>
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[ChildElementInfo(typeof(PublishDate))]
[ChildElementInfo(typeof(DocumentAbstract))]
[ChildElementInfo(typeof(CompanyAddress))]
[ChildElementInfo(typeof(CompanyPhoneNumber))]
[ChildElementInfo(typeof(CompanyFaxNumber))]
[ChildElementInfo(typeof(CompanyEmailAddress))]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CoverPageProperties : OpenXmlCompositeElement
{
private const string tagName = "CoverPageProperties";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12692;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CoverPageProperties class.
/// </summary>
public CoverPageProperties():base(){}
/// <summary>
///Initializes a new instance of the CoverPageProperties class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CoverPageProperties(System.Collections.Generic.IEnumerable<OpenXmlElement> childElements)
: base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CoverPageProperties class with the specified child elements.
/// </summary>
/// <param name="childElements">Specifies the child elements.</param>
public CoverPageProperties(params OpenXmlElement[] childElements) : base(childElements)
{
}
/// <summary>
/// Initializes a new instance of the CoverPageProperties class from outer XML.
/// </summary>
/// <param name="outerXml">Specifies the outer XML of the element.</param>
public CoverPageProperties(string outerXml)
: base(outerXml)
{
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
internal override OpenXmlElement ElementFactory(byte namespaceId, string name)
{
if( 36 == namespaceId && "PublishDate" == name)
return new PublishDate();
if( 36 == namespaceId && "Abstract" == name)
return new DocumentAbstract();
if( 36 == namespaceId && "CompanyAddress" == name)
return new CompanyAddress();
if( 36 == namespaceId && "CompanyPhone" == name)
return new CompanyPhoneNumber();
if( 36 == namespaceId && "CompanyFax" == name)
return new CompanyFaxNumber();
if( 36 == namespaceId && "CompanyEmail" == name)
return new CompanyEmailAddress();
return null;
}
private static readonly string[] eleTagNames = { "PublishDate","Abstract","CompanyAddress","CompanyPhone","CompanyFax","CompanyEmail" };
private static readonly byte[] eleNamespaceIds = { 36,36,36,36,36,36 };
internal override string[] ElementTagNames {
get{
return eleTagNames;
}
}
internal override byte[] ElementNamespaceIds {
get{
return eleNamespaceIds;
}
}
internal override OpenXmlCompositeType OpenXmlCompositeType
{
get {return OpenXmlCompositeType.OneSequence;}
}
/// <summary>
/// <para> PublishDate.</para>
/// <para> Represents the following element tag in the schema: cppr:PublishDate </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public PublishDate PublishDate
{
get
{
return GetElement<PublishDate>(0);
}
set
{
SetElement(0, value);
}
}
/// <summary>
/// <para> DocumentAbstract.</para>
/// <para> Represents the following element tag in the schema: cppr:Abstract </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public DocumentAbstract DocumentAbstract
{
get
{
return GetElement<DocumentAbstract>(1);
}
set
{
SetElement(1, value);
}
}
/// <summary>
/// <para> CompanyAddress.</para>
/// <para> Represents the following element tag in the schema: cppr:CompanyAddress </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public CompanyAddress CompanyAddress
{
get
{
return GetElement<CompanyAddress>(2);
}
set
{
SetElement(2, value);
}
}
/// <summary>
/// <para> CompanyPhoneNumber.</para>
/// <para> Represents the following element tag in the schema: cppr:CompanyPhone </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public CompanyPhoneNumber CompanyPhoneNumber
{
get
{
return GetElement<CompanyPhoneNumber>(3);
}
set
{
SetElement(3, value);
}
}
/// <summary>
/// <para> CompanyFaxNumber.</para>
/// <para> Represents the following element tag in the schema: cppr:CompanyFax </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public CompanyFaxNumber CompanyFaxNumber
{
get
{
return GetElement<CompanyFaxNumber>(4);
}
set
{
SetElement(4, value);
}
}
/// <summary>
/// <para> CompanyEmailAddress.</para>
/// <para> Represents the following element tag in the schema: cppr:CompanyEmail </para>
/// </summary>
/// <remark>
/// xmlns:cppr = http://schemas.microsoft.com/office/2006/coverPageProps
/// </remark>
public CompanyEmailAddress CompanyEmailAddress
{
get
{
return GetElement<CompanyEmailAddress>(5);
}
set
{
SetElement(5, value);
}
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CoverPageProperties>(deep);
}
}
/// <summary>
/// <para>Defines the PublishDate Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:PublishDate.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class PublishDate : OpenXmlLeafTextElement
{
private const string tagName = "PublishDate";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12693;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the PublishDate class.
/// </summary>
public PublishDate():base(){}
/// <summary>
/// Initializes a new instance of the PublishDate class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public PublishDate(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<PublishDate>(deep);
}
}
/// <summary>
/// <para>Defines the DocumentAbstract Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:Abstract.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class DocumentAbstract : OpenXmlLeafTextElement
{
private const string tagName = "Abstract";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12694;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the DocumentAbstract class.
/// </summary>
public DocumentAbstract():base(){}
/// <summary>
/// Initializes a new instance of the DocumentAbstract class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public DocumentAbstract(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<DocumentAbstract>(deep);
}
}
/// <summary>
/// <para>Defines the CompanyAddress Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:CompanyAddress.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CompanyAddress : OpenXmlLeafTextElement
{
private const string tagName = "CompanyAddress";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12695;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CompanyAddress class.
/// </summary>
public CompanyAddress():base(){}
/// <summary>
/// Initializes a new instance of the CompanyAddress class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public CompanyAddress(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CompanyAddress>(deep);
}
}
/// <summary>
/// <para>Defines the CompanyPhoneNumber Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:CompanyPhone.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CompanyPhoneNumber : OpenXmlLeafTextElement
{
private const string tagName = "CompanyPhone";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12696;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CompanyPhoneNumber class.
/// </summary>
public CompanyPhoneNumber():base(){}
/// <summary>
/// Initializes a new instance of the CompanyPhoneNumber class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public CompanyPhoneNumber(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CompanyPhoneNumber>(deep);
}
}
/// <summary>
/// <para>Defines the CompanyFaxNumber Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:CompanyFax.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CompanyFaxNumber : OpenXmlLeafTextElement
{
private const string tagName = "CompanyFax";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12697;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CompanyFaxNumber class.
/// </summary>
public CompanyFaxNumber():base(){}
/// <summary>
/// Initializes a new instance of the CompanyFaxNumber class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public CompanyFaxNumber(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CompanyFaxNumber>(deep);
}
}
/// <summary>
/// <para>Defines the CompanyEmailAddress Class.</para>
/// <para> When the object is serialized out as xml, its qualified name is cppr:CompanyEmail.</para>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix")]
[System.CodeDom.Compiler.GeneratedCode("DomGen", "2.0")]
public partial class CompanyEmailAddress : OpenXmlLeafTextElement
{
private const string tagName = "CompanyEmail";
/// <summary>
/// Gets the local name of the element.
/// </summary>
public override string LocalName
{
get { return tagName; }
}
private const byte tagNsId = 36;
internal override byte NamespaceId
{
get { return tagNsId; }
}
internal const int ElementTypeIdConst = 12698;
/// <summary>
/// Gets the type ID of the element.
/// </summary>
internal override int ElementTypeId
{
get { return ElementTypeIdConst; }
}
/// <summary>
/// Whether this element is available in a specific version of Office Application.
/// </summary>
/// <param name="version">The Office file format version.</param>
/// <returns>Returns true if the element is defined in the specified version.</returns>
internal override bool IsInVersion(FileFormatVersions version)
{
if((7 & (int)version) > 0)
{
return true;
}
return false;
}
/// <summary>
/// Initializes a new instance of the CompanyEmailAddress class.
/// </summary>
public CompanyEmailAddress():base(){}
/// <summary>
/// Initializes a new instance of the CompanyEmailAddress class with the specified text content.
/// </summary>
/// <param name="text">Specifies the text content of the element.</param>
public CompanyEmailAddress(string text):base(text)
{
}
internal override OpenXmlSimpleType InnerTextToValue(string text)
{
return new StringValue(){ InnerText = text };
}
/// <summary>
/// Creates a duplicate of this node.
/// </summary>
/// <param name="deep">True to recursively clone the subtree under the specified node; false to clone only the node itself. </param>
/// <returns>Returns the cloned node. </returns>
public override OpenXmlElement CloneNode(bool deep)
{
return CloneImp<CompanyEmailAddress>(deep);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="GZipStream.cs" company="XamlNinja">
// 2011 Richard Griffin and Ollie Riches
// </copyright>
// <summary>
// http://www.sharpgis.net/post/2011/08/28/GZIP-Compressed-Web-Requests-in-WP7-Take-2.aspx
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace WP7Contrib.Communications.Compression
{
using System;
using System.IO;
using System.Text;
internal class GZipStream : Stream
{
internal static DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
internal static Encoding Iso8859dash1 = Encoding.GetEncoding("iso-8859-1");
public DateTime? LastModified;
internal ZlibBaseStream BaseStream;
bool disposed;
bool firstReadDone;
string fileName;
string comment;
#region Properties
public int Crc32 { get; private set; }
public override bool CanSeek
{
get { return false; }
}
public override bool CanRead
{
get
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
else
return this.BaseStream._stream.CanRead;
}
}
public override bool CanWrite
{
get
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
else
return this.BaseStream._stream.CanWrite;
}
}
public int BufferSize
{
get
{
return this.BaseStream._bufferSize;
}
set
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
if (this.BaseStream._workingBuffer != null)
throw new ZlibException("The working buffer is already set.");
if (value < 128)
throw new ZlibException(string.Format("Don't be silly. {0} bytes?? Use a bigger buffer.", (object)value));
this.BaseStream._bufferSize = value;
}
}
public virtual long TotalIn
{
get { return this.BaseStream._z.TotalBytesIn; }
}
public virtual long TotalOut
{
get { return this.BaseStream._z.TotalBytesOut; }
}
public override long Length
{
get { return this.BaseStream.Length; }
}
public override long Position
{
get
{
if (this.BaseStream._streamMode == ZlibBaseStream.StreamMode.Reader)
return this.BaseStream._z.TotalBytesIn + (long)this.BaseStream._gzipHeaderByteCount;
else
return 0L;
}
set
{
throw new NotImplementedException();
}
}
public string Comment
{
get
{
return this.comment;
}
set
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
this.comment = value;
}
}
public string FileName
{
get
{
return this.fileName;
}
set
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
this.fileName = value;
if (this.fileName == null)
return;
if (this.fileName.IndexOf("/") != -1)
this.fileName = this.fileName.Replace("/", "\\");
if (this.fileName.EndsWith("\\"))
throw new Exception("Illegal filename");
if (this.fileName.IndexOf("\\") == -1)
return;
this.fileName = Path.GetFileName(this.fileName);
}
}
public virtual FlushType FlushMode
{
get
{
return this.BaseStream._flushMode;
}
set
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
this.BaseStream._flushMode = value;
}
}
#endregion Properties
#region Constructors
static GZipStream()
{
}
public GZipStream(Stream stream)
{
this.BaseStream = new ZlibBaseStream(stream, ZlibStreamFlavor.GZIP, false);
}
#endregion Constructors
#region Cleaning up
protected override void Dispose(bool disposing)
{
try
{
if (this.disposed)
return;
if (disposing && this.BaseStream != null)
{
this.BaseStream.Close();
this.Crc32 = this.BaseStream.Crc32;
}
this.disposed = true;
}
finally
{
base.Dispose(disposing);
}
}
#endregion Cleaning up
public override void Flush()
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
this.BaseStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
if (this.disposed)
throw new ObjectDisposedException("GZipStream");
int num = this.BaseStream.Read(buffer, offset, count);
if (!this.firstReadDone)
{
this.firstReadDone = true;
this.FileName = this.BaseStream._GzipFileName;
this.Comment = this.BaseStream._GzipComment;
}
return num;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotImplementedException();
}
public override void SetLength(long value)
{
throw new NotImplementedException();
}
int EmitHeader()
{
byte[] numArray1 = this.Comment == null ? (byte[])null : GZipStream.Iso8859dash1.GetBytes(this.Comment);
byte[] numArray2 = this.FileName == null ? (byte[])null : GZipStream.Iso8859dash1.GetBytes(this.FileName);
int num1 = this.Comment == null ? 0 : numArray1.Length + 1;
int num2 = this.FileName == null ? 0 : numArray2.Length + 1;
byte[] buffer = new byte[10 + num1 + num2];
int num3 = 0;
byte[] numArray3 = buffer;
int index1 = num3;
int num4 = 1;
int num5 = index1 + num4;
int num6 = 31;
numArray3[index1] = (byte)num6;
byte[] numArray4 = buffer;
int index2 = num5;
int num7 = 1;
int num8 = index2 + num7;
int num9 = 139;
numArray4[index2] = (byte)num9;
byte[] numArray5 = buffer;
int index3 = num8;
int num10 = 1;
int num11 = index3 + num10;
int num12 = 8;
numArray5[index3] = (byte)num12;
byte num13 = (byte)0;
if (this.Comment != null)
num13 ^= (byte)16;
if (this.FileName != null)
num13 ^= (byte)8;
byte[] numArray6 = buffer;
int index4 = num11;
int num14 = 1;
int destinationIndex1 = index4 + num14;
int num15 = (int)num13;
numArray6[index4] = (byte)num15;
if (!this.LastModified.HasValue)
this.LastModified = new DateTime?(DateTime.Now);
Array.Copy((Array)BitConverter.GetBytes((int)(this.LastModified.Value - GZipStream.UnixEpoch).TotalSeconds), 0, (Array)buffer, destinationIndex1, 4);
int num16 = destinationIndex1 + 4;
byte[] numArray7 = buffer;
int index5 = num16;
int num17 = 1;
int num18 = index5 + num17;
int num19 = 0;
numArray7[index5] = (byte)num19;
byte[] numArray8 = buffer;
int index6 = num18;
int num20 = 1;
int destinationIndex2 = index6 + num20;
int num21 = (int)byte.MaxValue;
numArray8[index6] = (byte)num21;
if (num2 != 0)
{
Array.Copy((Array)numArray2, 0, (Array)buffer, destinationIndex2, num2 - 1);
int num22 = destinationIndex2 + (num2 - 1);
byte[] numArray9 = buffer;
int index7 = num22;
int num23 = 1;
destinationIndex2 = index7 + num23;
int num24 = 0;
numArray9[index7] = (byte)num24;
}
if (num1 != 0)
{
Array.Copy((Array)numArray1, 0, (Array)buffer, destinationIndex2, num1 - 1);
int num22 = destinationIndex2 + (num1 - 1);
byte[] numArray9 = buffer;
int index7 = num22;
int num23 = 1;
int num24 = index7 + num23;
int num25 = 0;
numArray9[index7] = (byte)num25;
}
this.BaseStream._stream.Write(buffer, 0, buffer.Length);
return buffer.Length;
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotImplementedException();
}
}
}
| |
//-----------------------------------------------------------------------
// Copyright 2014 Tobii Technology AB. All rights reserved.
//-----------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using Tobii.EyeX.Client;
using Tobii.EyeX.Framework;
using UnityEngine;
using Rect = UnityEngine.Rect;
using Environment = Tobii.EyeX.Client.Environment;
/// <summary>
/// Provides the main point of contact with the EyeX Engine.
/// Hosts an EyeX context and responds to engine queries using a repository of interactors.
/// </summary>
public class EyeXHost : MonoBehaviour
{
/// <summary>
/// If set to true, it will automatically initialize the EyeX Engine on Start().
/// </summary>
public bool initializeOnStart = true;
/// <summary>
/// Special interactor ID indicating that an interactor doesn't have a parent.
/// </summary>
public const string NoParent = Literals.RootId;
private static EyeXHost _instance;
private readonly object _lock = new object();
private readonly Dictionary<string, IEyeXGlobalInteractor> _globalInteractors = new Dictionary<string, IEyeXGlobalInteractor>();
private readonly Dictionary<string, EyeXInteractor> _interactors = new Dictionary<string, EyeXInteractor>();
private readonly EyeXActivationHub _activationHub = new EyeXActivationHub();
private Environment _environment;
private Context _context;
private Vector2 _gameWindowPosition = new Vector2(float.NaN, float.NaN);
private float _horizontalScreenScale = 1.0f;
private float _verticalScreenScale = 1.0f;
private bool _isConnected;
private bool _isPaused;
private bool _isFocused;
private bool _runInBackground;
private ScreenHelpers _screenHelpers;
// Engine state accessors
private EyeXEngineStateAccessor<Tobii.EyeX.Client.Rect> _screenBoundsStateAccessor;
private EyeXEngineStateAccessor<Size2> _displaySizeStateAccessor;
private EyeXEngineStateAccessor<EyeTrackingDeviceStatus> _eyeTrackingDeviceStatusStateAccessor;
private EyeXEngineStateAccessor<UserPresence> _userPresenceStateAccessor;
/// <summary>
/// Gets the engine state: Screen bounds in pixels.
/// </summary>
public EyeXEngineStateValue<Tobii.EyeX.Client.Rect> ScreenBounds
{
get { return _screenBoundsStateAccessor.GetCurrentValue(_context); }
}
/// <summary>
/// Gets the engine state: Display size, width and height, in millimeters.
/// </summary>
public EyeXEngineStateValue<Size2> DisplaySize
{
get { return _displaySizeStateAccessor.GetCurrentValue(_context); }
}
/// <summary>
/// Gets the engine state: Eye tracking status.
/// </summary>
public EyeXEngineStateValue<EyeTrackingDeviceStatus> EyeTrackingDeviceStatus
{
get { return _eyeTrackingDeviceStatusStateAccessor.GetCurrentValue(_context); }
}
/// <summary>
/// Gets the engine state: User presence.
/// </summary>
public EyeXEngineStateValue<UserPresence> UserPresence
{
get { return _userPresenceStateAccessor.GetCurrentValue(_context); }
}
/// <summary>
/// Gets the shared ActivationHub used for synchronizing activation events across interactors and frames.
/// Use this object when creating EyeXActivatable behaviors.
/// </summary>
public IEyeXActivationHub ActivationHub
{
get { return _activationHub; }
}
/// <summary>
/// Returns a value indicating whether The EyeX Engine has been initialized
/// </summary>
public bool IsInitialized
{
get { return _context != null; }
}
private bool IsRunning
{
get
{
return !_isPaused &&
(_isFocused || _runInBackground);
}
}
/// <summary>
/// Gets the singleton EyeXHost instance.
/// Users of this class should store a reference to the singleton instance in their Awake() method, or similar,
/// to ensure that the EyeX host instance stays alive at least as long as the user object. Otherwise the
/// EyeXHost might be garbage collected and replaced with a new, uninitialized instance during application
/// shutdown, and that would lead to unexpected behavior.
/// </summary>
/// <returns>The instance.</returns>
public static EyeXHost GetInstance()
{
if (_instance == null)
{
// create a game object with a new instance of this class attached as a component.
// (there's no need to keep a reference to the game object, because game objects are not garbage collected.)
var container = new GameObject();
container.name = "EyeXHostContainer";
DontDestroyOnLoad(container);
_instance = (EyeXHost)container.AddComponent(typeof(EyeXHost));
}
return _instance;
}
/// <summary>
/// Initialize helper classes and state accessors on Awake
/// </summary>
void Awake()
{
_runInBackground = Application.runInBackground;
_screenHelpers = new ScreenHelpers();
_screenBoundsStateAccessor = new EyeXEngineStateAccessor<Tobii.EyeX.Client.Rect>(StatePaths.ScreenBounds, OnEngineStateChanged);
_displaySizeStateAccessor = new EyeXEngineStateAccessor<Size2>(StatePaths.DisplaySize, OnEngineStateChanged);
_eyeTrackingDeviceStatusStateAccessor = new EyeXEngineStateAccessor<EyeTrackingDeviceStatus>(StatePaths.EyeTrackingState, OnEngineStateChanged);
_userPresenceStateAccessor = new EyeXEngineStateAccessor<UserPresence>(StatePaths.UserPresence, OnEngineStateChanged);
}
/// <summary>
/// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time.
/// </summary>
public void Start()
{
if (initializeOnStart)
{
InitializeEyeX();
}
}
/// <summary>
/// Update is called every frame, if the MonoBehaviour is enabled.
/// </summary>
public void Update()
{
// update the game window position, in case the game window has been moved or resized.
_gameWindowPosition = _screenHelpers.GetGameWindowPosition();
_horizontalScreenScale = _screenHelpers.GetHorizontalScreenScale(ScreenBounds);
_verticalScreenScale = _screenHelpers.GetVerticalScreenScale(ScreenBounds);
StartCoroutine(DoEndOfFrameCleanup());
}
private IEnumerator DoEndOfFrameCleanup()
{
yield return new WaitForEndOfFrame();
_activationHub.EndFrame();
}
/// <summary>
/// Sent to all game objects when the player gets or loses focus.
/// </summary>
/// <param name="focusStatus">Gets a value indicating whether the player is focused.</param>
public void OnApplicationFocus(bool focusStatus)
{
var wasRunning = IsRunning;
_isFocused = focusStatus;
// make sure that data streams are disabled while the game is paused.
if (wasRunning != IsRunning && _isConnected)
{
CommitAllGlobalInteractors();
}
}
/// <summary>
/// Sent to all game objects when the player pauses.
/// </summary>
/// <param name="pauseStatus">Gets a value indicating whether the player is paused.</param>
public void OnApplicationPause(bool pauseStatus)
{
var wasRunning = IsRunning;
_isPaused = pauseStatus;
// make sure that data streams are disabled while the game is paused.
if (wasRunning != IsRunning && _isConnected)
{
CommitAllGlobalInteractors();
}
}
/// <summary>
/// Sent to all game objects before the application is quit.
/// </summary>
public void OnApplicationQuit()
{
ShutdownEyeX();
}
/// <summary>
/// Registers an interactor with the repository.
/// </summary>
/// <param name="interactor">The interactor.</param>
public void RegisterInteractor(EyeXInteractor interactor)
{
lock (_lock)
{
_interactors[interactor.Id] = interactor;
}
}
/// <summary>
/// Gets an interactor from the repository.
/// </summary>
/// <param name="interactorId">ID of the interactor.</param>
/// <returns>Interactor, or null if not found.</returns>
public EyeXInteractor GetInteractor(string interactorId)
{
lock (_lock)
{
EyeXInteractor interactor = null;
_interactors.TryGetValue(interactorId, out interactor);
return interactor;
}
}
/// <summary>
/// Removes an interactor from the repository.
/// </summary>
/// <param name="interactorId">ID of the interactor.</param>
public void UnregisterInteractor(string interactorId)
{
lock (_lock)
{
_interactors.Remove(interactorId);
}
}
/// <summary>
/// Gets a provider of gaze point data.
/// See <see cref="IEyeXDataProvider{T}"/>.
/// </summary>
/// <param name="mode">Specifies the kind of data processing to be applied by the EyeX Engine.</param>
/// <returns>The data provider.</returns>
public IEyeXDataProvider<EyeXGazePoint> GetGazePointDataProvider(GazePointDataMode mode)
{
var dataStream = new EyeXGazePointDataStream(mode);
return GetDataProviderForDataStream<EyeXGazePoint>(dataStream);
}
/// <summary>
/// Gets a provider of fixation data.
/// See <see cref="IEyeXDataProvider{T}"/>.
/// </summary>
/// <param name="mode">Specifies the kind of data processing to be applied by the EyeX Engine.</param>
/// <returns>The data provider.</returns>
public IEyeXDataProvider<EyeXFixationPoint> GetFixationDataProvider(FixationDataMode mode)
{
var dataStream = new EyeXFixationDataStream(mode);
return GetDataProviderForDataStream<EyeXFixationPoint>(dataStream);
}
/// <summary>
/// Gets a provider of eye position data.
/// See <see cref="IEyeXDataProvider{T}"/>.
/// </summary>
/// <returns>The data provider.</returns>
public IEyeXDataProvider<EyeXEyePosition> GetEyePositionDataProvider()
{
var dataStream = new EyeXEyePositionDataStream();
return GetDataProviderForDataStream<EyeXEyePosition>(dataStream);
}
/// <summary>
/// Gets a data provider for a given data stream: preferably an existing one
/// in the _globalInteractors collection, or, failing that, the one passed
/// in as a parameter.
/// </summary>
/// <typeparam name="T">Type of the provided data value object.</typeparam>
/// <param name="dataStream">Data stream to be added.</param>
/// <returns>A data provider.</returns>
private IEyeXDataProvider<T> GetDataProviderForDataStream<T>(EyeXDataStreamBase<T> dataStream)
{
lock (_lock)
{
IEyeXGlobalInteractor existing;
if (_globalInteractors.TryGetValue(dataStream.Id, out existing))
{
return (IEyeXDataProvider<T>)existing;
}
_globalInteractors.Add(dataStream.Id, dataStream);
dataStream.Updated += OnGlobalInteractorUpdated;
return dataStream;
}
}
/// <summary>
/// Gets an interactor from the repository.
/// </summary>
/// <param name="interactorId">ID of the interactor.</param>
/// <returns>Interactor, or null if not found.</returns>
private IEyeXGlobalInteractor GetGlobalInteractor(string interactorId)
{
lock (_lock)
{
IEyeXGlobalInteractor interactor = null;
_globalInteractors.TryGetValue(interactorId, out interactor);
return interactor;
}
}
/// <summary>
/// Handles a state changed notification from the EyeX Engine.
/// </summary>
/// <param name="asyncData">Notification data packet.</param>
protected virtual void OnEngineStateChanged(AsyncData asyncData)
{
ResultCode resultCode;
if (!asyncData.TryGetResultCode(out resultCode) ||
resultCode != ResultCode.Ok)
{
return;
}
var stateBag = asyncData.GetDataAs<StateBag>();
if (stateBag == null)
{
return;
}
_screenBoundsStateAccessor.HandleStateChanged(stateBag, this);
_displaySizeStateAccessor.HandleStateChanged(stateBag, this);
_eyeTrackingDeviceStatusStateAccessor.HandleStateChanged(stateBag, this);
_userPresenceStateAccessor.HandleStateChanged(stateBag, this);
asyncData.Dispose();
}
/// <summary>
/// Initializes the EyeX engine.
/// </summary>
public void InitializeEyeX()
{
if (IsInitialized) return;
try
{
Tobii.EyeX.Client.Interop.EyeX.EnableMonoCallbacks("mono");
_environment = Environment.Initialize();
}
catch (InteractionApiException ex)
{
Debug.LogError("EyeX initialization failed: " + ex.Message);
}
catch (DllNotFoundException)
{
#if UNITY_EDITOR
Debug.LogError("EyeX initialization failed because the client access library 'Tobii.EyeX.Client.dll' could not be loaded. " +
"Please make sure that it is present in the Unity project directory. " +
"You can find it in the SDK package, in the lib/x86 directory. (Currently only Windows is supported.)");
#else
Debug.LogError("EyeX initialization failed because the client access library 'Tobii.EyeX.Client.dll' could not be loaded. " +
"Please make sure that it is present in the root directory of the game/application.");
#endif
return;
}
try
{
_context = new Context(false);
_context.RegisterQueryHandlerForCurrentProcess(HandleQuery);
_context.RegisterEventHandler(HandleEvent);
_context.ConnectionStateChanged += OnConnectionStateChanged;
_context.EnableConnection();
print("EyeX is running.");
}
catch (InteractionApiException ex)
{
Debug.LogError("EyeX context initialization failed: " + ex.Message);
}
}
/// <summary>
/// Shuts down the eyeX engine.
/// </summary>
public void ShutdownEyeX()
{
if (!IsInitialized) return;
print("EyeX is shutting down.");
if (_context != null)
{
// The context must be shut down before disposing.
try
{
_context.Shutdown(1000, false);
}
catch (InteractionApiException ex)
{
Debug.LogError("EyeX context shutdown failed: " + ex.Message);
}
_context.Dispose();
_context = null;
}
if (_environment != null)
{
_environment.Dispose();
_environment = null;
}
}
private void OnConnectionStateChanged(object sender, ConnectionStateChangedEventArgs e)
{
if (e.State == ConnectionState.Connected)
{
_isConnected = true;
// commit the snapshot with the global interactor as soon as the connection to the engine is established.
// (it cannot be done earlier because committing means "send to the engine".)
CommitAllGlobalInteractors();
_screenBoundsStateAccessor.OnConnected(_context);
_displaySizeStateAccessor.OnConnected(_context);
_eyeTrackingDeviceStatusStateAccessor.OnConnected(_context);
_userPresenceStateAccessor.OnConnected(_context);
}
else
{
_isConnected = false;
_screenBoundsStateAccessor.OnDisconnected();
_displaySizeStateAccessor.OnDisconnected();
_eyeTrackingDeviceStatusStateAccessor.OnDisconnected();
_userPresenceStateAccessor.OnDisconnected();
}
}
private void HandleQuery(Query query)
{
// NOTE: this method is called from a worker thread, so it must not access any game objects.
try
{
// The mechanism that we use for getting the window ID assumes that the game window is on top
// when the scripts start running. It usually does the right thing, but not always.
// So adjust if necessary.
var queryWindowIdEnum = query.WindowIds.GetEnumerator();
if (queryWindowIdEnum.MoveNext())
{
if (queryWindowIdEnum.Current != _screenHelpers.GameWindowId)
{
//print(string.Format("Window ID mismatch: queried for {0}, expected {1}. Adjusting.", queryWindowIdEnum.Current, ScreenHelpers.Instance.GameWindowId));
_screenHelpers.GameWindowId = queryWindowIdEnum.Current;
_gameWindowPosition = new Vector2(float.NaN, float.NaN);
}
}
if (float.IsNaN(_gameWindowPosition.x))
{
// We don't have a valid game window position, so we cannot respond to any queries at this time.
return;
}
// Get query bounds and map them to GUI coordinates.
double boundsX, boundsY, boundsWidth, boundsHeight;
query.Bounds.TryGetRectangularData(out boundsX, out boundsY, out boundsWidth, out boundsHeight);
var queryRectInGuiCoordinates = new Rect(
(float)(boundsX - _gameWindowPosition.x) * _horizontalScreenScale,
(float)(boundsY - _gameWindowPosition.y) * _verticalScreenScale,
(float)boundsWidth,
(float)boundsHeight);
// Make a copy of the collection of interactors to avoid race conditions.
List<EyeXInteractor> interactorsCopy;
lock (_lock)
{
interactorsCopy = new List<EyeXInteractor>(_interactors.Values);
}
// Create the snapshot and add the interactors that intersect with the query bounds.
var snapshot = _context.CreateSnapshotWithQueryBounds(query);
snapshot.AddWindowId(_screenHelpers.GameWindowId);
foreach (var interactor in interactorsCopy)
{
if (interactor.IntersectsWith(queryRectInGuiCoordinates))
{
interactor.AddToSnapshot(snapshot, _screenHelpers.GameWindowId, _gameWindowPosition, _horizontalScreenScale, _verticalScreenScale);
}
}
CommitSnapshot(snapshot);
snapshot.Dispose();
query.Dispose();
}
catch (InteractionApiException ex)
{
print("EyeX query handler failed: " + ex.Message);
}
}
private void HandleEvent(InteractionEvent event_)
{
// NOTE: this method is called from a worker thread, so it must not access any game objects.
try
{
// Route the event to the appropriate interactor, if any.
var interactorId = event_.InteractorId;
var globalInteractor = GetGlobalInteractor(interactorId);
if (globalInteractor != null)
{
globalInteractor.HandleEvent(event_, _gameWindowPosition, _horizontalScreenScale, _verticalScreenScale);
return;
}
var interactor = GetInteractor(interactorId);
if (interactor != null)
{
interactor.HandleEvent(event_);
}
event_.Dispose();
}
catch (InteractionApiException ex)
{
print("EyeX event handler failed: " + ex.Message);
}
}
private void OnGlobalInteractorUpdated(object sender, EventArgs e)
{
var globalInteractor = (IEyeXGlobalInteractor)sender;
if (_isConnected)
{
CommitGlobalInteractors(new[] { globalInteractor });
}
}
private void CommitAllGlobalInteractors()
{
// make a copy of the collection of interactors to avoid race conditions.
List<IEyeXGlobalInteractor> globalInteractorsCopy;
lock (_lock)
{
if (_globalInteractors.Count == 0) { return; }
globalInteractorsCopy = new List<IEyeXGlobalInteractor>(_globalInteractors.Values);
}
CommitGlobalInteractors(globalInteractorsCopy);
}
private void CommitGlobalInteractors(IEnumerable<IEyeXGlobalInteractor> globalInteractors)
{
try
{
var snapshot = CreateGlobalInteractorSnapshot();
var forceDeletion = !IsRunning;
foreach (var globalInteractor in globalInteractors)
{
globalInteractor.AddToSnapshot(snapshot, forceDeletion);
}
CommitSnapshot(snapshot);
}
catch (InteractionApiException ex)
{
print("EyeX operation failed: " + ex.Message);
}
}
private Snapshot CreateGlobalInteractorSnapshot()
{
var snapshot = _context.CreateSnapshot();
snapshot.CreateBounds(BoundsType.None);
snapshot.AddWindowId(Literals.GlobalInteractorWindowId);
return snapshot;
}
private void CommitSnapshot(Snapshot snapshot)
{
#if DEVELOPMENT_BUILD
snapshot.CommitAsync(OnSnapshotCommitted);
#else
snapshot.CommitAsync(null);
#endif
}
#if DEVELOPMENT_BUILD
private static void OnSnapshotCommitted(AsyncData asyncData)
{
try
{
ResultCode resultCode;
if (!asyncData.TryGetResultCode(out resultCode)) { return; }
if (resultCode == ResultCode.InvalidSnapshot)
{
print("Snapshot validation failed: " + GetErrorMessage(asyncData));
}
else if (resultCode != ResultCode.Ok && resultCode != ResultCode.Cancelled)
{
print("Could not commit snapshot: " + GetErrorMessage(asyncData));
}
asyncData.Dispose();
}
catch (InteractionApiException ex)
{
print("EyeX operation failed: " + ex.Message);
}
}
private static string GetErrorMessage(AsyncData asyncData)
{
string errorMessage;
if (asyncData.TryGetPropertyValue<string>(Literals.ErrorMessage, out errorMessage))
{
return errorMessage;
}
else
{
return "Unspecified error.";
}
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.GrainReferences;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime
{
/// <summary>
/// Maintains additional per-activation state that is required for Orleans internal operations.
/// MUST lock this object for any concurrent access
/// Consider: compartmentalize by usage, e.g., using separate interfaces for data for catalog, etc.
/// </summary>
internal class ActivationData : IActivationData, IGrainExtensionBinder, IAsyncDisposable
{
// This is the maximum amount of time we expect a request to continue processing
private readonly TimeSpan maxRequestProcessingTime;
private readonly TimeSpan maxWarningRequestProcessingTime;
private readonly SiloMessagingOptions messagingOptions;
private readonly ILogger logger;
private readonly IServiceScope serviceScope;
public readonly TimeSpan CollectionAgeLimit;
private readonly GrainTypeComponents _shared;
private readonly ActivationMessageScheduler _messageScheduler;
private readonly Action<object> _receiveMessageInScheduler;
private HashSet<IGrainTimer> timers;
private Dictionary<Type, object> _components;
public ActivationData(
ActivationAddress addr,
PlacementStrategy placedUsing,
IActivationCollector collector,
TimeSpan ageLimit,
IOptions<SiloMessagingOptions> messagingOptions,
TimeSpan maxWarningRequestProcessingTime,
TimeSpan maxRequestProcessingTime,
ILoggerFactory loggerFactory,
IServiceProvider applicationServices,
IGrainRuntime grainRuntime,
GrainReferenceActivator referenceActivator,
GrainTypeComponents sharedComponents,
ActivationMessageScheduler messageScheduler)
{
if (null == addr) throw new ArgumentNullException(nameof(addr));
if (null == placedUsing) throw new ArgumentNullException(nameof(placedUsing));
if (null == collector) throw new ArgumentNullException(nameof(collector));
_receiveMessageInScheduler = state => this.ReceiveMessageInScheduler(state);
_shared = sharedComponents;
_messageScheduler = messageScheduler;
logger = loggerFactory.CreateLogger<ActivationData>();
this.lifecycle = new GrainLifecycle(loggerFactory.CreateLogger<LifecycleSubject>());
this.maxRequestProcessingTime = maxRequestProcessingTime;
this.maxWarningRequestProcessingTime = maxWarningRequestProcessingTime;
this.messagingOptions = messagingOptions.Value;
ResetKeepAliveRequest();
Address = addr;
State = ActivationState.Create;
PlacedUsing = placedUsing;
if (!this.GrainId.IsSystemTarget())
{
this.collector = collector;
}
CollectionAgeLimit = ageLimit;
this.GrainReference = referenceActivator.CreateReference(addr.Grain, default);
this.serviceScope = applicationServices.CreateScope();
this.Runtime = grainRuntime;
}
public IGrainRuntime Runtime { get; }
public IServiceProvider ActivationServices => this.serviceScope.ServiceProvider;
internal WorkItemGroup WorkItemGroup { get; set; }
public async ValueTask ActivateAsync(CancellationToken cancellation)
{
await this.Lifecycle.OnStart(cancellation);
lock (this)
{
if (this.State == ActivationState.Activating)
{
this.SetState(ActivationState.Valid); // Activate calls on this activation are finished
}
this.collector.ScheduleCollection(this);
if (!this.IsCurrentlyExecuting)
{
this.RunOnInactive();
}
// Run message pump to see if there is a new request is queued to be processed
_messageScheduler.RunMessagePump(this);
}
}
public TComponent GetComponent<TComponent>()
{
TComponent result;
if (this.GrainInstance is TComponent grainResult)
{
result = grainResult;
}
else if (this is TComponent contextResult)
{
result = contextResult;
}
else if (_components is object && _components.TryGetValue(typeof(TComponent), out var resultObj))
{
result = (TComponent)resultObj;
}
else
{
result = _shared.GetComponent<TComponent>();
}
return result;
}
public void SetComponent<TComponent>(TComponent instance)
{
if (this.GrainInstance is TComponent)
{
throw new ArgumentException("Cannot override a component which is implemented by this grain");
}
if (this is TComponent)
{
throw new ArgumentException("Cannot override a component which is implemented by this grain context");
}
if (instance == null)
{
_components?.Remove(typeof(TComponent));
return;
}
if (_components is null) _components = new Dictionary<Type, object>();
_components[typeof(TComponent)] = instance;
}
internal void SetGrainInstance(Grain grainInstance)
{
GrainInstance = grainInstance;
}
public IAddressable GrainInstance { get; private set; }
public ActivationId ActivationId { get { return Address.Activation; } }
public ActivationAddress Address { get; private set; }
public IServiceProvider ServiceProvider => this.serviceScope?.ServiceProvider;
private readonly GrainLifecycle lifecycle;
public IGrainLifecycle ObservableLifecycle => lifecycle;
internal ILifecycleObserver Lifecycle => lifecycle;
public void OnTimerCreated(IGrainTimer timer)
{
AddTimer(timer);
}
public GrainReference GrainReference { get; }
public SiloAddress Silo { get { return Address.Silo; } }
public GrainId GrainId { get { return Address.Grain; } }
public ActivationState State { get; private set; }
public void SetState(ActivationState state)
{
State = state;
}
// Don't accept any new messages and stop all timers.
public void PrepareForDeactivation()
{
SetState(ActivationState.Deactivating);
deactivationStartTime = DateTime.UtcNow;
if (!IsCurrentlyExecuting)
StopAllTimers();
}
/// <summary>
/// If State == Invalid, this may contain a forwarding address for incoming messages
/// </summary>
public ActivationAddress ForwardingAddress { get; set; }
private IActivationCollector collector;
internal bool IsExemptFromCollection
{
get { return collector == null; }
}
public DateTime CollectionTicket { get; private set; }
private bool collectionCancelledFlag;
public bool TrySetCollectionCancelledFlag()
{
lock (this)
{
if (default(DateTime) == CollectionTicket || collectionCancelledFlag) return false;
collectionCancelledFlag = true;
return true;
}
}
public void ResetCollectionCancelledFlag()
{
lock (this)
{
collectionCancelledFlag = false;
}
}
public void ResetCollectionTicket()
{
CollectionTicket = default(DateTime);
}
public void SetCollectionTicket(DateTime ticket)
{
if (ticket == default(DateTime)) throw new ArgumentException("default(DateTime) is disallowed", "ticket");
if (CollectionTicket != default(DateTime))
{
throw new InvalidOperationException("call ResetCollectionTicket before calling SetCollectionTicket.");
}
CollectionTicket = ticket;
}
public PlacementStrategy PlacedUsing { get; private set; }
// Currently, the only supported multi-activation grain is one using the StatelessWorkerPlacement strategy.
internal bool IsStatelessWorker => this.PlacedUsing is StatelessWorkerPlacement;
/// <summary>
/// Returns a value indicating whether or not this placement strategy requires activations to be registered in
/// the grain directory.
/// </summary>
internal bool IsUsingGrainDirectory => this.PlacedUsing.IsUsingGrainDirectory;
public Message Blocking { get; private set; }
public Dictionary<Message, DateTime> RunningRequests { get; private set; } = new Dictionary<Message, DateTime>();
private DateTime currentRequestStartTime;
private DateTime becameIdle;
private DateTime deactivationStartTime;
public void RecordRunning(Message message, bool isInterleavable)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
var now = DateTime.UtcNow;
RunningRequests.Add(message, now);
if (this.Blocking != null || isInterleavable) return;
// This logic only works for non-reentrant activations
// Consider: Handle long request detection for reentrant activations.
this.Blocking = message;
currentRequestStartTime = now;
}
public void ResetRunning(Message message)
{
// Note: This method is always called while holding lock on this activation, so no need for additional locks here
RunningRequests.Remove(message);
if (RunningRequests.Count == 0)
{
becameIdle = DateTime.UtcNow;
if (!IsExemptFromCollection)
{
collector.TryRescheduleCollection(this);
}
}
// The below logic only works for non-reentrant activations.
if (this.Blocking != null && !message.Equals(this.Blocking)) return;
this.Blocking = null;
currentRequestStartTime = DateTime.MinValue;
}
private long inFlightCount;
private long enqueuedOnDispatcherCount;
/// <summary>
/// Number of messages that are actively being processed [as opposed to being in the Waiting queue].
/// In most cases this will be 0 or 1, but for Reentrant grains can be >1.
/// </summary>
public long InFlightCount { get { return Interlocked.Read(ref inFlightCount); } }
/// <summary>
/// Number of messages that are being received [as opposed to being in the scheduler queue or actively processed].
/// </summary>
public long EnqueuedOnDispatcherCount { get { return Interlocked.Read(ref enqueuedOnDispatcherCount); } }
/// <summary>Increment the number of in-flight messages currently being processed.</summary>
public void IncrementInFlightCount() { Interlocked.Increment(ref inFlightCount); }
/// <summary>Decrement the number of in-flight messages currently being processed.</summary>
public void DecrementInFlightCount() { Interlocked.Decrement(ref inFlightCount); }
/// <summary>Increment the number of messages currently in the process of being received.</summary>
public void IncrementEnqueuedOnDispatcherCount() { Interlocked.Increment(ref enqueuedOnDispatcherCount); }
/// <summary>Decrement the number of messages currently in the process of being received.</summary>
public void DecrementEnqueuedOnDispatcherCount() { Interlocked.Decrement(ref enqueuedOnDispatcherCount); }
/// <summary>
/// grouped by sending activation: responses first, then sorted by id
/// </summary>
private List<Message> waiting;
public int WaitingCount
{
get
{
return waiting == null ? 0 : waiting.Count;
}
}
public enum EnqueueMessageResult
{
Success,
ErrorInvalidActivation,
ErrorStuckActivation,
ErrorActivateFailed,
}
/// <summary>
/// Insert in a FIFO order
/// </summary>
/// <param name="message"></param>
public EnqueueMessageResult EnqueueMessage(Message message)
{
lock (this)
{
if (State == ActivationState.Invalid)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to invalid activation {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorInvalidActivation;
}
if (State == ActivationState.FailedToActivate)
{
logger.Warn(ErrorCode.Dispatcher_InvalidActivation,
"Cannot enqueue message to activation that failed in OnActivate {0} : {1}", this.ToDetailedString(), message);
return EnqueueMessageResult.ErrorActivateFailed;
}
if (State == ActivationState.Deactivating)
{
var deactivatingTime = DateTime.UtcNow - deactivationStartTime;
if (deactivatingTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current activation {ToDetailedString()} marked as Deactivating for {deactivatingTime}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
}
if (this.Blocking != null)
{
var currentRequestActiveTime = DateTime.UtcNow - currentRequestStartTime;
if (currentRequestActiveTime > maxRequestProcessingTime)
{
logger.Error(ErrorCode.Dispatcher_StuckActivation,
$"Current request has been active for {currentRequestActiveTime} for activation {ToDetailedString()}. Currently executing {this.Blocking}. Trying to enqueue {message}.");
return EnqueueMessageResult.ErrorStuckActivation;
}
// Consider: Handle long request detection for reentrant activations -- this logic only works for non-reentrant activations
else if (currentRequestActiveTime > maxWarningRequestProcessingTime)
{
logger.Warn(ErrorCode.Dispatcher_ExtendedMessageProcessing,
"Current request has been active for {0} for activation {1}. Currently executing {2}. Trying to enqueue {3}.",
currentRequestActiveTime, this.ToDetailedString(), this.Blocking, message);
}
}
if (!message.QueuedTime.HasValue)
{
message.QueuedTime = DateTime.UtcNow;
}
waiting ??= new List<Message>();
waiting.Add(message);
return EnqueueMessageResult.Success;
}
}
/// <summary>
/// Check whether this activation is overloaded.
/// Returns LimitExceededException if overloaded, otherwise <c>null</c>c>
/// </summary>
/// <returns>Returns LimitExceededException if overloaded, otherwise <c>null</c>c></returns>
public LimitExceededException CheckOverloaded()
{
string limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS;
int maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit;
int maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit;
if (IsStatelessWorker)
{
limitName = LimitNames.LIMIT_MAX_ENQUEUED_REQUESTS_STATELESS_WORKER;
maxRequestsHardLimit = this.messagingOptions.MaxEnqueuedRequestsHardLimit_StatelessWorker;
maxRequestsSoftLimit = this.messagingOptions.MaxEnqueuedRequestsSoftLimit_StatelessWorker;
}
if (maxRequestsHardLimit <= 0 && maxRequestsSoftLimit <= 0) return null; // No limits are set
int count = GetRequestCount();
if (maxRequestsHardLimit > 0 && count > maxRequestsHardLimit) // Hard limit
{
this.logger.LogWarning(
(int)ErrorCode.Catalog_Reject_ActivationTooManyRequests,
"Overload - {Count} enqueued requests for activation {Activation}, exceeding hard limit rejection threshold of {HardLimit}",
count,
this,
maxRequestsHardLimit);
return new LimitExceededException(limitName, count, maxRequestsHardLimit, this.ToString());
}
if (maxRequestsSoftLimit > 0 && count > maxRequestsSoftLimit) // Soft limit
{
this.logger.LogWarning(
(int)ErrorCode.Catalog_Warn_ActivationTooManyRequests,
"Hot - {Count} enqueued requests for activation {Activation}, exceeding soft limit warning threshold of {SoftLimit}",
count,
this,
maxRequestsSoftLimit);
return null;
}
return null;
}
internal int GetRequestCount()
{
lock (this)
{
long numInDispatcher = EnqueuedOnDispatcherCount;
long numActive = InFlightCount;
long numWaiting = WaitingCount;
return (int)(numInDispatcher + numActive + numWaiting);
}
}
public Message PeekNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0) return waiting[0];
return null;
}
public void DequeueNextWaitingMessage()
{
if (waiting != null && waiting.Count > 0)
waiting.RemoveAt(0);
}
internal List<Message> DequeueAllWaitingMessages()
{
lock (this)
{
if (waiting == null) return null;
List<Message> tmp = waiting;
waiting = null;
return tmp;
}
}
public bool IsInactive
{
get
{
return !IsCurrentlyExecuting && (waiting == null || waiting.Count == 0);
}
}
public bool IsCurrentlyExecuting
{
get
{
return RunningRequests.Count > 0;
}
}
/// <summary>
/// Returns how long this activation has been idle.
/// </summary>
public TimeSpan GetIdleness(DateTime now)
{
if (now == default(DateTime))
throw new ArgumentException("default(DateTime) is not allowed; Use DateTime.UtcNow instead.", "now");
return now - becameIdle;
}
/// <summary>
/// Returns whether this activation has been idle long enough to be collected.
/// </summary>
public bool IsStale(DateTime now)
{
return GetIdleness(now) >= CollectionAgeLimit;
}
private DateTime keepAliveUntil;
public bool ShouldBeKeptAlive { get { return keepAliveUntil >= DateTime.UtcNow; } }
public void DelayDeactivation(TimeSpan timespan)
{
if (timespan <= TimeSpan.Zero)
{
// reset any current keepAliveUntill
ResetKeepAliveRequest();
}
else if (timespan == TimeSpan.MaxValue)
{
// otherwise creates negative time.
keepAliveUntil = DateTime.MaxValue;
}
else
{
keepAliveUntil = DateTime.UtcNow + timespan;
}
}
public void ResetKeepAliveRequest()
{
keepAliveUntil = DateTime.MinValue;
}
public List<Action> OnInactive { get; set; } // ActivationData
public void AddOnInactive(Action action) // ActivationData
{
lock (this)
{
if (OnInactive == null)
{
OnInactive = new List<Action>();
}
OnInactive.Add(action);
if (!IsCurrentlyExecuting)
{
RunOnInactive();
}
}
}
public void RunOnInactive()
{
lock (this)
{
if (OnInactive == null) return;
var actions = OnInactive;
OnInactive = null;
foreach (var action in actions)
{
action();
}
}
}
internal void AddTimer(IGrainTimer timer)
{
lock(this)
{
if (timers == null)
{
timers = new HashSet<IGrainTimer>();
}
timers.Add(timer);
}
}
private void StopAllTimers()
{
lock (this)
{
if (timers == null) return;
foreach (var timer in timers)
{
timer.Stop();
}
}
}
public void OnTimerDisposed(IGrainTimer orleansTimerInsideGrain)
{
lock (this) // need to lock since dispose can be called on finalizer thread, outside grain context (not single threaded).
{
timers.Remove(orleansTimerInsideGrain);
}
}
internal Task WaitForAllTimersToFinish()
{
lock(this)
{
if (timers == null)
{
return Task.CompletedTask;
}
var tasks = new List<Task>();
var timerCopy = timers.ToList(); // need to copy since OnTimerDisposed will change the timers set.
foreach (var timer in timerCopy)
{
// first call dispose, then wait to finish.
Utils.SafeExecute(timer.Dispose, logger, "timer.Dispose has thrown");
tasks.Add(timer.GetCurrentlyExecutingTickTask());
}
return Task.WhenAll(tasks);
}
}
public void AnalyzeWorkload(DateTime now, IMessageCenter messageCenter, MessageFactory messageFactory, SiloMessagingOptions options)
{
var slowRunningRequestDuration = options.RequestProcessingWarningTime;
var longQueueTimeDuration = options.RequestQueueDelayWarningTime;
List<string> diagnostics = null;
lock (this)
{
if (State != ActivationState.Valid)
{
return;
}
if (this.Blocking is object)
{
var message = this.Blocking;
var timeSinceQueued = now - message.QueuedTime;
var executionTime = now - currentRequestStartTime;
if (executionTime >= slowRunningRequestDuration)
{
GetStatusList(ref diagnostics);
if (timeSinceQueued.HasValue)
{
diagnostics.Add($"Message {message} was enqueued {timeSinceQueued} ago and has now been executing for {executionTime}.");
}
else
{
diagnostics.Add($"Message {message} was has been executing for {executionTime}.");
}
var response = messageFactory.CreateDiagnosticResponseMessage(message, isExecuting: true, isWaiting: false, diagnostics);
messageCenter.SendMessage(response);
}
}
foreach (var running in RunningRequests)
{
var message = running.Key;
var startTime = running.Value;
if (ReferenceEquals(message, this.Blocking)) continue;
// Check how long they've been executing.
var executionTime = now - startTime;
if (executionTime >= slowRunningRequestDuration)
{
// Interleaving message X has been executing for a long time
GetStatusList(ref diagnostics);
var messageDiagnostics = new List<string>(diagnostics)
{
$"Interleaving message {message} has been executing for {executionTime}."
};
var response = messageFactory.CreateDiagnosticResponseMessage(message, isExecuting: true, isWaiting: false, messageDiagnostics);
messageCenter.SendMessage(response);
}
}
if (waiting is object)
{
var queueLength = 1;
foreach (var message in waiting)
{
var waitTime = now - message.QueuedTime;
if (waitTime >= longQueueTimeDuration)
{
// Message X has been enqueued on the target grain for Y and is currently position QueueLength in queue for processing.
GetStatusList(ref diagnostics);
var messageDiagnostics = new List<string>(diagnostics)
{
$"Message {message} has been enqueued on the target grain for {waitTime} and is currently position {queueLength} in queue for processing."
};
var response = messageFactory.CreateDiagnosticResponseMessage(message, isExecuting: false, isWaiting: true, messageDiagnostics);
messageCenter.SendMessage(response);
}
queueLength++;
}
}
}
void GetStatusList(ref List<string> diagnostics)
{
if (diagnostics is object) return;
diagnostics = new List<string>
{
this.ToDetailedString(),
$"TaskScheduler status: {this.WorkItemGroup.DumpStatus()}"
};
}
}
public string DumpStatus()
{
var sb = new StringBuilder();
lock (this)
{
sb.AppendFormat(" {0}", ToDetailedString());
if (this.Blocking != null)
{
sb.AppendFormat(" Processing message: {0}", this.Blocking);
}
foreach (var msg in RunningRequests)
{
if (ReferenceEquals(msg.Key, this.Blocking)) continue;
sb.AppendFormat(" Processing message: {0}", msg);
}
if (waiting!=null && waiting.Count > 0)
{
sb.AppendFormat(" Messages queued within ActivationData: {0}", PrintWaitingQueue());
}
}
return sb.ToString();
}
public override string ToString()
{
return String.Format("[Activation: {0}/{1}{2}{3} State={4}]",
Silo,
this.GrainId,
this.ActivationId,
GetActivationInfoString(),
State);
}
internal string ToDetailedString(bool includeExtraDetails = false)
{
return
String.Format(
"[Activation: {0}/{1}{2} {3} State={4} NonReentrancyQueueSize={5} EnqueuedOnDispatcher={6} InFlightCount={7} NumRunning={8} IdlenessTimeSpan={9} CollectionAgeLimit={10}{11}]",
Silo.ToLongString(),
this.GrainId.ToString(),
this.ActivationId,
GetActivationInfoString(),
State, // 4
WaitingCount, // 5 NonReentrancyQueueSize
EnqueuedOnDispatcherCount, // 6 EnqueuedOnDispatcher
InFlightCount, // 7 InFlightCount
RunningRequests.Count, // 8 NumRunning
GetIdleness(DateTime.UtcNow), // 9 IdlenessTimeSpan
CollectionAgeLimit, // 10 CollectionAgeLimit
(includeExtraDetails && this.Blocking != null) ? " CurrentlyExecuting=" + this.Blocking : ""); // 11: Running
}
public string Name
{
get
{
return String.Format("[Activation: {0}{1}{2}{3}]",
Silo,
this.GrainId,
this.ActivationId,
GetActivationInfoString());
}
}
/// <summary>
/// Return string containing dump of the queue of waiting work items
/// </summary>
/// <returns></returns>
/// <remarks>Note: Caller must be holding lock on this activation while calling this method.</remarks>
internal string PrintWaitingQueue()
{
return Utils.EnumerableToString(waiting);
}
private string GetActivationInfoString()
{
var placement = PlacedUsing != null ? PlacedUsing.GetType().Name : String.Empty;
return GrainInstance is null ? placement : $"#GrainType={GrainInstance.GetType().FullName} Placement={placement}";
}
public async ValueTask DisposeAsync()
{
var activator = this.GetComponent<IGrainActivator>();
if (activator != null)
{
await activator.DisposeInstance(this, this.GrainInstance);
}
switch (this.serviceScope)
{
case IAsyncDisposable asyncDisposable:
await asyncDisposable.DisposeAsync();
break;
case IDisposable disposable:
disposable.Dispose();
break;
}
}
bool IEquatable<IGrainContext>.Equals(IGrainContext other) => ReferenceEquals(this, other);
public (TExtension, TExtensionInterface) GetOrSetExtension<TExtension, TExtensionInterface>(Func<TExtension> newExtensionFunc)
where TExtension : TExtensionInterface
where TExtensionInterface : IGrainExtension
{
TExtension implementation;
if (this.GetComponent<TExtensionInterface>() is object existing)
{
if (existing is TExtension typedResult)
{
implementation = typedResult;
}
else
{
throw new InvalidCastException($"Cannot cast existing extension of type {existing.GetType()} to target type {typeof(TExtension)}");
}
}
else
{
implementation = newExtensionFunc();
this.SetComponent<TExtensionInterface>(implementation);
}
var reference = this.GrainReference.Cast<TExtensionInterface>();
return (implementation, reference);
}
public TExtensionInterface GetExtension<TExtensionInterface>()
where TExtensionInterface : IGrainExtension
{
if (this.GetComponent<TExtensionInterface>() is TExtensionInterface result)
{
return result;
}
var implementation = this.ActivationServices.GetServiceByKey<Type, IGrainExtension>(typeof(TExtensionInterface));
if (!(implementation is TExtensionInterface typedResult))
{
throw new GrainExtensionNotInstalledException($"No extension of type {typeof(TExtensionInterface)} is installed on this instance and no implementations are registered for automated install");
}
this.SetComponent<TExtensionInterface>(typedResult);
return typedResult;
}
public void ReceiveMessage(object message)
{
var msg = (Message)message;
lock (this)
{
// Get the activation's scheduler or the default task scheduler if the activation is not valid.
// Requests to an invalid activation are handled later.
var scheduler = this.WorkItemGroup?.TaskScheduler ?? TaskScheduler.Default;
this.IncrementEnqueuedOnDispatcherCount();
// Enqueue the handler on the activation's scheduler
var task = new Task(_receiveMessageInScheduler, msg);
task.Start(scheduler);
}
}
private void ReceiveMessageInScheduler(object state)
{
try
{
_messageScheduler.ReceiveMessage(this, (Message)state);
}
finally
{
this.DecrementEnqueuedOnDispatcherCount();
}
}
}
internal static class StreamResourceTestControl
{
internal static bool TestOnlySuppressStreamCleanupOnDeactivate;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using NUnit.Framework;
using System.Drawing;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
namespace OpenQA.Selenium
{
[TestFixture]
public class VisibilityTest : DriverTestFixture
{
[Test]
[Category("Javascript")]
public void ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot()
{
driver.Url = javascriptPage;
Assert.IsTrue(driver.FindElement(By.Id("displayed")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("none")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("suppressedParagraph")).Displayed);
Assert.IsFalse(driver.FindElement(By.Id("hidden")).Displayed);
}
[Test]
[Category("Javascript")]
public void VisibilityShouldTakeIntoAccountParentVisibility()
{
driver.Url = javascriptPage;
IWebElement childDiv = driver.FindElement(By.Id("hiddenchild"));
IWebElement hiddenLink = driver.FindElement(By.Id("hiddenlink"));
Assert.IsFalse(childDiv.Displayed);
Assert.IsFalse(hiddenLink.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Id("visibleSubElement"));
Assert.IsTrue(shown.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldModifyTheVisibilityOfAnElementDynamically()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("hideMe"));
Assert.IsTrue(element.Displayed);
element.Click();
Assert.IsFalse(element.Displayed);
}
[Test]
[Category("Javascript")]
public void HiddenInputElementsAreNeverVisible()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Name("hidden"));
Assert.IsFalse(shown.Displayed);
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.Throws<ElementNotVisibleException>(() => element.Click());
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.Throws<ElementNotVisibleException>(() => element.SendKeys("You don't see me"));
Assert.AreNotEqual(element.GetAttribute("value"), "You don't see me");
}
[Test]
[Category("Javascript")]
public void ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("untogglable"));
Assert.Throws<ElementNotVisibleException>(() => element.Click());
}
[Test]
[Category("Javascript")]
public void ZeroSizedDivIsShownIfDescendantHasSize()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("zero"));
Size size = element.Size;
Assert.AreEqual(0, size.Width, "Should have 0 width");
Assert.AreEqual(0, size.Height, "Should have 0 height");
Assert.IsTrue(element.Displayed);
}
[Test]
public void ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("suggest"));
Assert.IsTrue(element.Displayed);
}
[Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.PhantomJS)]
[IgnoreBrowser(Browser.Safari)]
public void ElementHiddenByOverflowXIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_hidden_y_scroll.html",
"overflow/x_hidden_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.IsFalse(right.Displayed, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsFalse(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Chrome)]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
[IgnoreBrowser(Browser.PhantomJS)]
public void ElementHiddenByOverflowYIsNotVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_hidden.html",
"overflow/x_scroll_y_hidden.html",
"overflow/x_auto_y_hidden.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.IsFalse(bottom.Displayed, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsFalse(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_hidden.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_hidden.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement right = driver.FindElement(By.Id("right"));
Assert.IsTrue(right.Displayed, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Safari)]
public void ElementScrollableByOverflowYIsVisible()
{
string[] pages = new string[]{
"overflow/x_hidden_y_scroll.html",
"overflow/x_scroll_y_scroll.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_hidden_y_auto.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottom = driver.FindElement(By.Id("bottom"));
Assert.IsTrue(bottom.Displayed, "Failed for " + page);
}
}
[Test]
public void ElementScrollableByOverflowXAndYIsVisible()
{
string[] pages = new string[]{
"overflow/x_scroll_y_scroll.html",
"overflow/x_scroll_y_auto.html",
"overflow/x_auto_y_scroll.html",
"overflow/x_auto_y_auto.html",
};
foreach (string page in pages)
{
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs(page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.IsTrue(bottomRight.Displayed, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Android)]
[IgnoreBrowser(Browser.IPhone)]
[IgnoreBrowser(Browser.Opera)]
public void tooSmallAWindowWithOverflowHiddenIsNotAProblem()
{
IWindow window = driver.Manage().Window;
Size originalSize = window.Size;
try
{
// Short in the Y dimension
window.Size = new Size(1024, 500);
driver.Url = EnvironmentManager.Instance.UrlBuilder.WhereIs("overflow-body.html");
IWebElement element = driver.FindElement(By.Name("resultsFrame"));
Assert.IsTrue(element.Displayed);
}
finally
{
window.Size = originalSize;
}
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldShowElementNotVisibleWithHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("singleHidden"));
Assert.IsFalse(element.Displayed);
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
[IgnoreBrowser(Browser.HtmlUnit)]
public void ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("child"));
Assert.IsFalse(element.Displayed);
}
[Test]
public void ShouldBeAbleToClickOnElementsWithOpacityZero()
{
if (TestUtilities.IsOldIE(driver))
{
return;
}
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.AreEqual("0", element.GetCssValue("opacity"), "Precondition failed: clickJacker should be transparent");
element.Click();
Assert.AreEqual("1", element.GetCssValue("opacity"));
}
[Test]
[Category("JavaScript")]
[IgnoreBrowser(Browser.HtmlUnit)]
[IgnoreBrowser(Browser.Opera)]
public void ShouldBeAbleToSelectOptionsFromAnInvisibleSelect()
{
driver.Url = formsPage;
IWebElement select = driver.FindElement(By.Id("invisi_select"));
ReadOnlyCollection<IWebElement> options = select.FindElements(By.TagName("option"));
IWebElement apples = options[0];
IWebElement oranges = options[1];
Assert.IsTrue(apples.Selected, "Apples should be selected");
Assert.IsFalse(oranges.Selected, "Oranges shoudl be selected");
oranges.Click();
Assert.IsFalse(apples.Selected, "Apples should not be selected");
Assert.IsTrue(oranges.Selected, "Oranges should be selected");
}
[Test]
[Category("Javascript")]
public void CorrectlyDetectMapElementsAreShown()
{
driver.Url = mapVisibilityPage;
IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0"));
bool isShown = area.Displayed;
Assert.IsTrue(isShown, "The element and the enclosing map should be considered shown.");
}
[Test]
public void ElementsWithOpacityZeroShouldNotBeVisible()
{
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.IsFalse(element.Displayed);
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using Axiom;
using Axiom.Collections;
using Axiom.Core;
using Axiom.MathLib;
using Axiom.Graphics;
namespace Axiom.SceneManagers.Octree {
/// <summary>
/// Summary description for OctreeSceneManager.
/// </summary>
public class OctreeSceneManager : SceneManager {
#region Member Variables
protected System.Collections.ArrayList boxList = new ArrayList();
protected System.Collections.ArrayList colorList = new ArrayList();
//NOTE: "visible" was a Nodelist...could be a custom collection
protected System.Collections.ArrayList visible = new ArrayList();
public System.Collections.Hashtable options = new Hashtable();
protected static long white = 0xFFFFFFFF;
protected ushort[] indexes = {0,1,1,2,2,3,3,0,0,6,6,5,5,1,3,7,7,4,4,2,6,7,5,4};
protected long[] colors = {white, white, white, white, white, white, white, white };
protected float[] corners;
protected Matrix4 scaleFactor;
protected int intersect = 0;
protected int maxDepth;
protected bool cullCamera;
protected float worldSize;
protected int numObjects;
protected bool looseOctree;
//protected bool showBoxes;
protected Octree octree;
public enum Intersection {
Outside,
Inside,
Intersect
}
#endregion
#region Properties
public long White {
get {
return white;
}
}
#endregion
public OctreeSceneManager() : base("OcttreeSM") {
Vector3 Min = new Vector3(-500f,-500f,-500f);
Vector3 Max = new Vector3(500f,500f,500f);
int depth = 5;
AxisAlignedBox box = new AxisAlignedBox(Min, Max);
Init(box, depth);
}
public OctreeSceneManager(string name, AxisAlignedBox box, int max_depth) : base(name) {
Init(box, max_depth);
}
public Intersection Intersect(AxisAlignedBox box1, AxisAlignedBox box2) {
intersect++;
Vector3[] outside = box1.Corners;
Vector3[] inside = box2.Corners;
if(inside[4].x < outside[0].x ||
inside[4].y < outside[0].y ||
inside[4].z < outside[0].z ||
inside[0].x > outside[4].x ||
inside[0].y > outside[4].y ||
inside[0].z > outside[4].z ) {
return Intersection.Outside;
}
if(inside[0].x > outside[0].x &&
inside[0].y > outside[0].y &&
inside[0].z > outside[0].z &&
inside[4].x < outside[4].x &&
inside[4].y < outside[4].y &&
inside[4].z < outside[4].z ) {
return Intersection.Inside;
}
else {
return Intersection.Intersect;
}
}
public Intersection Intersect(Sphere sphere, AxisAlignedBox box) {
intersect++;
float Radius = sphere.Radius;
Vector3 Center = sphere.Center;
Vector3[] Corners = box.Corners;
float s = 0;
float d = 0;
int i;
bool Partial;
Radius *= Radius;
Vector3 MinDistance = (Corners[0] - Center);
Vector3 MaxDistance = (Corners[4] - Center);
if((MinDistance.LengthSquared < Radius) && (MaxDistance.LengthSquared < Radius)) {
return Intersection.Inside;
}
//find the square of the distance
//from the sphere to the box
for(i=0;i<3;i++) {
if ( Center[i] < Corners[0][i] ) {
s = Center[i] - Corners[0][i];
d += s * s;
}
else if ( Center[i] > Corners[4][i] ) {
s = Center[i] - Corners[4][i];
d += s * s;
}
}
Partial = (d <= Radius);
if(!Partial) {
return Intersection.Outside;
}
else {
return Intersection.Intersect;
}
}
public void Init(AxisAlignedBox box, int depth) {
rootSceneNode = new OctreeNode(this, "SceneRoot");
maxDepth = depth;
octree = new Octree(null);
octree.Box = box;
Vector3 Min = box.Minimum;
Vector3 Max = box.Maximum;
octree.HalfSize = (Max - Min) / 2;
numObjects = 0;
Vector3 scalar = new Vector3(1.5f,1.5f,1.5f);
scaleFactor.Scale = scalar;
}
public override SceneNode CreateSceneNode() {
OctreeNode node = new OctreeNode(this);
sceneNodeList[node.Name] = node;
return node;
}
public override SceneNode CreateSceneNode(string name) {
OctreeNode node = new OctreeNode(this, name);
sceneNodeList[node.Name] = node;
return node;
}
public override Camera CreateCamera(string name) {
Camera cam = new OctreeCamera(name, this);
cameraList.Add(name, cam);
// create visible bounds aabb map entry
camVisibleObjectsMap[cam] = new VisibleObjectsBoundsInfo();
return cam;
}
protected override void UpdateSceneGraph(Camera cam) {
base.UpdateSceneGraph(cam);
}
public override void FindVisibleObjects(Camera cam, VisibleObjectsBoundsInfo visibleBounds, bool onlyShadowCasters) {
GetRenderQueue().Clear();
boxList.Clear();
visible.Clear();
if(cullCamera) {
Camera c = cameraList["CullCamera"];
if(c != null) {
cameraInProgress = cameraList["CullCamera"];
}
}
numObjects = 0;
//walk the octree, adding all visible Octreenodes nodes to the render queue.
WalkOctree((OctreeCamera)cam, GetRenderQueue(), octree, visibleBounds, onlyShadowCasters, false);
// Show the octree boxes & cull camera if required
if(this.ShowBoundingBoxes || cullCamera) {
if(this.ShowBoundingBoxes) {
for(int i = 0; i < boxList.Count; i++) {
WireBoundingBox box = (WireBoundingBox)boxList[i];
GetRenderQueue().AddRenderable(box);
}
}
if(cullCamera) {
OctreeCamera c = (OctreeCamera)GetCamera("CullCamera");
if(c != null) {
GetRenderQueue().AddRenderable(c);
}
}
}
}
/** Alerts each unculled object, notifying it that it will be drawn.
* Useful for doing calculations only on nodes that will be drawn, prior
* to drawing them...
*/
public void AlertVisibleObjects() {
int i;
for(i=0;i<visible.Count;i++) {
OctreeNode node = (OctreeNode)visible[i];
//TODO: looks like something is missing here
}
}
/** Walks through the octree, adding any visible objects to the render queue.
@remarks
If any octant in the octree if completely within the the view frustum,
all subchildren are automatically added with no visibility tests.
*/
public void WalkOctree(OctreeCamera camera, RenderQueue queue, Octree octant,
VisibleObjectsBoundsInfo visibleBounds, bool onlyShadowCasters, bool foundVisible) {
//return immediately if nothing is in the node.
if(octant.NumNodes == 0) {
return;
}
Visibility v = Visibility.None;
if(foundVisible) {
v = Visibility.Full;
}
else if(octant == octree) {
v = Visibility.Partial;
}
else {
AxisAlignedBox box = octant.CullBounds;
v = camera.GetVisibility(box);
}
// if the octant is visible, or if it's the root node...
if(v != Visibility.None) {
if(this.ShowBoundingBoxes) {
// TODO: Implement Octree.WireBoundingBox
//boxList.Add(octant.WireBoundingBox);
}
bool vis = true;
for(int i = 0; i < octant.NodeList.Count; i++) {
OctreeNode node = (OctreeNode)octant.NodeList[i];
// if this octree is partially visible, manually cull all
// scene nodes attached directly to this level.
if(v == Visibility.Partial) {
vis = camera.IsObjectVisible(node.WorldAABB);
}
if(vis) {
numObjects++;
node.AddToRenderQueue(camera, queue, onlyShadowCasters, visibleBounds);
visible.Add(node);
if(DisplayNodes) {
GetRenderQueue().AddRenderable(node);
}
// check if the scene manager or this node wants the bounding box shown.
if(node.ShowBoundingBox || this.ShowBoundingBoxes) {
node.AddBoundingBoxToQueue(queue);
}
}
}
if(octant.Children[0,0,0] != null ) WalkOctree(camera, queue, octant.Children[0,0,0], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[1,0,0] != null ) WalkOctree(camera, queue, octant.Children[1,0,0], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[0,1,0] != null ) WalkOctree(camera, queue, octant.Children[0,1,0], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[1,1,0] != null ) WalkOctree(camera, queue, octant.Children[1,1,0], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[0,0,1] != null ) WalkOctree(camera, queue, octant.Children[0,0,1], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[1,0,1] != null ) WalkOctree(camera, queue, octant.Children[1,0,1], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[0,1,1] != null ) WalkOctree(camera, queue, octant.Children[0,1,1], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
if(octant.Children[1,1,1] != null ) WalkOctree(camera, queue, octant.Children[1,1,1], visibleBounds, onlyShadowCasters, ( v == Visibility.Full ) );
}
}
/** Checks the given OctreeNode, and determines if it needs to be moved
* to a different octant.
*/
public void UpdateOctreeNode(OctreeNode node) {
AxisAlignedBox box = node.WorldAABB;
if(box.IsNull) {
return;
}
if(node.Octant == null) {
//if outside the octree, force into the root node.
if(!node.IsInBox(octree.Box)) {
octree.AddNode(node);
}
else {
AddOctreeNode(node, octree);
return;
}
}
if(!node.IsInBox(node.Octant.Box)) {
RemoveOctreeNode(node);
//if outside the octree, force into the root node.
if(!node.IsInBox(octree.Box)) {
octree.AddNode(node);
}
else {
AddOctreeNode(node,octree);
}
}
}
/*public void RemoveOctreeNode(OctreeNode node, Octree tree, int depth)
{
}*/
/** Only removes the node from the octree. It leaves the octree, even if it's empty.
*/
public void RemoveOctreeNode(OctreeNode node) {
Octree tree = node.Octant;
if(tree != null) {
tree.RemoveNode(node);
}
}
public override void DestroySceneNode(string name) {
OctreeNode node = (OctreeNode)GetSceneNode(name);
if(node != null) {
RemoveOctreeNode(node);
}
base.DestroySceneNode(name);
}
public void AddOctreeNode(OctreeNode node, Octree octant) {
AddOctreeNode(node, octant, 0);
}
public void AddOctreeNode(OctreeNode node, Octree octant, int depth) {
AxisAlignedBox box = node.WorldAABB;
//if the octree is twice as big as the scene node,
//we will add it to a child.
if((depth < maxDepth) && octant.IsTwiceSize(box)) {
int x,y,z;
octant.GetChildIndexes(box, out x, out y, out z);
if(octant.Children[x,y,z] == null) {
octant.Children[x,y,z] = new Octree(octant);
Vector3[] corners = octant.Box.Corners;
Vector3 min, max;
if(x == 0) {
min.x = corners[0].x;
max.x = (corners[0].x + corners[4].x) / 2;
}
else {
min.x = (corners[0].x + corners[4].x) / 2;
max.x = corners[4].x;
}
if ( y == 0 ) {
min.y = corners[ 0 ].y;
max.y = ( corners[ 0 ].y + corners[ 4 ].y ) / 2;
}
else {
min.y = ( corners[ 0 ].y + corners[ 4 ].y ) / 2;
max.y = corners[ 4 ].y;
}
if ( z == 0 ) {
min.z = corners[ 0 ].z;
max.z = ( corners[ 0 ].z + corners[ 4 ].z ) / 2;
}
else {
min.z = ( corners[ 0 ].z + corners[ 4 ].z ) / 2;
max.z = corners[ 4 ].z;
}
octant.Children[x,y,z].Box.SetExtents(min,max);
octant.Children[x,y,z].HalfSize = (max - min) / 2;
}
AddOctreeNode(node, octant.Children[x,y,z], ++depth);
}
else {
octant.AddNode(node);
}
}
/*public void AddOctreeNode(OctreeNode node, Octree octree)
{
}*/
/** Resizes the octree to the given size */
public void Resize(AxisAlignedBox box) {
List<SceneNode> nodes = new List<SceneNode>();
FindNodes(this.octree.Box, nodes, null, true, this.octree);
octree = new Octree(null);
octree.Box = box;
foreach (OctreeNode node in nodes) {
node.Octant = null;
UpdateOctreeNode(node);
}
}
public void FindNodes(AxisAlignedBox box, List<SceneNode> sceneNodeList, SceneNode exclude, bool full, Octree octant) {
System.Collections.ArrayList localList = new System.Collections.ArrayList();
if(octant == null) {
octant = this.octree;
}
if(!full) {
AxisAlignedBox obox = octant.CullBounds;
Intersection isect = this.Intersect(box,obox);
if(isect == Intersection.Outside) {
return;
}
full = (isect == Intersection.Inside);
}
for(int i=0;i<octant.NodeList.Count;i++) {
OctreeNode node = (OctreeNode)octant.NodeList[i];
if(node != exclude) {
if(full) {
localList.Add(node);
}
else {
Intersection nsect = this.Intersect(box,node.WorldAABB);
if(nsect != Intersection.Outside) {
localList.Add(node);
}
}
}
}
if ( octant.Children[0,0,0] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[0,0,0]);
if ( octant.Children[1,0,0] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[1,0,0]);
if ( octant.Children[0,1,0] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[0,1,0] );
if ( octant.Children[1,1,0] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[1,1,0]);
if ( octant.Children[0,0,1] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[0,0,1]);
if ( octant.Children[1,0,1] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[1,0,1]);
if ( octant.Children[0,1,1] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[0,1,1]);
if ( octant.Children[1,1,1] != null ) FindNodes( box, sceneNodeList, exclude, full, octant.Children[1,1,1]);
}
public void FindNodes(Sphere sphere, List<SceneNode> sceneNodeList, SceneNode exclude, bool full, Octree octant) {
//TODO: Implement
}
public bool SetOption(string key,object val) {
bool ret = false;
switch(key) {
case "Size":
Resize((AxisAlignedBox)val);
ret = true;
break;
case "Depth":
maxDepth = (int)val;
Resize(this.octree.Box);
ret = true;
break;
case "ShowOctree":
this.ShowBoundingBoxes = (bool)val;
ret = true;
break;
case "CullCamera":
cullCamera = (bool)val;
ret = true;
break;
}
return ret;
}
public bool GetOption() {
return true;//TODO: Implement
}
}
}
| |
/*
* Farseer Physics Engine:
* Copyright (c) 2012 Ian Qvist
*
* Original source Box2D:
* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
using System;
using System.Diagnostics;
using Astrid.Core;
using Astrid.FarseerPhysics.Collision;
using Astrid.FarseerPhysics.Collision.Shapes;
using Astrid.FarseerPhysics.Common;
namespace Astrid.FarseerPhysics.Dynamics.Contacts
{
public sealed class ContactPositionConstraint
{
public Vector2[] localPoints = new Vector2[Settings.MaxManifoldPoints];
public Vector2 localNormal;
public Vector2 localPoint;
public int indexA;
public int indexB;
public float invMassA, invMassB;
public Vector2 localCenterA, localCenterB;
public float invIA, invIB;
public ManifoldType type;
public float radiusA, radiusB;
public int pointCount;
}
public sealed class VelocityConstraintPoint
{
public Vector2 rA;
public Vector2 rB;
public float normalImpulse;
public float tangentImpulse;
public float normalMass;
public float tangentMass;
public float velocityBias;
}
public sealed class ContactVelocityConstraint
{
public VelocityConstraintPoint[] points = new VelocityConstraintPoint[Settings.MaxManifoldPoints];
public Vector2 normal;
public Mat22 normalMass;
public Mat22 K;
public int indexA;
public int indexB;
public float invMassA, invMassB;
public float invIA, invIB;
public float friction;
public float restitution;
public float tangentSpeed;
public int pointCount;
public int contactIndex;
public ContactVelocityConstraint()
{
for (int i = 0; i < Settings.MaxManifoldPoints; i++)
{
points[i] = new VelocityConstraintPoint();
}
}
}
public class ContactSolver
{
public TimeStep _step;
public Position[] _positions;
public Velocity[] _velocities;
public ContactPositionConstraint[] _positionConstraints;
public ContactVelocityConstraint[] _velocityConstraints;
public Contact[] _contacts;
public int _count;
public void Reset(TimeStep step, int count, Contact[] contacts, Position[] positions, Velocity[] velocities, bool warmstarting = Settings.EnableWarmstarting)
{
_step = step;
_count = count;
_positions = positions;
_velocities = velocities;
_contacts = contacts;
// grow the array
if (_velocityConstraints == null || _velocityConstraints.Length < count)
{
_velocityConstraints = new ContactVelocityConstraint[count * 2];
_positionConstraints = new ContactPositionConstraint[count * 2];
for (int i = 0; i < _velocityConstraints.Length; i++)
{
_velocityConstraints[i] = new ContactVelocityConstraint();
}
for (int i = 0; i < _positionConstraints.Length; i++)
{
_positionConstraints[i] = new ContactPositionConstraint();
}
}
// Initialize position independent portions of the constraints.
for (int i = 0; i < _count; ++i)
{
Contact contact = contacts[i];
Fixture fixtureA = contact.FixtureA;
Fixture fixtureB = contact.FixtureB;
Shape shapeA = fixtureA.Shape;
Shape shapeB = fixtureB.Shape;
float radiusA = shapeA.Radius;
float radiusB = shapeB.Radius;
Body bodyA = fixtureA.Body;
Body bodyB = fixtureB.Body;
Manifold manifold = contact.Manifold;
int pointCount = manifold.PointCount;
Debug.Assert(pointCount > 0);
ContactVelocityConstraint vc = _velocityConstraints[i];
vc.friction = contact.Friction;
vc.restitution = contact.Restitution;
vc.tangentSpeed = contact.TangentSpeed;
vc.indexA = bodyA.IslandIndex;
vc.indexB = bodyB.IslandIndex;
vc.invMassA = bodyA._invMass;
vc.invMassB = bodyB._invMass;
vc.invIA = bodyA._invI;
vc.invIB = bodyB._invI;
vc.contactIndex = i;
vc.pointCount = pointCount;
vc.K.SetZero();
vc.normalMass.SetZero();
ContactPositionConstraint pc = _positionConstraints[i];
pc.indexA = bodyA.IslandIndex;
pc.indexB = bodyB.IslandIndex;
pc.invMassA = bodyA._invMass;
pc.invMassB = bodyB._invMass;
pc.localCenterA = bodyA._sweep.LocalCenter;
pc.localCenterB = bodyB._sweep.LocalCenter;
pc.invIA = bodyA._invI;
pc.invIB = bodyB._invI;
pc.localNormal = manifold.LocalNormal;
pc.localPoint = manifold.LocalPoint;
pc.pointCount = pointCount;
pc.radiusA = radiusA;
pc.radiusB = radiusB;
pc.type = manifold.Type;
for (int j = 0; j < pointCount; ++j)
{
ManifoldPoint cp = manifold.Points[j];
VelocityConstraintPoint vcp = vc.points[j];
if (Settings.EnableWarmstarting)
{
vcp.normalImpulse = _step.dtRatio * cp.NormalImpulse;
vcp.tangentImpulse = _step.dtRatio * cp.TangentImpulse;
}
else
{
vcp.normalImpulse = 0.0f;
vcp.tangentImpulse = 0.0f;
}
vcp.rA = Vector2.Zero;
vcp.rB = Vector2.Zero;
vcp.normalMass = 0.0f;
vcp.tangentMass = 0.0f;
vcp.velocityBias = 0.0f;
pc.localPoints[j] = cp.LocalPoint;
}
}
}
public void InitializeVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = _velocityConstraints[i];
ContactPositionConstraint pc = _positionConstraints[i];
float radiusA = pc.radiusA;
float radiusB = pc.radiusB;
Manifold manifold = _contacts[vc.contactIndex].Manifold;
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float mB = vc.invMassB;
float iA = vc.invIA;
float iB = vc.invIB;
Vector2 localCenterA = pc.localCenterA;
Vector2 localCenterB = pc.localCenterB;
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Debug.Assert(manifold.PointCount > 0);
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
Vector2 normal;
FixedArray2<Vector2> points;
WorldManifold.Initialize(ref manifold, ref xfA, radiusA, ref xfB, radiusB, out normal, out points);
vc.normal = normal;
int pointCount = vc.pointCount;
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.points[j];
vcp.rA = points[j] - cA;
vcp.rB = points[j] - cB;
float rnA = MathUtils.Cross(vcp.rA, vc.normal);
float rnB = MathUtils.Cross(vcp.rB, vc.normal);
float kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
vcp.normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f;
Vector2 tangent = MathUtils.Cross(vc.normal, 1.0f);
float rtA = MathUtils.Cross(vcp.rA, tangent);
float rtB = MathUtils.Cross(vcp.rB, tangent);
float kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB;
vcp.tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f;
// Setup a velocity bias for restitution.
vcp.velocityBias = 0.0f;
float vRel = Vector2.Dot(vc.normal, vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA));
if (vRel < -Settings.VelocityThreshold)
{
vcp.velocityBias = -vc.restitution * vRel;
}
}
// If we have two points, then prepare the block solver.
if (vc.pointCount == 2)
{
VelocityConstraintPoint vcp1 = vc.points[0];
VelocityConstraintPoint vcp2 = vc.points[1];
float rn1A = MathUtils.Cross(vcp1.rA, vc.normal);
float rn1B = MathUtils.Cross(vcp1.rB, vc.normal);
float rn2A = MathUtils.Cross(vcp2.rA, vc.normal);
float rn2B = MathUtils.Cross(vcp2.rB, vc.normal);
float k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B;
float k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B;
float k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B;
// Ensure a reasonable condition number.
const float k_maxConditionNumber = 1000.0f;
if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12))
{
// K is safe to invert.
vc.K.ex = new Vector2(k11, k12);
vc.K.ey = new Vector2(k12, k22);
vc.normalMass = vc.K.Inverse;
}
else
{
// The constraints are redundant, just use one.
// TODO_ERIN use deepest?
vc.pointCount = 1;
}
}
}
}
public void WarmStart()
{
// Warm start.
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = _velocityConstraints[i];
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float iA = vc.invIA;
float mB = vc.invMassB;
float iB = vc.invIB;
int pointCount = vc.pointCount;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Vector2 normal = vc.normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.points[j];
Vector2 P = vcp.normalImpulse * normal + vcp.tangentImpulse * tangent;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vA -= mA * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
vB += mB * P;
}
_velocities[indexA].v = vA;
_velocities[indexA].w = wA;
_velocities[indexB].v = vB;
_velocities[indexB].w = wB;
}
}
public void SolveVelocityConstraints()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = _velocityConstraints[i];
int indexA = vc.indexA;
int indexB = vc.indexB;
float mA = vc.invMassA;
float iA = vc.invIA;
float mB = vc.invMassB;
float iB = vc.invIB;
int pointCount = vc.pointCount;
Vector2 vA = _velocities[indexA].v;
float wA = _velocities[indexA].w;
Vector2 vB = _velocities[indexB].v;
float wB = _velocities[indexB].w;
Vector2 normal = vc.normal;
Vector2 tangent = MathUtils.Cross(normal, 1.0f);
float friction = vc.friction;
Debug.Assert(pointCount == 1 || pointCount == 2);
// Solve tangent constraints first because non-penetration is more important
// than friction.
for (int j = 0; j < pointCount; ++j)
{
VelocityConstraintPoint vcp = vc.points[j];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute tangent force
float vt = Vector2.Dot(dv, tangent) - vc.tangentSpeed;
float lambda = vcp.tangentMass * (-vt);
// b2Clamp the accumulated force
float maxFriction = friction * vcp.normalImpulse;
float newImpulse = MathUtils.Clamp(vcp.tangentImpulse + lambda, -maxFriction, maxFriction);
lambda = newImpulse - vcp.tangentImpulse;
vcp.tangentImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * tangent;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
// Solve normal constraints
if (vc.pointCount == 1)
{
VelocityConstraintPoint vcp = vc.points[0];
// Relative velocity at contact
Vector2 dv = vB + MathUtils.Cross(wB, vcp.rB) - vA - MathUtils.Cross(wA, vcp.rA);
// Compute normal impulse
float vn = Vector2.Dot(dv, normal);
float lambda = -vcp.normalMass * (vn - vcp.velocityBias);
// b2Clamp the accumulated impulse
float newImpulse = Math.Max(vcp.normalImpulse + lambda, 0.0f);
lambda = newImpulse - vcp.normalImpulse;
vcp.normalImpulse = newImpulse;
// Apply contact impulse
Vector2 P = lambda * normal;
vA -= mA * P;
wA -= iA * MathUtils.Cross(vcp.rA, P);
vB += mB * P;
wB += iB * MathUtils.Cross(vcp.rB, P);
}
else
{
// Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite).
// Build the mini LCP for this contact patch
//
// vn = A * x + b, vn >= 0, , vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2
//
// A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n )
// b = vn0 - velocityBias
//
// The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i
// implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases
// vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid
// solution that satisfies the problem is chosen.
//
// In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires
// that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i).
//
// Substitute:
//
// x = a + d
//
// a := old total impulse
// x := new total impulse
// d := incremental impulse
//
// For the current iteration we extend the formula for the incremental impulse
// to compute the new total impulse:
//
// vn = A * d + b
// = A * (x - a) + b
// = A * x + b - A * a
// = A * x + b'
// b' = b - A * a;
VelocityConstraintPoint cp1 = vc.points[0];
VelocityConstraintPoint cp2 = vc.points[1];
Vector2 a = new Vector2(cp1.normalImpulse, cp2.normalImpulse);
Debug.Assert(a.X >= 0.0f && a.Y >= 0.0f);
// Relative velocity at contact
Vector2 dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
Vector2 dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
float vn1 = Vector2.Dot(dv1, normal);
float vn2 = Vector2.Dot(dv2, normal);
Vector2 b = new Vector2();
b.X = vn1 - cp1.velocityBias;
b.Y = vn2 - cp2.velocityBias;
// Compute b'
b -= MathUtils.Mul(ref vc.K, a);
const float k_errorTol = 1e-3f;
//B2_NOT_USED(k_errorTol);
for (; ; )
{
//
// Case 1: vn = 0
//
// 0 = A * x + b'
//
// Solve for x:
//
// x = - inv(A) * b'
//
Vector2 x = -MathUtils.Mul(ref vc.normalMass, b);
if (x.X >= 0.0f && x.Y >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
vn2 = Vector2.Dot(dv2, normal);
b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 2: vn1 = 0 and x2 = 0
//
// 0 = a11 * x1 + a12 * 0 + b1'
// vn2 = a21 * x1 + a22 * 0 + b2'
//
x.X = -cp1.normalMass * b.X;
x.Y = 0.0f;
vn1 = 0.0f;
vn2 = vc.K.ex.Y * x.X + b.Y;
if (x.X >= 0.0f && vn2 >= 0.0f)
{
// Get the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv1 = vB + MathUtils.Cross(wB, cp1.rB) - vA - MathUtils.Cross(wA, cp1.rA);
// Compute normal velocity
vn1 = Vector2.Dot(dv1, normal);
b2Assert(b2Abs(vn1 - cp1.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 3: vn2 = 0 and x1 = 0
//
// vn1 = a11 * 0 + a12 * x2 + b1'
// 0 = a21 * 0 + a22 * x2 + b2'
//
x.X = 0.0f;
x.Y = -cp2.normalMass * b.Y;
vn1 = vc.K.ey.X * x.Y + b.X;
vn2 = 0.0f;
if (x.Y >= 0.0f && vn1 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
#if B2_DEBUG_SOLVER
// Postconditions
dv2 = vB + MathUtils.Cross(wB, cp2.rB) - vA - MathUtils.Cross(wA, cp2.rA);
// Compute normal velocity
vn2 = Vector2.Dot(dv2, normal);
b2Assert(b2Abs(vn2 - cp2.velocityBias) < k_errorTol);
#endif
break;
}
//
// Case 4: x1 = 0 and x2 = 0
//
// vn1 = b1
// vn2 = b2;
x.X = 0.0f;
x.Y = 0.0f;
vn1 = b.X;
vn2 = b.Y;
if (vn1 >= 0.0f && vn2 >= 0.0f)
{
// Resubstitute for the incremental impulse
Vector2 d = x - a;
// Apply incremental impulse
Vector2 P1 = d.X * normal;
Vector2 P2 = d.Y * normal;
vA -= mA * (P1 + P2);
wA -= iA * (MathUtils.Cross(cp1.rA, P1) + MathUtils.Cross(cp2.rA, P2));
vB += mB * (P1 + P2);
wB += iB * (MathUtils.Cross(cp1.rB, P1) + MathUtils.Cross(cp2.rB, P2));
// Accumulate
cp1.normalImpulse = x.X;
cp2.normalImpulse = x.Y;
break;
}
// No solution, give up. This is hit sometimes, but it doesn't seem to matter.
break;
}
}
_velocities[indexA].v = vA;
_velocities[indexA].w = wA;
_velocities[indexB].v = vB;
_velocities[indexB].w = wB;
}
}
public void StoreImpulses()
{
for (int i = 0; i < _count; ++i)
{
ContactVelocityConstraint vc = _velocityConstraints[i];
Manifold manifold = _contacts[vc.contactIndex].Manifold;
for (int j = 0; j < vc.pointCount; ++j)
{
ManifoldPoint point = manifold.Points[j];
point.NormalImpulse = vc.points[j].normalImpulse;
point.TangentImpulse = vc.points[j].tangentImpulse;
manifold.Points[j] = point;
}
_contacts[vc.contactIndex].Manifold = manifold;
}
}
public bool SolvePositionConstraints()
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.indexA;
int indexB = pc.indexB;
Vector2 localCenterA = pc.localCenterA;
float mA = pc.invMassA;
float iA = pc.invIA;
Vector2 localCenterB = pc.localCenterB;
float mB = pc.invMassB;
float iB = pc.invIB;
int pointCount = pc.pointCount;
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
Vector2 normal;
Vector2 point;
float separation;
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].c = cA;
_positions[indexA].a = aA;
_positions[indexB].c = cB;
_positions[indexB].a = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -3.0f * Settings.LinearSlop;
}
// Sequential position solver for position constraints.
public bool SolveTOIPositionConstraints(int toiIndexA, int toiIndexB)
{
float minSeparation = 0.0f;
for (int i = 0; i < _count; ++i)
{
ContactPositionConstraint pc = _positionConstraints[i];
int indexA = pc.indexA;
int indexB = pc.indexB;
Vector2 localCenterA = pc.localCenterA;
Vector2 localCenterB = pc.localCenterB;
int pointCount = pc.pointCount;
float mA = 0.0f;
float iA = 0.0f;
if (indexA == toiIndexA || indexA == toiIndexB)
{
mA = pc.invMassA;
iA = pc.invIA;
}
float mB = 0.0f;
float iB = 0.0f;
if (indexB == toiIndexA || indexB == toiIndexB)
{
mB = pc.invMassB;
iB = pc.invIB;
}
Vector2 cA = _positions[indexA].c;
float aA = _positions[indexA].a;
Vector2 cB = _positions[indexB].c;
float aB = _positions[indexB].a;
// Solve normal constraints
for (int j = 0; j < pointCount; ++j)
{
Transform xfA = new Transform();
Transform xfB = new Transform();
xfA.q.Set(aA);
xfB.q.Set(aB);
xfA.p = cA - MathUtils.Mul(xfA.q, localCenterA);
xfB.p = cB - MathUtils.Mul(xfB.q, localCenterB);
Vector2 normal;
Vector2 point;
float separation;
PositionSolverManifold.Initialize(pc, xfA, xfB, j, out normal, out point, out separation);
Vector2 rA = point - cA;
Vector2 rB = point - cB;
// Track max constraint error.
minSeparation = Math.Min(minSeparation, separation);
// Prevent large corrections and allow slop.
float C = MathUtils.Clamp(Settings.Baumgarte * (separation + Settings.LinearSlop), -Settings.MaxLinearCorrection, 0.0f);
// Compute the effective mass.
float rnA = MathUtils.Cross(rA, normal);
float rnB = MathUtils.Cross(rB, normal);
float K = mA + mB + iA * rnA * rnA + iB * rnB * rnB;
// Compute normal impulse
float impulse = K > 0.0f ? -C / K : 0.0f;
Vector2 P = impulse * normal;
cA -= mA * P;
aA -= iA * MathUtils.Cross(rA, P);
cB += mB * P;
aB += iB * MathUtils.Cross(rB, P);
}
_positions[indexA].c = cA;
_positions[indexA].a = aA;
_positions[indexB].c = cB;
_positions[indexB].a = aB;
}
// We can't expect minSpeparation >= -b2_linearSlop because we don't
// push the separation above -b2_linearSlop.
return minSeparation >= -1.5f * Settings.LinearSlop;
}
public static class WorldManifold
{
/// <summary>
/// Evaluate the manifold with supplied transforms. This assumes
/// modest motion from the original state. This does not change the
/// point count, impulses, etc. The radii must come from the Shapes
/// that generated the manifold.
/// </summary>
/// <param name="manifold">The manifold.</param>
/// <param name="xfA">The transform for A.</param>
/// <param name="radiusA">The radius for A.</param>
/// <param name="xfB">The transform for B.</param>
/// <param name="radiusB">The radius for B.</param>
/// <param name="normal">World vector pointing from A to B</param>
/// <param name="points">Torld contact point (point of intersection).</param>
public static void Initialize(ref Manifold manifold, ref Transform xfA, float radiusA, ref Transform xfB, float radiusB, out Vector2 normal, out FixedArray2<Vector2> points)
{
normal = Vector2.Zero;
points = new FixedArray2<Vector2>();
if (manifold.PointCount == 0)
{
return;
}
switch (manifold.Type)
{
case ManifoldType.Circles:
{
normal = new Vector2(1.0f, 0.0f);
Vector2 pointA = MathUtils.Mul(ref xfA, manifold.LocalPoint);
Vector2 pointB = MathUtils.Mul(ref xfB, manifold.Points[0].LocalPoint);
if (Vector2.DistanceSquared(pointA, pointB) > Settings.Epsilon * Settings.Epsilon)
{
normal = pointB - pointA;
normal.Normalize();
}
Vector2 cA = pointA + radiusA * normal;
Vector2 cB = pointB - radiusB * normal;
points[0] = 0.5f * (cA + cB);
}
break;
case ManifoldType.FaceA:
{
normal = MathUtils.Mul(xfA.q, manifold.LocalNormal);
Vector2 planePoint = MathUtils.Mul(ref xfA, manifold.LocalPoint);
for (int i = 0; i < manifold.PointCount; ++i)
{
Vector2 clipPoint = MathUtils.Mul(ref xfB, manifold.Points[i].LocalPoint);
Vector2 cA = clipPoint + (radiusA - Vector2.Dot(clipPoint - planePoint, normal)) * normal;
Vector2 cB = clipPoint - radiusB * normal;
points[i] = 0.5f * (cA + cB);
}
}
break;
case ManifoldType.FaceB:
{
normal = MathUtils.Mul(xfB.q, manifold.LocalNormal);
Vector2 planePoint = MathUtils.Mul(ref xfB, manifold.LocalPoint);
for (int i = 0; i < manifold.PointCount; ++i)
{
Vector2 clipPoint = MathUtils.Mul(ref xfA, manifold.Points[i].LocalPoint);
Vector2 cB = clipPoint + (radiusB - Vector2.Dot(clipPoint - planePoint, normal)) * normal;
Vector2 cA = clipPoint - radiusA * normal;
points[i] = 0.5f * (cA + cB);
}
// Ensure normal points from A to B.
normal = -normal;
}
break;
}
}
}
private static class PositionSolverManifold
{
public static void Initialize(ContactPositionConstraint pc, Transform xfA, Transform xfB, int index, out Vector2 normal, out Vector2 point, out float separation)
{
Debug.Assert(pc.pointCount > 0);
switch (pc.type)
{
case ManifoldType.Circles:
{
Vector2 pointA = MathUtils.Mul(ref xfA, pc.localPoint);
Vector2 pointB = MathUtils.Mul(ref xfB, pc.localPoints[0]);
normal = pointB - pointA;
normal.Normalize();
point = 0.5f * (pointA + pointB);
separation = Vector2.Dot(pointB - pointA, normal) - pc.radiusA - pc.radiusB;
}
break;
case ManifoldType.FaceA:
{
normal = MathUtils.Mul(xfA.q, pc.localNormal);
Vector2 planePoint = MathUtils.Mul(ref xfA, pc.localPoint);
Vector2 clipPoint = MathUtils.Mul(ref xfB, pc.localPoints[index]);
separation = Vector2.Dot(clipPoint - planePoint, normal) - pc.radiusA - pc.radiusB;
point = clipPoint;
}
break;
case ManifoldType.FaceB:
{
normal = MathUtils.Mul(xfB.q, pc.localNormal);
Vector2 planePoint = MathUtils.Mul(ref xfB, pc.localPoint);
Vector2 clipPoint = MathUtils.Mul(ref xfA, pc.localPoints[index]);
separation = Vector2.Dot(clipPoint - planePoint, normal) - pc.radiusA - pc.radiusB;
point = clipPoint;
// Ensure normal points from A to B
normal = -normal;
}
break;
default:
normal = Vector2.Zero;
point = Vector2.Zero;
separation = 0;
break;
}
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Razorvine.Pyro;
using Razorvine.Pyro.Serializer;
// ReSharper disable CheckNamespace
namespace Pyrolite.Tests.Pyro
{
public class SerializePyroTests
{
public SerializePyroTests()
{
Config.SERPENT_INDENT=true;
}
[Fact]
public void PyroClassesSerpent()
{
var ser = new SerpentSerializer();
var uri = new PyroURI("PYRO:something@localhost:4444");
var s = ser.serializeData(uri);
object x = ser.deserializeData(s);
Assert.Equal(uri, x);
var proxy = new PyroProxy(uri)
{
correlation_id = Guid.NewGuid(),
pyroHandshake = "apples",
pyroAttrs = new HashSet<string> {"attr1", "attr2"}
};
s = ser.serializeData(proxy);
x = ser.deserializeData(s);
PyroProxy proxy2 = (PyroProxy) x;
Assert.Equal(uri.host, proxy2.hostname);
Assert.Equal(uri.objectid, proxy2.objectid);
Assert.Equal(uri.port, proxy2.port);
Assert.Null(proxy2.correlation_id); // "correlation_id is not serialized on the proxy object"
Assert.Equal(proxy.pyroHandshake, proxy2.pyroHandshake);
Assert.Equal(2, proxy2.pyroAttrs.Count);
Assert.Equal(proxy.pyroAttrs, proxy2.pyroAttrs);
PyroException ex = new PyroException("error");
s = ser.serializeData(ex);
x = ser.deserializeData(s);
PyroException ex2 = (PyroException) x;
Assert.Equal("[PyroError] error", ex2.Message);
Assert.Null(ex._pyroTraceback);
// try another kind of pyro exception
s = Encoding.UTF8.GetBytes("{'attributes':{'tb': 'traceback', '_pyroTraceback': ['line1', 'line2']},'__exception__':True,'args':('hello',42),'__class__':'CommunicationError'}");
x = ser.deserializeData(s);
ex2 = (PyroException) x;
Assert.Equal("[CommunicationError] hello", ex2.Message);
Assert.Equal("traceback", ex2.Data["tb"]);
Assert.Equal("line1line2", ex2._pyroTraceback);
Assert.Equal("CommunicationError", ex2.PythonExceptionType);
}
[Fact]
public void TestPyroProxySerpent()
{
PyroURI uri = new PyroURI("PYRO:something@localhost:4444");
PyroProxy proxy = new PyroProxy(uri)
{
correlation_id = Guid.NewGuid(),
pyroHandshake = "apples",
pyroAttrs = new HashSet<string> {"attr1", "attr2"}
};
var data = PyroProxySerpent.ToSerpentDict(proxy);
Assert.Equal(2, data.Count);
Assert.Equal("Pyro5.client.Proxy", (string) data["__class__"]);
Assert.Equal(7, ((object[])data["state"]).Length);
PyroProxy proxy2 = (PyroProxy) PyroProxySerpent.FromSerpentDict(data);
Assert.Equal(proxy.objectid, proxy2.objectid);
Assert.Equal("apples", proxy2.pyroHandshake);
}
[Fact]
public void TestUnserpentProxy()
{
var data = Encoding.UTF8.GetBytes("# serpent utf-8 python3.2\n" +
"{'state':('PYRO:Pyro.NameServer@localhost:9090',(),('count','lookup','register','ping','list','remove'),(),0.0,'hello',0),'__class__':'Pyro5.client.Proxy'}");
SerpentSerializer ser = new SerpentSerializer();
PyroProxy p = (PyroProxy) ser.deserializeData(data);
Assert.Null(p.correlation_id);
Assert.Equal("Pyro.NameServer", p.objectid);
Assert.Equal("localhost", p.hostname);
Assert.Equal(9090, p.port);
Assert.Equal("hello", p.pyroHandshake);
Assert.Equal(0, p.pyroAttrs.Count);
Assert.Equal(0, p.pyroOneway.Count);
Assert.Equal(6, p.pyroMethods.Count);
var methods = new List<string> {"count", "list", "lookup", "ping", "register", "remove"};
Assert.Equal(methods, p.pyroMethods.OrderBy(m=>m).ToList());
}
[Fact]
public void TestBytes()
{
byte[] bytes = { 97, 98, 99, 100, 101, 102 }; // abcdef
var dict = new Dictionary<string, string> {{"data", "YWJjZGVm"}, {"encoding", "base64"}};
var bytes2 = SerpentSerializer.ToBytes(dict);
Assert.Equal(bytes, bytes2);
var hashtable = new Hashtable {{"data", "YWJjZGVm"}, {"encoding", "base64"}};
bytes2 = SerpentSerializer.ToBytes(hashtable);
Assert.Equal(bytes, bytes2);
try {
SerpentSerializer.ToBytes(12345);
Assert.True(false, "error expected");
} catch (ArgumentException) {
//
}
}
}
/// <summary>
/// Some tests about the peculiarities of the handshake
/// </summary>
public class HandshakeTests
{
class MetadataProxy : PyroProxy
{
public MetadataProxy() : base("test", 999, "object42")
{
}
public void TestMetadataHashtable(Hashtable table)
{
base._processMetadata(table);
}
public void TestMetadataDictionary(IDictionary dict)
{
base._processMetadata(dict);
}
public void TestMetadataGenericDict(IDictionary<object, object> dict)
{
base._processMetadata(dict);
}
}
[Fact]
public void TestHandshakeDicts()
{
var proxy = new MetadataProxy();
var hashtable = new Hashtable
{
{"methods", new object[] {"method1"}},
{"attrs", new List<object>() {"attr1"}},
{"oneway", new HashSet<object>() {"oneway1"}}
};
var dict = new SortedList
{
{"methods", new object[] {"method1"}},
{"attrs", new List<object>() {"attr1"}},
{"oneway", new HashSet<object>() {"oneway1"}}
};
var gdict = new Dictionary<object, object>
{
{"methods", new object[] {"method1"}},
{"attrs", new List<object>() {"attr1"}},
{"oneway", new HashSet<object>() {"oneway1"}}
};
var expectedMethods = new HashSet<string> {"method1"};
var expectedAttrs = new HashSet<string> {"attr1"};
var expectedOneway = new HashSet<string> {"oneway1"};
proxy.pyroMethods.Clear();
proxy.pyroAttrs.Clear();
proxy.pyroOneway.Clear();
proxy.TestMetadataHashtable(hashtable);
Assert.Equal(expectedMethods, proxy.pyroMethods);
Assert.Equal(expectedAttrs, proxy.pyroAttrs);
Assert.Equal(expectedOneway, proxy.pyroOneway);
proxy.pyroMethods.Clear();
proxy.pyroAttrs.Clear();
proxy.pyroOneway.Clear();
proxy.TestMetadataDictionary(dict);
Assert.Equal(expectedMethods, proxy.pyroMethods);
Assert.Equal(expectedAttrs, proxy.pyroAttrs);
Assert.Equal(expectedOneway, proxy.pyroOneway);
proxy.pyroMethods.Clear();
proxy.pyroAttrs.Clear();
proxy.pyroOneway.Clear();
proxy.TestMetadataDictionary(gdict);
Assert.Equal(expectedMethods, proxy.pyroMethods);
Assert.Equal(expectedAttrs, proxy.pyroAttrs);
Assert.Equal(expectedOneway, proxy.pyroOneway);
proxy.pyroMethods.Clear();
proxy.pyroAttrs.Clear();
proxy.pyroOneway.Clear();
proxy.TestMetadataGenericDict(gdict);
Assert.Equal(expectedMethods, proxy.pyroMethods);
Assert.Equal(expectedAttrs, proxy.pyroAttrs);
Assert.Equal(expectedOneway, proxy.pyroOneway);
}
}
/// <summary>
/// Miscellaneous tests.
/// </summary>
public class MiscellaneousTests
{
[Fact]
public void TestPyroExceptionType()
{
var ex=new PyroException("hello");
var type = ex.GetType();
var prop = type.GetProperty("PythonExceptionType");
Assert.NotNull(prop); // "pyro exception class has to have a property PythonExceptionType, it is used in constructor classes"
prop = type.GetProperty("_pyroTraceback");
Assert.NotNull(prop); // "pyro exception class has to have a property _pyroTraceback, it is used in constructor classes"
}
[Fact]
public void TestSerpentDictType()
{
Hashtable ht = new Hashtable {["key"] = "value"};
var ser = new SerpentSerializer();
var data = ser.serializeData(ht);
var result = ser.deserializeData(data);
Assert.IsAssignableFrom<Dictionary<object,object>>(result); // "in recent serpent versions, hashtables/dicts must be deserialized as IDictionary<object,object> rather than Hashtable"
var dict = (IDictionary<object,object>)result;
Assert.Equal("value", dict["key"]);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.VisualStudio.InteractiveWindow;
using Microsoft.VisualStudio.InteractiveWindow.Commands;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Microsoft.VisualStudio.Utilities;
using Microsoft.VisualStudioTools;
namespace Microsoft.PythonTools.Repl {
[Export(typeof(IInteractiveWindowCommand))]
[ContentType(PythonCoreConstants.ContentType)]
class LoadReplCommand : IInteractiveWindowCommand {
const string _commentPrefix = "%%";
public Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) {
var finder = new FileFinder(arguments);
var eval = window.GetPythonEvaluator();
if (eval != null) {
finder.Search(eval.Configuration.WorkingDirectory);
foreach (var p in eval.Configuration.SearchPaths) {
finder.Search(p);
}
}
finder.ThrowIfNotFound();
string commandPrefix = "$";
string lineBreak = window.TextView.Options.GetNewLineCharacter();
IEnumerable<string> lines = File.ReadLines(finder.Filename);
IEnumerable<string> submissions;
if (eval != null) {
submissions = ReplEditFilter.JoinToCompleteStatements(lines, eval.LanguageVersion).Where(CommentPrefixPredicate);
} else {
// v1 behavior, will probably never be hit, but if someone was developing their own IReplEvaluator
// and using this class it would be hit.
var submissionList = new List<string>();
var currentSubmission = new List<string>();
foreach (var line in lines) {
if (line.StartsWith(_commentPrefix)) {
continue;
}
if (line.StartsWith(commandPrefix)) {
AddSubmission(submissionList, currentSubmission, lineBreak);
submissionList.Add(line);
currentSubmission.Clear();
} else {
currentSubmission.Add(line);
}
}
AddSubmission(submissionList, currentSubmission, lineBreak);
submissions = submissionList;
}
window.SubmitAsync(submissions);
return ExecutionResult.Succeeded;
}
private static bool CommentPrefixPredicate(string input) {
return !input.StartsWith(_commentPrefix);
}
private static void AddSubmission(List<string> submissions, List<string> lines, string lineBreak) {
string submission = String.Join(lineBreak, lines);
// skip empty submissions:
if (submission.Length > 0) {
submissions.Add(submission);
}
}
public string Description {
get { return "Loads commands from file and executes until complete"; }
}
public string Command {
get { return "load"; }
}
public IEnumerable<ClassificationSpan> ClassifyArguments(ITextSnapshot snapshot, Span argumentsSpan, Span spanToClassify) {
yield break;
}
public string CommandLine {
get {
return "";
}
}
public IEnumerable<string> DetailedDescription {
get {
yield return Description;
}
}
public IEnumerable<KeyValuePair<string, string>> ParametersDescription {
get {
yield break;
}
}
public IEnumerable<string> Names {
get {
yield return Command;
}
}
class FileFinder {
private readonly string _baseName;
public FileFinder(string baseName) {
_baseName = (baseName ?? "").Trim(' ', '\"');
if (PathUtils.IsValidPath(_baseName) && Path.IsPathRooted(_baseName) && File.Exists(_baseName)) {
Found = true;
Filename = _baseName;
}
}
/// <summary>
/// Searches the specified path and changes <see cref="Found"/> to
/// true if the file exists. Returns true if the file was found in
/// the provided path.
/// </summary>
public bool Search(string path) {
if (Found) {
// File was found, but not in this path
return false;
}
if (!PathUtils.IsValidPath(path) || !Path.IsPathRooted(path)) {
return false;
}
var fullPath = PathUtils.GetAbsoluteFilePath(path, _baseName);
if (File.Exists(fullPath)) {
Found = true;
Filename = fullPath;
return true;
}
return false;
}
/// <summary>
/// Searches each path in the list of paths as if they had been
/// passed to <see cref="Search"/> individually.
/// </summary>
public bool SearchAll(string paths, char separator) {
if (Found) {
// File was found, but not in this path
return false;
}
if (string.IsNullOrEmpty(paths)) {
return false;
}
return SearchAll(paths.Split(separator));
}
/// <summary>
/// Searches each path in the sequence as if they had been passed
/// to <see cref="Search"/> individually.
/// </summary>
public bool SearchAll(IEnumerable<string> paths) {
if (Found) {
// File was found, but not in this path
return false;
}
if (paths == null) {
return false;
}
foreach (var path in paths) {
if (Search(path)) {
return true;
}
}
return false;
}
[DebuggerStepThrough, DebuggerHidden]
public void ThrowIfNotFound() {
if (!Found) {
throw new FileNotFoundException("Cannot find file.", _baseName);
}
}
public bool Found { get; private set; }
public string Filename { get; private set; }
}
}
}
| |
using MatterHackers.Agg.Transform;
using MatterHackers.Agg.VertexSource;
using MatterHackers.VectorMath;
//----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// C# Port port by: Lars Brubaker
// larsbrubaker@gmail.com
// Copyright (C) 2007
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
//
// classes spline_ctrl_impl, spline_ctrl
//
//----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
namespace MatterHackers.Agg.UI
{
//------------------------------------------------------------------------
// Class that can be used to create an interactive control to set up
// gamma arrays.
//------------------------------------------------------------------------
public class spline_ctrl : SimpleVertexSourceWidget
{
private RGBA_Bytes m_background_color;
private RGBA_Bytes m_border_color;
private RGBA_Bytes m_curve_color;
private RGBA_Bytes m_inactive_pnt_color;
private RGBA_Bytes m_active_pnt_color;
private int m_num_pnt;
private double[] m_xp = new double[32];
private double[] m_yp = new double[32];
private bspline m_spline = new bspline();
private double[] m_spline_values = new double[256];
private byte[] m_spline_values8 = new byte[256];
private double m_border_width;
private double m_border_extra;
private double m_curve_width;
private double m_point_size;
private double m_xs1;
private double m_ys1;
private double m_xs2;
private double m_ys2;
private VertexSource.PathStorage m_curve_pnt;
private Stroke m_curve_poly;
private VertexSource.Ellipse m_ellipse;
private int m_idx;
private int m_vertex;
private double[] m_vx = new double[32];
private double[] m_vy = new double[32];
private int m_active_pnt;
private int m_move_pnt;
private double m_pdx;
private double m_pdy;
private Transform.Affine m_mtx = Affine.NewIdentity();
public spline_ctrl(Vector2 location, Vector2 size, int num_pnt)
: base(location, false)
{
LocalBounds = new RectangleDouble(0, 0, size.x, size.y);
m_curve_pnt = new PathStorage();
m_curve_poly = new Stroke(m_curve_pnt);
m_ellipse = new Ellipse();
m_background_color = new RGBA_Bytes(1.0, 1.0, 0.9);
m_border_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_curve_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_inactive_pnt_color = new RGBA_Bytes(0.0, 0.0, 0.0);
m_active_pnt_color = new RGBA_Bytes(1.0, 0.0, 0.0);
m_num_pnt = (num_pnt);
m_border_width = (1.0);
m_border_extra = (0.0);
m_curve_width = (1.0);
m_point_size = (3.0);
m_curve_poly = new Stroke(m_curve_pnt);
m_idx = (0);
m_vertex = (0);
m_active_pnt = (-1);
m_move_pnt = (-1);
m_pdx = (0.0);
m_pdy = (0.0);
if (m_num_pnt < 4) m_num_pnt = 4;
if (m_num_pnt > 32) m_num_pnt = 32;
for (int i = 0; i < m_num_pnt; i++)
{
m_xp[i] = (double)(i) / (double)(m_num_pnt - 1);
m_yp[i] = 0.5;
}
calc_spline_box();
update_spline();
{
m_spline.init((int)m_num_pnt, m_xp, m_yp);
for (int i = 0; i < 256; i++)
{
m_spline_values[i] = m_spline.get((double)(i) / 255.0);
if (m_spline_values[i] < 0.0) m_spline_values[i] = 0.0;
if (m_spline_values[i] > 1.0) m_spline_values[i] = 1.0;
m_spline_values8[i] = (byte)(m_spline_values[i] * 255.0);
}
}
}
// Set other parameters
public void border_width(double t)
{
border_width(t, 0);
}
public void border_width(double t, double extra)
{
m_border_width = t;
m_border_extra = extra;
calc_spline_box();
LocalBounds = new RectangleDouble(-m_border_extra, -m_border_extra, Width + m_border_extra, Height + m_border_extra);
}
public void curve_width(double t)
{
m_curve_width = t;
}
public void point_size(double s)
{
m_point_size = s;
}
public override void OnMouseDown(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
int i;
for (i = 0; i < m_num_pnt; i++)
{
double xp = calc_xp(i);
double yp = calc_yp(i);
if (agg_math.calc_distance(x, y, xp, yp) <= m_point_size + 1)
{
m_pdx = xp - x;
m_pdy = yp - y;
m_active_pnt = m_move_pnt = (int)(i);
}
}
base.OnMouseDown(mouseEvent);
}
public override void OnMouseUp(MouseEventArgs mouseEvent)
{
if (m_move_pnt >= 0)
{
m_move_pnt = -1;
}
base.OnMouseUp(mouseEvent);
}
public override void OnMouseMove(MouseEventArgs mouseEvent)
{
double x = mouseEvent.X;
double y = mouseEvent.Y;
if (m_move_pnt >= 0)
{
double xp = x + m_pdx;
double yp = y + m_pdy;
set_xp((int)m_move_pnt, (xp - m_xs1) / (m_xs2 - m_xs1));
set_yp((int)m_move_pnt, (yp - m_ys1) / (m_ys2 - m_ys1));
update_spline();
Invalidate();
}
base.OnMouseMove(mouseEvent);
}
public override void OnKeyDown(KeyEventArgs keyEvent)
{
double kx = 0.0;
double ky = 0.0;
bool ret = false;
if (m_active_pnt >= 0)
{
kx = m_xp[m_active_pnt];
ky = m_yp[m_active_pnt];
if (keyEvent.KeyCode == Keys.Left) { kx -= 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Right) { kx += 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Down) { ky -= 0.001; ret = true; }
if (keyEvent.KeyCode == Keys.Up) { ky += 0.001; ret = true; }
}
if (ret)
{
set_xp((int)m_active_pnt, kx);
set_yp((int)m_active_pnt, ky);
update_spline();
keyEvent.Handled = true;
Invalidate();
}
base.OnKeyDown(keyEvent);
}
public void active_point(int i)
{
m_active_pnt = i;
}
public double[] spline()
{
return m_spline_values;
}
public byte[] spline8()
{
return m_spline_values8;
}
public double value(double x)
{
x = m_spline.get(x);
if (x < 0.0) x = 0.0;
if (x > 1.0) x = 1.0;
return x;
}
public void value(int idx, double y)
{
if (idx < m_num_pnt)
{
set_yp(idx, y);
}
}
public void point(int idx, double x, double y)
{
if (idx < m_num_pnt)
{
set_xp(idx, x);
set_yp(idx, y);
}
}
public void x(int idx, double x)
{
m_xp[idx] = x;
}
public void y(int idx, double y)
{
m_yp[idx] = y;
}
public double x(int idx)
{
return m_xp[idx];
}
public double y(int idx)
{
return m_yp[idx];
}
public void update_spline()
{
m_spline.init((int)m_num_pnt, m_xp, m_yp);
for (int i = 0; i < 256; i++)
{
m_spline_values[i] = m_spline.get((double)(i) / 255.0);
if (m_spline_values[i] < 0.0) m_spline_values[i] = 0.0;
if (m_spline_values[i] > 1.0) m_spline_values[i] = 1.0;
m_spline_values8[i] = (byte)(m_spline_values[i] * 255.0);
}
}
public override void OnDraw(Graphics2D graphics2D)
{
int index = 0;
rewind(index);
graphics2D.Render(this, m_background_color);
rewind(++index);
graphics2D.Render(this, m_border_color);
rewind(++index);
graphics2D.Render(this, m_curve_color);
rewind(++index);
graphics2D.Render(this, m_inactive_pnt_color);
rewind(++index);
graphics2D.Render(this, m_active_pnt_color);
base.OnDraw(graphics2D);
}
// Vertex soutce interface
public override int num_paths()
{
return 5;
}
public override IEnumerable<VertexData> Vertices()
{
throw new NotImplementedException();
}
public override void rewind(int idx)
{
m_idx = idx;
switch (idx)
{
default:
case 0: // Background
m_vertex = 0;
m_vx[0] = -m_border_extra;
m_vy[0] = -m_border_extra;
m_vx[1] = Width + m_border_extra;
m_vy[1] = -m_border_extra;
m_vx[2] = Width + m_border_extra;
m_vy[2] = Height + m_border_extra;
m_vx[3] = -m_border_extra;
m_vy[3] = Height + m_border_extra;
break;
case 1: // Border
m_vertex = 0;
m_vx[0] = 0;
m_vy[0] = 0;
m_vx[1] = Width - m_border_extra * 2;
m_vy[1] = 0;
m_vx[2] = Width - m_border_extra * 2;
m_vy[2] = Height - m_border_extra * 2;
m_vx[3] = 0;
m_vy[3] = Height - m_border_extra * 2;
m_vx[4] = +m_border_width;
m_vy[4] = +m_border_width;
m_vx[5] = +m_border_width;
m_vy[5] = Height - m_border_width - m_border_extra * 2;
m_vx[6] = Width - m_border_width - m_border_extra * 2;
m_vy[6] = Height - m_border_width - m_border_extra * 2;
m_vx[7] = Width - m_border_width - m_border_extra * 2;
m_vy[7] = +m_border_width;
break;
case 2: // Curve
calc_curve();
m_curve_poly.width(m_curve_width);
m_curve_poly.rewind(0);
break;
case 3: // Inactive points
m_curve_pnt.remove_all();
for (int i = 0; i < m_num_pnt; i++)
{
if (i != m_active_pnt)
{
m_ellipse.init(calc_xp(i), calc_yp(i),
m_point_size, m_point_size, 32);
m_curve_pnt.concat_path(m_ellipse);
}
}
m_curve_poly.rewind(0);
break;
case 4: // Active point
m_curve_pnt.remove_all();
if (m_active_pnt >= 0)
{
m_ellipse.init(calc_xp(m_active_pnt), calc_yp(m_active_pnt),
m_point_size, m_point_size, 32);
m_curve_pnt.concat_path(m_ellipse);
}
m_curve_poly.rewind(0);
break;
}
}
public override ShapePath.FlagsAndCommand vertex(out double x, out double y)
{
x = 0;
y = 0;
ShapePath.FlagsAndCommand cmd = ShapePath.FlagsAndCommand.CommandLineTo;
switch (m_idx)
{
case 0:
if (m_vertex == 0) cmd = ShapePath.FlagsAndCommand.CommandMoveTo;
if (m_vertex >= 4) cmd = ShapePath.FlagsAndCommand.CommandStop;
x = m_vx[m_vertex];
y = m_vy[m_vertex];
m_vertex++;
break;
case 1:
if (m_vertex == 0 || m_vertex == 4) cmd = ShapePath.FlagsAndCommand.CommandMoveTo;
if (m_vertex >= 8) cmd = ShapePath.FlagsAndCommand.CommandStop;
x = m_vx[m_vertex];
y = m_vy[m_vertex];
m_vertex++;
break;
case 2:
cmd = m_curve_poly.vertex(out x, out y);
break;
case 3:
case 4:
cmd = m_curve_pnt.vertex(out x, out y);
break;
default:
cmd = ShapePath.FlagsAndCommand.CommandStop;
break;
}
if (!ShapePath.is_stop(cmd))
{
//OriginRelativeParentTransform.transform(ref x, ref y);
}
return cmd;
}
private void calc_spline_box()
{
m_xs1 = LocalBounds.Left + m_border_width;
m_ys1 = LocalBounds.Bottom + m_border_width;
m_xs2 = LocalBounds.Right - m_border_width;
m_ys2 = LocalBounds.Top - m_border_width;
}
private void calc_curve()
{
int i;
m_curve_pnt.remove_all();
m_curve_pnt.MoveTo(m_xs1, m_ys1 + (m_ys2 - m_ys1) * m_spline_values[0]);
for (i = 1; i < 256; i++)
{
m_curve_pnt.LineTo(m_xs1 + (m_xs2 - m_xs1) * (double)(i) / 255.0,
m_ys1 + (m_ys2 - m_ys1) * m_spline_values[i]);
}
}
private double calc_xp(int idx)
{
return m_xs1 + (m_xs2 - m_xs1) * m_xp[idx];
}
private double calc_yp(int idx)
{
return m_ys1 + (m_ys2 - m_ys1) * m_yp[idx];
}
private void set_xp(int idx, double val)
{
if (val < 0.0) val = 0.0;
if (val > 1.0) val = 1.0;
if (idx == 0)
{
val = 0.0;
}
else if (idx == m_num_pnt - 1)
{
val = 1.0;
}
else
{
if (val < m_xp[idx - 1] + 0.001) val = m_xp[idx - 1] + 0.001;
if (val > m_xp[idx + 1] - 0.001) val = m_xp[idx + 1] - 0.001;
}
m_xp[idx] = val;
}
private void set_yp(int idx, double val)
{
if (val < 0.0) val = 0.0;
if (val > 1.0) val = 1.0;
m_yp[idx] = val;
}
// Set colors
public void background_color(RGBA_Bytes c)
{
m_background_color = c;
}
public void border_color(RGBA_Bytes c)
{
m_border_color = c;
}
public void curve_color(RGBA_Bytes c)
{
m_curve_color = c;
}
public void inactive_pnt_color(RGBA_Bytes c)
{
m_inactive_pnt_color = c;
}
public void active_pnt_color(RGBA_Bytes c)
{
m_active_pnt_color = c;
}
public override IColorType color(int i)
{
switch (i)
{
case 0:
return m_background_color;
case 1:
return m_border_color;
case 2:
return m_curve_color;
case 3:
return m_inactive_pnt_color;
case 4:
return m_active_pnt_color;
default:
throw new System.IndexOutOfRangeException("You asked for a color out of range.");
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gax = Google.Api.Gax;
using sys = System;
namespace Google.Ads.GoogleAds.V9.Resources
{
/// <summary>Resource name for the <c>CampaignFeed</c> resource.</summary>
public sealed partial class CampaignFeedName : gax::IResourceName, sys::IEquatable<CampaignFeedName>
{
/// <summary>The possible contents of <see cref="CampaignFeedName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_id}</c>.
/// </summary>
CustomerCampaignFeed = 1,
}
private static gax::PathTemplate s_customerCampaignFeed = new gax::PathTemplate("customers/{customer_id}/campaignFeeds/{campaign_id_feed_id}");
/// <summary>Creates a <see cref="CampaignFeedName"/> 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="CampaignFeedName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static CampaignFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new CampaignFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="CampaignFeedName"/> with the pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_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>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="CampaignFeedName"/> constructed from the provided ids.</returns>
public static CampaignFeedName FromCustomerCampaignFeed(string customerId, string campaignId, string feedId) =>
new CampaignFeedName(ResourceNameType.CustomerCampaignFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignFeedName"/> with pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_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>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignFeedName"/> with pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_id}</c>.
/// </returns>
public static string Format(string customerId, string campaignId, string feedId) =>
FormatCustomerCampaignFeed(customerId, campaignId, feedId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="CampaignFeedName"/> with pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_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>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="CampaignFeedName"/> with pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_id}</c>.
/// </returns>
public static string FormatCustomerCampaignFeed(string customerId, string campaignId, string feedId) =>
s_customerCampaignFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}");
/// <summary>Parses the given resource name string into a new <see cref="CampaignFeedName"/> 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}/campaignFeeds/{campaign_id}~{feed_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="CampaignFeedName"/> if successful.</returns>
public static CampaignFeedName Parse(string campaignFeedName) => Parse(campaignFeedName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="CampaignFeedName"/> 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}/campaignFeeds/{campaign_id}~{feed_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignFeedName">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="CampaignFeedName"/> if successful.</returns>
public static CampaignFeedName Parse(string campaignFeedName, bool allowUnparsed) =>
TryParse(campaignFeedName, allowUnparsed, out CampaignFeedName 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="CampaignFeedName"/> 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}/campaignFeeds/{campaign_id}~{feed_id}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="campaignFeedName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="CampaignFeedName"/>, 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 campaignFeedName, out CampaignFeedName result) =>
TryParse(campaignFeedName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="CampaignFeedName"/> 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}/campaignFeeds/{campaign_id}~{feed_id}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="campaignFeedName">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="CampaignFeedName"/>, 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 campaignFeedName, bool allowUnparsed, out CampaignFeedName result)
{
gax::GaxPreconditions.CheckNotNull(campaignFeedName, nameof(campaignFeedName));
gax::TemplatedResourceName resourceName;
if (s_customerCampaignFeed.TryParseName(campaignFeedName, out resourceName))
{
string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', });
if (split1 == null)
{
result = null;
return false;
}
result = FromCustomerCampaignFeed(resourceName[0], split1[0], split1[1]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(campaignFeedName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private static string[] ParseSplitHelper(string s, char[] separators)
{
string[] result = new string[separators.Length + 1];
int i0 = 0;
for (int i = 0; i <= separators.Length; i++)
{
int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length;
if (i1 < 0 || i1 == i0)
{
return null;
}
result[i] = s.Substring(i0, i1 - i0);
i0 = i1 + 1;
}
return result;
}
private CampaignFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string campaignId = null, string customerId = null, string feedId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
CampaignId = campaignId;
CustomerId = customerId;
FeedId = feedId;
}
/// <summary>
/// Constructs a new instance of a <see cref="CampaignFeedName"/> class from the component parts of pattern
/// <c>customers/{customer_id}/campaignFeeds/{campaign_id}~{feed_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>
/// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param>
public CampaignFeedName(string customerId, string campaignId, string feedId) : this(ResourceNameType.CustomerCampaignFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), campaignId: gax::GaxPreconditions.CheckNotNullOrEmpty(campaignId, nameof(campaignId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))
{
}
/// <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>
/// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string FeedId { 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.CustomerCampaignFeed: return s_customerCampaignFeed.Expand(CustomerId, $"{CampaignId}~{FeedId}");
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 CampaignFeedName);
/// <inheritdoc/>
public bool Equals(CampaignFeedName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(CampaignFeedName a, CampaignFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(CampaignFeedName a, CampaignFeedName b) => !(a == b);
}
public partial class CampaignFeed
{
/// <summary>
/// <see cref="CampaignFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property.
/// </summary>
internal CampaignFeedName ResourceNameAsCampaignFeedName
{
get => string.IsNullOrEmpty(ResourceName) ? null : CampaignFeedName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
/// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary>
internal FeedName FeedAsFeedName
{
get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true);
set => Feed = value?.ToString() ?? "";
}
/// <summary>
/// <see cref="CampaignName"/>-typed view over the <see cref="Campaign"/> resource name property.
/// </summary>
internal CampaignName CampaignAsCampaignName
{
get => string.IsNullOrEmpty(Campaign) ? null : CampaignName.Parse(Campaign, allowUnparsed: true);
set => Campaign = value?.ToString() ?? "";
}
}
}
| |
/*
* Copyright (c) Contributors, http://aurora-sim.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Aurora-Sim Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using Aurora.Framework;
using Aurora.Simulation.Base;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Region.Framework.Scenes.Components;
namespace Aurora.ScriptEngine.AuroraDotNetEngine
{
public class ScriptStateSave
{
private string m_componentName = "ScriptState";
private IComponentManager m_manager;
private ScriptEngine m_module;
public void Initialize(ScriptEngine module)
{
m_module = module;
m_manager = module.Worlds[0].RequestModuleInterface<IComponentManager>();
}
public void AddScene(IScene scene)
{
scene.AuroraEventManager.RegisterEventHandler("DeleteToInventory", AuroraEventManager_OnGenericEvent);
}
public void Close()
{
}
private object AuroraEventManager_OnGenericEvent(string FunctionName, object parameters)
{
if (FunctionName == "DeleteToInventory")
{
//Resave all the state saves for this object
ISceneEntity entity = (ISceneEntity)parameters;
foreach (ISceneChildEntity child in entity.ChildrenEntities())
{
m_module.SaveStateSaves(child.UUID);
}
}
return null;
}
public void SaveStateTo(ScriptData script)
{
SaveStateTo(script, false);
}
public void SaveStateTo(ScriptData script, bool forced)
{
SaveStateTo(script, forced, true);
}
public void SaveStateTo(ScriptData script, bool forced, bool saveBackup)
{
if (!forced)
{
if (script.Script == null)
return; //If it didn't compile correctly, this happens
if (!script.Script.NeedsStateSaved)
return; //If it doesn't need a state save, don't save one
}
if (script.Script != null)
script.Script.NeedsStateSaved = false;
if (saveBackup)
script.Part.ParentEntity.HasGroupChanged = true;
StateSave stateSave = new StateSave
{
State = script.State,
ItemID = script.ItemID,
Running = script.Running,
MinEventDelay = script.EventDelayTicks,
Disabled = script.Disabled,
UserInventoryID = script.UserInventoryItemID,
AssemblyName = script.AssemblyName,
Compiled = script.Compiled,
Source = script.Source
};
//Allow for the full path to be put down, not just the assembly name itself
if (script.InventoryItem != null)
{
stateSave.PermsGranter = script.InventoryItem.PermsGranter;
stateSave.PermsMask = script.InventoryItem.PermsMask;
}
else
{
stateSave.PermsGranter = UUID.Zero;
stateSave.PermsMask = 0;
}
stateSave.TargetOmegaWasSet = script.TargetOmegaWasSet;
//Vars
Dictionary<string, Object> vars = new Dictionary<string, object>();
if (script.Script != null)
vars = script.Script.GetStoreVars();
try
{
stateSave.Variables = WebUtils.BuildXmlResponse(vars);
}
catch
{
}
//Plugins
stateSave.Plugins = m_module.GetSerializationData(script.ItemID, script.Part.UUID);
CreateOSDMapForState(script, stateSave);
}
public void Deserialize(ScriptData instance, StateSave save)
{
instance.State = save.State;
instance.Running = save.Running;
instance.EventDelayTicks = (long)save.MinEventDelay;
instance.AssemblyName = save.AssemblyName;
instance.Disabled = save.Disabled;
instance.UserInventoryItemID = save.UserInventoryID;
instance.PluginData = save.Plugins;
m_module.CreateFromData(instance.Part.UUID, instance.ItemID, instance.Part.UUID,
instance.PluginData);
instance.Source = save.Source;
instance.InventoryItem.PermsGranter = save.PermsGranter;
instance.InventoryItem.PermsMask = save.PermsMask;
instance.TargetOmegaWasSet = save.TargetOmegaWasSet;
try
{
Dictionary<string, object> vars = WebUtils.ParseXmlResponse(save.Variables);
if (vars != null && vars.Count != 0 || instance.Script != null)
instance.Script.SetStoreVars(vars);
}
catch
{
}
}
public StateSave FindScriptStateSave(ScriptData script)
{
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
OSD o;
//If we have one for this item, deserialize it
if (!component.TryGetValue(script.ItemID.ToString(), out o))
{
if (!component.TryGetValue(script.InventoryItem.OldItemID.ToString(), out o))
{
if (!component.TryGetValue(script.InventoryItem.ItemID.ToString(), out o))
{
return null;
}
}
}
StateSave save = new StateSave();
save.FromOSD((OSDMap)o);
return save;
}
return null;
}
public void DeleteFrom(ScriptData script)
{
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
bool changed = false;
//if we did remove something, resave it
if (component.Remove(script.ItemID.ToString()))
changed = true;
if (component.Remove(script.InventoryItem.OldItemID.ToString()))
changed = true;
if (component.Remove(script.InventoryItem.ItemID.ToString()))
changed = true;
if (changed)
{
if (component.Count == 0)
m_manager.RemoveComponentState(script.Part.UUID, m_componentName);
else
m_manager.SetComponentState(script.Part, m_componentName, component);
script.Part.ParentEntity.HasGroupChanged = true;
}
}
}
public void DeleteFrom(ISceneChildEntity Part, UUID ItemID)
{
OSDMap component = m_manager.GetComponentState(Part, m_componentName) as OSDMap;
//Attempt to find the state saves we have
if (component != null)
{
//if we did remove something, resave it
if (component.Remove(ItemID.ToString()))
{
if (component.Count == 0)
m_manager.RemoveComponentState(Part.UUID, m_componentName);
else
m_manager.SetComponentState(Part, m_componentName, component);
Part.ParentEntity.HasGroupChanged = true;
}
}
}
private void CreateOSDMapForState(ScriptData script, StateSave save)
{
//Get any previous state saves from the component manager
OSDMap component = m_manager.GetComponentState(script.Part, m_componentName) as OSDMap;
if (component == null)
component = new OSDMap();
//Add our state to the list of all scripts in this object
component[script.ItemID.ToString()] = save.ToOSD();
//Now resave it
m_manager.SetComponentState(script.Part, m_componentName, component);
}
}
}
| |
//
// System.Diagnostics.Win32EventLog.cs
//
// Author:
// Gert Driesen <driesen@users.sourceforge.net>
//
// Copyright (C) 2006 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.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using Microsoft.Win32;
namespace System.Diagnostics
{
internal class Win32EventLog : EventLogImpl
{
private const int MESSAGE_NOT_FOUND = 317;
private ManualResetEvent _notifyResetEvent;
private IntPtr _readHandle;
private Thread _notifyThread;
private int _lastEntryWritten;
private bool _notifying;
public Win32EventLog (EventLog coreEventLog)
: base (coreEventLog)
{
}
public override void BeginInit ()
{
}
public override void Clear ()
{
int ret = PInvoke.ClearEventLog (ReadHandle, null);
if (ret != 1)
throw new Win32Exception (Marshal.GetLastWin32Error ());
}
public override void Close ()
{
if (_readHandle != IntPtr.Zero) {
CloseEventLog (_readHandle);
_readHandle = IntPtr.Zero;
}
}
public override void CreateEventSource (EventSourceCreationData sourceData)
{
using (RegistryKey eventLogKey = GetEventLogKey (sourceData.MachineName, true)) {
if (eventLogKey == null)
throw new InvalidOperationException ("EventLog registry key is missing.");
bool logKeyCreated = false;
RegistryKey logKey = null;
try {
logKey = eventLogKey.OpenSubKey (sourceData.LogName, true);
if (logKey == null) {
ValidateCustomerLogName (sourceData.LogName,
sourceData.MachineName);
logKey = eventLogKey.CreateSubKey (sourceData.LogName);
logKey.SetValue ("Sources", new string [] { sourceData.LogName,
sourceData.Source });
UpdateLogRegistry (logKey);
using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.LogName)) {
UpdateSourceRegistry (sourceKey, sourceData);
}
logKeyCreated = true;
}
if (sourceData.LogName != sourceData.Source) {
if (!logKeyCreated) {
string [] sources = (string []) logKey.GetValue ("Sources");
if (sources == null) {
logKey.SetValue ("Sources", new string [] { sourceData.LogName,
sourceData.Source });
} else {
bool found = false;
for (int i = 0; i < sources.Length; i++) {
if (sources [i] == sourceData.Source) {
found = true;
break;
}
}
if (!found) {
string [] newSources = new string [sources.Length + 1];
Array.Copy (sources, 0, newSources, 0, sources.Length);
newSources [sources.Length] = sourceData.Source;
logKey.SetValue ("Sources", newSources);
}
}
}
using (RegistryKey sourceKey = logKey.CreateSubKey (sourceData.Source)) {
UpdateSourceRegistry (sourceKey, sourceData);
}
}
} finally {
if (logKey != null)
logKey.Close ();
}
}
}
public override void Delete (string logName, string machineName)
{
using (RegistryKey eventLogKey = GetEventLogKey (machineName, true)) {
if (eventLogKey == null)
throw new InvalidOperationException ("The event log key does not exist.");
using (RegistryKey logKey = eventLogKey.OpenSubKey (logName, false)) {
if (logKey == null)
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Event Log '{0}'"
+ " does not exist on computer '{1}'.", logName,
machineName));
// remove all eventlog entries for specified log
CoreEventLog.Clear ();
// remove file holding event log entries
string file = (string) logKey.GetValue ("File");
if (file != null) {
try {
File.Delete (file);
} catch (Exception) {
// .NET seems to ignore failures here
}
}
}
eventLogKey.DeleteSubKeyTree (logName);
}
}
public override void DeleteEventSource (string source, string machineName)
{
using (RegistryKey logKey = FindLogKeyBySource (source, machineName, true)) {
if (logKey == null) {
throw new ArgumentException (string.Format (
CultureInfo.InvariantCulture, "The source '{0}' is not"
+ " registered on computer '{1}'.", source, machineName));
}
logKey.DeleteSubKeyTree (source);
string [] sources = (string []) logKey.GetValue ("Sources");
if (sources != null) {
ArrayList temp = new ArrayList ();
for (int i = 0; i < sources.Length; i++)
if (sources [i] != source)
temp.Add (sources [i]);
string [] newSources = new string [temp.Count];
temp.CopyTo (newSources, 0);
logKey.SetValue ("Sources", newSources);
}
}
}
public override void Dispose (bool disposing)
{
Close ();
}
public override void EndInit ()
{
}
public override bool Exists (string logName, string machineName)
{
using (RegistryKey logKey = FindLogKeyByName (logName, machineName, false)) {
return (logKey != null);
}
}
[MonoTODO] // ParameterResourceFile ??
protected override string FormatMessage (string source, uint messageID, string [] replacementStrings)
{
string formattedMessage = null;
string [] msgResDlls = GetMessageResourceDlls (source, "EventMessageFile");
for (int i = 0; i < msgResDlls.Length; i++) {
formattedMessage = FetchMessage (msgResDlls [i],
messageID, replacementStrings);
if (formattedMessage != null)
break;
}
return formattedMessage != null ? formattedMessage : string.Join (
", ", replacementStrings);
}
private string FormatCategory (string source, int category)
{
string formattedCategory = null;
string [] msgResDlls = GetMessageResourceDlls (source, "CategoryMessageFile");
for (int i = 0; i < msgResDlls.Length; i++) {
formattedCategory = FetchMessage (msgResDlls [i],
(uint) category, new string [0]);
if (formattedCategory != null)
break;
}
return formattedCategory != null ? formattedCategory : "(" +
category.ToString (CultureInfo.InvariantCulture) + ")";
}
protected override int GetEntryCount ()
{
int entryCount = 0;
int retVal = PInvoke.GetNumberOfEventLogRecords (ReadHandle, ref entryCount);
if (retVal != 1)
throw new Win32Exception (Marshal.GetLastWin32Error ());
return entryCount;
}
protected override EventLogEntry GetEntry (int index)
{
// http://msdn.microsoft.com/library/en-us/eventlog/base/readeventlog.asp
// http://msdn.microsoft.com/library/en-us/eventlog/base/eventlogrecord_str.asp
// http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html
index += OldestEventLogEntry;
int bytesRead = 0;
int minBufferNeeded = 0;
byte [] buffer = new byte [0x7ffff]; // according to MSDN this is the max size of the buffer
ReadEventLog (index, buffer, ref bytesRead, ref minBufferNeeded);
MemoryStream ms = new MemoryStream (buffer);
BinaryReader br = new BinaryReader (ms);
// skip first 8 bytes
br.ReadBytes (8);
int recordNumber = br.ReadInt32 (); // 8
int timeGeneratedSeconds = br.ReadInt32 (); // 12
int timeWrittenSeconds = br.ReadInt32 (); // 16
uint instanceID = br.ReadUInt32 ();
int eventID = EventLog.GetEventID (instanceID);
short eventType = br.ReadInt16 (); // 24
short numStrings = br.ReadInt16 (); ; // 26
short categoryNumber = br.ReadInt16 (); ; // 28
// skip reservedFlags
br.ReadInt16 (); // 30
// skip closingRecordNumber
br.ReadInt32 (); // 32
int stringOffset = br.ReadInt32 (); // 36
int userSidLength = br.ReadInt32 (); // 40
int userSidOffset = br.ReadInt32 (); // 44
int dataLength = br.ReadInt32 (); // 48
int dataOffset = br.ReadInt32 (); // 52
DateTime timeGenerated = new DateTime (1970, 1, 1).AddSeconds (
timeGeneratedSeconds);
DateTime timeWritten = new DateTime (1970, 1, 1).AddSeconds (
timeWrittenSeconds);
StringBuilder sb = new StringBuilder ();
while (br.PeekChar () != '\0')
sb.Append (br.ReadChar ());
br.ReadChar (); // skip the null-char
string sourceName = sb.ToString ();
sb.Length = 0;
while (br.PeekChar () != '\0')
sb.Append (br.ReadChar ());
br.ReadChar (); // skip the null-char
string machineName = sb.ToString ();
sb.Length = 0;
while (br.PeekChar () != '\0')
sb.Append (br.ReadChar ());
br.ReadChar (); // skip the null-char
string userName = null;
if (userSidLength != 0) {
// TODO: lazy init ?
ms.Position = userSidOffset;
byte [] sid = br.ReadBytes (userSidLength);
userName = LookupAccountSid (machineName, sid);
}
ms.Position = stringOffset;
string [] replacementStrings = new string [numStrings];
for (int i = 0; i < numStrings; i++) {
sb.Length = 0;
while (br.PeekChar () != '\0')
sb.Append (br.ReadChar ());
br.ReadChar (); // skip the null-char
replacementStrings [i] = sb.ToString ();
}
byte [] data = new byte [dataLength];
ms.Position = dataOffset;
br.Read (data, 0, dataLength);
// TODO: lazy fetch ??
string message = this.FormatMessage (sourceName, instanceID, replacementStrings);
string category = FormatCategory (sourceName, categoryNumber);
return new EventLogEntry (category, (short) categoryNumber, recordNumber,
eventID, sourceName, message, userName, machineName,
(EventLogEntryType) eventType, timeGenerated, timeWritten,
data, replacementStrings, instanceID);
}
[MonoTODO]
protected override string GetLogDisplayName ()
{
return CoreEventLog.Log;
}
protected override string [] GetLogNames (string machineName)
{
using (RegistryKey eventLogKey = GetEventLogKey (machineName, true)) {
if (eventLogKey == null)
return new string [0];
return eventLogKey.GetSubKeyNames ();
}
}
public override string LogNameFromSourceName (string source, string machineName)
{
using (RegistryKey logKey = FindLogKeyBySource (source, machineName, false)) {
if (logKey == null)
return string.Empty;
return GetLogName (logKey);
}
}
public override bool SourceExists (string source, string machineName)
{
RegistryKey logKey = FindLogKeyBySource (source, machineName, false);
if (logKey != null) {
logKey.Close ();
return true;
}
return false;
}
public override void WriteEntry (string [] replacementStrings, EventLogEntryType type, uint instanceID, short category, byte [] rawData)
{
IntPtr hEventLog = RegisterEventSource ();
try {
int ret = PInvoke.ReportEvent (hEventLog, (ushort) type,
(ushort) category, instanceID, IntPtr.Zero,
(ushort) replacementStrings.Length,
(uint) rawData.Length, replacementStrings, rawData);
if (ret != 1) {
throw new Win32Exception (Marshal.GetLastWin32Error ());
}
} finally {
DeregisterEventSource (hEventLog);
}
}
private static void UpdateLogRegistry (egistryKey logKey)
{
// TODO: write other Log values:
// - MaxSize
// - Retention
// - AutoBackupLogFiles
if (logKey.GetValue ("File") == null) {
string logName = GetLogName (logKey);
string file;
if (logName.Length > 8) {
file = logName.Substring (0, 8) + ".evt";
} else {
file = logName + ".evt";
}
string configPath = Path.Combine (Environment.GetFolderPath (
Environment.SpecialFolder.System), "config");
logKey.SetValue ("File", Path.Combine (configPath, file));
}
}
private static void UpdateSourceRegistry (RegistryKey sourceKey, EventSourceCreationData data)
{
if (data.CategoryCount > 0)
sourceKey.SetValue ("CategoryCount", data.CategoryCount);
if (data.CategoryResourceFile != null && data.CategoryResourceFile.Length > 0)
sourceKey.SetValue ("CategoryMessageFile", data.CategoryResourceFile);
if (data.MessageResourceFile != null && data.MessageResourceFile.Length > 0) {
sourceKey.SetValue ("EventMessageFile", data.MessageResourceFile);
} else {
// FIXME: write default once we have approval for shipping EventLogMessages.dll
}
if (data.ParameterResourceFile != null && data.ParameterResourceFile.Length > 0)
sourceKey.SetValue ("ParameterMessageFile", data.ParameterResourceFile);
}
private static string GetLogName (RegistryKey logKey)
{
string logName = logKey.Name;
return logName.Substring (logName.LastIndexOf ("\\") + 1);
}
private void ReadEventLog (int index, byte [] buffer, ref int bytesRead, ref int minBufferNeeded)
{
const int max_retries = 3;
// if the eventlog file changed since the handle was
// obtained, then we need to re-try multiple times
for (int i = 0; i < max_retries; i++) {
int ret = PInvoke.ReadEventLog (ReadHandle,
ReadFlags.Seek | ReadFlags.ForwardsRead,
index, buffer, buffer.Length, ref bytesRead,
ref minBufferNeeded);
if (ret != 1) {
int error = Marshal.GetLastWin32Error ();
if (i < (max_retries - 1)) {
CoreEventLog.Reset ();
} else {
throw new Win32Exception (error);
}
}
}
}
[MonoTODO ("Support remote machines")]
private static RegistryKey GetEventLogKey (string machineName, bool writable)
{
return Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Services\EventLog", writable);
}
private static RegistryKey FindSourceKeyByName (string source, string machineName, bool writable)
{
if (source == null || source.Length == 0)
return null;
RegistryKey eventLogKey = null;
try {
eventLogKey = GetEventLogKey (machineName, writable);
if (eventLogKey == null)
return null;
string [] subKeys = eventLogKey.GetSubKeyNames ();
for (int i = 0; i < subKeys.Length; i++) {
using (RegistryKey logKey = eventLogKey.OpenSubKey (subKeys [i], writable)) {
if (logKey == null)
break;
RegistryKey sourceKey = logKey.OpenSubKey (source, writable);
if (sourceKey != null)
return sourceKey;
}
}
return null;
} finally {
if (eventLogKey != null)
eventLogKey.Close ();
}
}
private static RegistryKey FindLogKeyByName (string logName, string machineName, bool writable)
{
using (RegistryKey eventLogKey = GetEventLogKey (machineName, writable)) {
if (eventLogKey == null) {
return null;
}
return eventLogKey.OpenSubKey (logName, writable);
}
}
private static RegistryKey FindLogKeyBySource (string source, string machineName, bool writable)
{
if (source == null || source.Length == 0)
return null;
RegistryKey eventLogKey = null;
try {
eventLogKey = GetEventLogKey (machineName, writable);
if (eventLogKey == null)
return null;
string [] subKeys = eventLogKey.GetSubKeyNames ();
for (int i = 0; i < subKeys.Length; i++) {
RegistryKey sourceKey = null;
try {
RegistryKey logKey = eventLogKey.OpenSubKey (subKeys [i], writable);
if (logKey != null) {
sourceKey = logKey.OpenSubKey (source, writable);
if (sourceKey != null)
return logKey;
}
} finally {
if (sourceKey != null)
sourceKey.Close ();
}
}
return null;
} finally {
if (eventLogKey != null)
eventLogKey.Close ();
}
}
private int OldestEventLogEntry {
get {
int oldestEventLogEntry = 0;
int ret = PInvoke.GetOldestEventLogRecord (ReadHandle, ref oldestEventLogEntry);
if (ret != 1) {
throw new Win32Exception (Marshal.GetLastWin32Error ());
}
return oldestEventLogEntry;
}
}
private void CloseEventLog (IntPtr hEventLog)
{
int ret = PInvoke.CloseEventLog (hEventLog);
if (ret != 1) {
throw new Win32Exception (Marshal.GetLastWin32Error ());
}
}
private void DeregisterEventSource (IntPtr hEventLog)
{
int ret = PInvoke.DeregisterEventSource (hEventLog);
if (ret != 1) {
throw new Win32Exception (Marshal.GetLastWin32Error ());
}
}
private static string LookupAccountSid (string machineName, byte [] sid)
{
// http://www.pinvoke.net/default.aspx/advapi32/LookupAccountSid.html
// http://msdn.microsoft.com/library/en-us/secauthz/security/lookupaccountsid.asp
StringBuilder name = new StringBuilder ();
uint cchName = (uint) name.Capacity;
StringBuilder referencedDomainName = new StringBuilder ();
uint cchReferencedDomainName = (uint) referencedDomainName.Capacity;
SidNameUse sidUse;
string accountName = null;
while (accountName == null) {
bool retOk = PInvoke.LookupAccountSid (machineName, sid, name, ref cchName,
referencedDomainName, ref cchReferencedDomainName,
out sidUse);
if (!retOk) {
int err = Marshal.GetLastWin32Error ();
if (err == PInvoke.ERROR_INSUFFICIENT_BUFFER) {
name.EnsureCapacity ((int) cchName);
referencedDomainName.EnsureCapacity ((int) cchReferencedDomainName);
} else {
// TODO: write warning ?
accountName = string.Empty;
}
} else {
accountName = string.Format ("{0}\\{1}", referencedDomainName.ToString (),
name.ToString ());
}
}
return accountName;
}
private static string FetchMessage (string msgDll, uint messageID, string [] replacementStrings)
{
// http://msdn.microsoft.com/library/en-us/debug/base/formatmessage.asp
// http://msdn.microsoft.com/msdnmag/issues/02/08/CQA/
// http://msdn.microsoft.com/netframework/programming/netcf/cffaq/default.aspx
IntPtr msgDllHandle = PInvoke.LoadLibraryEx (msgDll, IntPtr.Zero,
LoadFlags.LibraryAsDataFile);
if (msgDllHandle == IntPtr.Zero)
// TODO: write warning
return null;
IntPtr lpMsgBuf = IntPtr.Zero;
IntPtr [] arguments = new IntPtr [replacementStrings.Length];
try {
for (int i = 0; i < replacementStrings.Length; i++) {
arguments [i] = Marshal.StringToHGlobalAuto (
replacementStrings [i]);
}
int ret = PInvoke.FormatMessage (FormatMessageFlags.ArgumentArray |
FormatMessageFlags.FromHModule | FormatMessageFlags.AllocateBuffer,
msgDllHandle, messageID, 0, ref lpMsgBuf, 0, arguments);
if (ret != 0) {
string sRet = Marshal.PtrToStringAuto (lpMsgBuf);
lpMsgBuf = PInvoke.LocalFree (lpMsgBuf);
// remove trailing whitespace (CRLF)
return sRet.TrimEnd (null);
} else {
int err = Marshal.GetLastWin32Error ();
if (err == MESSAGE_NOT_FOUND) {
// do not consider this a failure (or even warning) as
// multiple message resource DLLs may have been configured
// and as such we just need to try the next library if
// the current one does not contain a message for this
// ID
} else {
// TODO: report warning
}
}
} finally {
// release unmanaged memory allocated for replacement strings
for (int i = 0; i < arguments.Length; i++) {
IntPtr argument = arguments [i];
if (argument != IntPtr.Zero)
Marshal.FreeHGlobal (argument);
}
PInvoke.FreeLibrary (msgDllHandle);
}
return null;
}
private string [] GetMessageResourceDlls (string source, string valueName)
{
// Some event sources (such as Userenv) have multiple message
// resource DLLs, delimited by a semicolon.
RegistryKey sourceKey = FindSourceKeyByName (source,
CoreEventLog.MachineName, false);
if (sourceKey != null) {
string value = sourceKey.GetValue (valueName) as string;
if (value != null) {
string [] msgResDlls = value.Split (';');
return msgResDlls;
}
}
return new string [0];
}
private IntPtr ReadHandle {
get {
if (_readHandle != IntPtr.Zero)
return _readHandle;
string logName = CoreEventLog.GetLogName ();
_readHandle = PInvoke.OpenEventLog (CoreEventLog.MachineName,
logName);
if (_readHandle == IntPtr.Zero)
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Event Log '{0}' on computer"
+ " '{1}' cannot be opened.", logName, CoreEventLog.MachineName),
new Win32Exception ());
return _readHandle;
}
}
private IntPtr RegisterEventSource ()
{
IntPtr hEventLog = PInvoke.RegisterEventSource (
CoreEventLog.MachineName, CoreEventLog.Source);
if (hEventLog == IntPtr.Zero) {
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Event source '{0}' on computer"
+ " '{1}' cannot be opened.", CoreEventLog.Source,
CoreEventLog.MachineName), new Win32Exception ());
}
return hEventLog;
}
public override void DisableNotification ()
{
if (_notifyResetEvent != null) {
_notifyResetEvent.Close ();
_notifyResetEvent = null;
}
if (_notifyThread != null) {
if (_notifyThread.ThreadState == System.Threading.ThreadState.Running)
_notifyThread.Abort ();
_notifyThread = null;
}
}
public override void EnableNotification ()
{
_notifyResetEvent = new ManualResetEvent (false);
_lastEntryWritten = OldestEventLogEntry + EntryCount;
if (PInvoke.NotifyChangeEventLog (ReadHandle, _notifyResetEvent.Handle) == 0)
throw new InvalidOperationException (string.Format (
CultureInfo.InvariantCulture, "Unable to receive notifications"
+ " for log '{0}' on computer '{1}'.", CoreEventLog.GetLogName (),
CoreEventLog.MachineName), new Win32Exception ());
_notifyThread = new Thread (new ThreadStart (NotifyEventThread));
_notifyThread.IsBackground = true;
_notifyThread.Start ();
}
private void NotifyEventThread ()
{
while (true) {
_notifyResetEvent.WaitOne ();
lock (this) {
// after a clear, we something get notified
// twice for the same entry
if (_notifying)
return;
_notifying = true;
}
try {
int oldest_entry = OldestEventLogEntry;
if (_lastEntryWritten < oldest_entry)
_lastEntryWritten = oldest_entry;
int current_entry = _lastEntryWritten - oldest_entry;
int last_entry = EntryCount + oldest_entry;
for (int i = current_entry; i < (last_entry - 1); i++) {
EventLogEntry entry = GetEntry (i);
CoreEventLog.OnEntryWritten (entry);
}
_lastEntryWritten = last_entry;
} finally {
lock (this)
_notifying = false;
}
}
}
public override OverflowAction OverflowAction {
get { throw new NotImplementedException (); }
}
public override int MinimumRetentionDays {
get { throw new NotImplementedException (); }
}
public override long MaximumKilobytes {
get { throw new NotImplementedException (); }
set { throw new NotImplementedException (); }
}
public override void ModifyOverflowPolicy (OverflowAction action, int retentionDays)
{
throw new NotImplementedException ();
}
public override void RegisterDisplayName (string resourceFile, long resourceId)
{
throw new NotImplementedException ();
}
private class PInvoke
{
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int ClearEventLog (IntPtr hEventLog, string lpBackupFileName);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int CloseEventLog (IntPtr hEventLog);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int DeregisterEventSource (IntPtr hEventLog);
[DllImport ("kernel32", CharSet=CharSet.Auto, SetLastError=true)]
public static extern int FormatMessage (FormatMessageFlags dwFlags, IntPtr lpSource, uint dwMessageId, int dwLanguageId, ref IntPtr lpBuffer, int nSize, IntPtr [] arguments);
[DllImport ("kernel32", SetLastError=true)]
public static extern bool FreeLibrary (IntPtr hModule);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int GetNumberOfEventLogRecords (IntPtr hEventLog, ref int NumberOfRecords);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int GetOldestEventLogRecord (IntPtr hEventLog, ref int OldestRecord);
[DllImport ("kernel32", SetLastError=true)]
public static extern IntPtr LoadLibraryEx (string lpFileName, IntPtr hFile, LoadFlags dwFlags);
[DllImport ("kernel32", SetLastError=true)]
public static extern IntPtr LocalFree (IntPtr hMem);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern bool LookupAccountSid (
string lpSystemName,
[MarshalAs (UnmanagedType.LPArray)] byte [] Sid,
StringBuilder lpName,
ref uint cchName,
StringBuilder ReferencedDomainName,
ref uint cchReferencedDomainName,
out SidNameUse peUse);
[DllImport ("advapi32.dll", SetLastError = true)]
public static extern int NotifyChangeEventLog (IntPtr hEventLog, IntPtr hEvent);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern IntPtr OpenEventLog (string machineName, string logName);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern IntPtr RegisterEventSource (string machineName, string sourceName);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int ReportEvent (IntPtr hHandle, ushort wType,
ushort wCategory, uint dwEventID, IntPtr sid, ushort wNumStrings,
uint dwDataSize, string [] lpStrings, byte [] lpRawData);
[DllImport ("advapi32.dll", SetLastError=true)]
public static extern int ReadEventLog (IntPtr hEventLog, ReadFlags dwReadFlags, int dwRecordOffset, byte [] buffer, int nNumberOfBytesToRead, ref int pnBytesRead, ref int pnMinNumberOfBytesNeeded);
public const int ERROR_INSUFFICIENT_BUFFER = 122;
public const int ERROR_EVENTLOG_FILE_CHANGED = 1503;
}
private enum ReadFlags
{
Sequential = 0x001,
Seek = 0x002,
ForwardsRead = 0x004,
BackwardsRead = 0x008
}
private enum LoadFlags: uint
{
LibraryAsDataFile = 0x002
}
[Flags]
private enum FormatMessageFlags
{
AllocateBuffer = 0x100,
IgnoreInserts = 0x200,
FromHModule = 0x0800,
FromSystem = 0x1000,
ArgumentArray = 0x2000
}
private enum SidNameUse
{
User = 1,
Group,
Domain,
lias,
WellKnownGroup,
DeletedAccount,
Invalid,
Unknown,
Computer
}
}
}
// http://msdn.microsoft.com/library/en-us/eventlog/base/eventlogrecord_str.asp:
//
// struct EVENTLOGRECORD {
// int Length;
// int Reserved;
// int RecordNumber;
// int TimeGenerated;
// int TimeWritten;
// int EventID;
// short EventType;
// short NumStrings;
// short EventCategory;
// short ReservedFlags;
// int ClosingRecordNumber;
// int StringOffset;
// int UserSidLength;
// int UserSidOffset;
// int DataLength;
// int DataOffset;
// }
//
// http://www.whitehats.ca/main/members/Malik/malik_eventlogs/malik_eventlogs.html
| |
//
// 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.Config;
namespace NLog.UnitTests.Targets.Wrappers
{
using System;
using System.Threading;
using NLog.Common;
using NLog.Targets;
using NLog.Targets.Wrappers;
using Xunit;
public class LimitingTargetWrapperTests : NLogTestBase
{
[Fact]
public void WriteMoreMessagesThanLimitOnlyWritesLimitMessages()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5'>
<target name='debug' type='Debug' layout='${message}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
for (int i = 0; i < 10; i++)
{
logger.Debug("message {0}", i);
}
//Should have only written 5 messages, since limit is 5.
AssertDebugCounter("debug", 5);
AssertDebugLastMessage("debug", "message 4");
}
[Fact]
public void WriteMessagesAfterLimitExpiredWritesMessages()
{
LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='5' interval='0:0:0:0.100'>
<target name='debug' type='Debug' layout='${message}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
var logger = LogManager.GetLogger("A");
for (int i = 0; i < 10; i++)
{
logger.Debug("message {0}", i);
}
//Wait for the interval to expire.
Thread.Sleep(100);
for (int i = 10; i < 20; i++)
{
logger.Debug("message {0}", i);
}
//Should have written 10 messages.
//5 from the first interval and 5 from the second.
AssertDebugCounter("debug", 10);
AssertDebugLastMessage("debug", "message 14");
}
[Fact]
public void WriteMessagesLessThanMessageLimitWritesToWrappedTarget()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100));
InitializeTargets(wrappedTarget, wrapper);
// Write limit number of messages should just write them to the wrappedTarget.
WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper);
Assert.Equal(5, wrappedTarget.WriteCount);
//Let the interval expire to start a new one.
Thread.Sleep(100);
// Write limit number of messages should just write them to the wrappedTarget.
var lastException = WriteNumberAsyncLogEventsStartingAt(5, 5, wrapper);
// We should have 10 messages (5 from first interval, 5 from second interval).
Assert.Equal(10, wrappedTarget.WriteCount);
Assert.Null(lastException);
}
[Fact]
public void WriteMoreMessagesThanMessageLimitDiscardsExcessMessages()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromHours(1));
InitializeTargets(wrappedTarget, wrapper);
// Write limit number of messages should just write them to the wrappedTarget.
var lastException = WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper);
Assert.Equal(5, wrappedTarget.WriteCount);
//Additional messages will be discarded, but InternalLogger will write to trace.
string internalLog = RunAndCaptureInternalLog(() =>
{
wrapper.WriteAsyncLogEvent(
new LogEventInfo(LogLevel.Debug, "test", $"Hello {5}").WithContinuation(ex => lastException = ex));
}, LogLevel.Trace);
Assert.Equal(5, wrappedTarget.WriteCount);
Assert.Contains("MessageLimit", internalLog);
Assert.Null(lastException);
}
[Fact]
public void WriteMessageAfterIntervalHasExpiredStartsNewInterval()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100));
InitializeTargets(wrappedTarget, wrapper);
Exception lastException = null;
wrapper.WriteAsyncLogEvent(
new LogEventInfo(LogLevel.Debug, "test", "first interval").WithContinuation(ex => lastException = ex));
//Let the interval expire.
Thread.Sleep(100);
//Writing a logEvent should start a new Interval. This should be written to InternalLogger.Debug.
string internalLog = RunAndCaptureInternalLog(() =>
{
// We can write 5 messages again since a new interval started.
lastException = WriteNumberAsyncLogEventsStartingAt(0, 5, wrapper);
}, LogLevel.Trace);
//We should have written 6 messages (1 in first interval and 5 in second interval).
Assert.Equal(6, wrappedTarget.WriteCount);
Assert.Contains("New interval", internalLog);
Assert.Null(lastException);
}
[Fact]
public void TestWritingMessagesOverMultipleIntervals()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget, 5, TimeSpan.FromMilliseconds(100));
InitializeTargets(wrappedTarget, wrapper);
Exception lastException = null;
lastException = WriteNumberAsyncLogEventsStartingAt(0, 10, wrapper);
//Let the interval expire.
Thread.Sleep(100);
Assert.Equal(5, wrappedTarget.WriteCount);
Assert.Equal("Hello 4", wrappedTarget.LastWrittenMessage);
Assert.Null(lastException);
lastException = WriteNumberAsyncLogEventsStartingAt(10, 10, wrapper);
//We should have 10 messages (5 from first, 5 from second interval).
Assert.Equal(10, wrappedTarget.WriteCount);
Assert.Equal("Hello 14", wrappedTarget.LastWrittenMessage);
Assert.Null(lastException);
//Let the interval expire.
Thread.Sleep(230);
lastException = WriteNumberAsyncLogEventsStartingAt(20, 10, wrapper);
//We should have 15 messages (5 from first, 5 from second, 5 from third interval).
Assert.Equal(15, wrappedTarget.WriteCount);
Assert.Equal("Hello 24", wrappedTarget.LastWrittenMessage);
Assert.Null(lastException);
//Let the interval expire.
Thread.Sleep(20);
lastException = WriteNumberAsyncLogEventsStartingAt(30, 10, wrapper);
//No more messages should be been written, since we are still in the third interval.
Assert.Equal(15, wrappedTarget.WriteCount);
Assert.Equal("Hello 24", wrappedTarget.LastWrittenMessage);
Assert.Null(lastException);
}
[Fact]
public void ConstructorWithNoParametersInitialisesDefaultsCorrectly()
{
LimitingTargetWrapper wrapper = new LimitingTargetWrapper();
Assert.Equal(1000, wrapper.MessageLimit);
Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval);
}
[Fact]
public void ConstructorWithTargetInitialisesDefaultsCorrectly()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget);
Assert.Equal(1000, wrapper.MessageLimit);
Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval);
}
[Fact]
public void ConstructorWithNameInitialisesDefaultsCorrectly()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper("Wrapper", wrappedTarget);
Assert.Equal(1000, wrapper.MessageLimit);
Assert.Equal(TimeSpan.FromHours(1), wrapper.Interval);
}
[Fact]
public void InitializeThrowsNLogConfigurationExceptionIfMessageLimitIsSetToZero()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {MessageLimit = 0};
wrappedTarget.Initialize(null);
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null));
LogManager.ThrowConfigExceptions = false;
}
[Fact]
public void InitializeThrowsNLogConfigurationExceptionIfMessageLimitIsSmallerZero()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {MessageLimit = -1};
wrappedTarget.Initialize(null);
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null));
LogManager.ThrowConfigExceptions = false;
}
[Fact]
public void InitializeThrowsNLogConfigurationExceptionIfIntervalIsSmallerZero()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {Interval = TimeSpan.MinValue};
wrappedTarget.Initialize(null);
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null));
LogManager.ThrowConfigExceptions = false;
}
[Fact]
public void InitializeThrowsNLogConfigurationExceptionIfIntervalIsZero()
{
MyTarget wrappedTarget = new MyTarget();
LimitingTargetWrapper wrapper = new LimitingTargetWrapper(wrappedTarget) {Interval = TimeSpan.Zero};
wrappedTarget.Initialize(null);
LogManager.ThrowConfigExceptions = true;
Assert.Throws<NLogConfigurationException>(() => wrapper.Initialize(null));
LogManager.ThrowConfigExceptions = false;
}
[Fact]
public void CreatingFromConfigSetsMessageLimitCorrectly()
{
LoggingConfiguration config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' messagelimit='50'>
<target name='debug' type='Debug' layout='${message}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
LimitingTargetWrapper limitingWrapper = (LimitingTargetWrapper) config.FindTargetByName("limiting");
DebugTarget debugTarget = (DebugTarget) config.FindTargetByName("debug");
Assert.NotNull(limitingWrapper);
Assert.NotNull(debugTarget);
Assert.Equal(50, limitingWrapper.MessageLimit);
Assert.Equal(TimeSpan.FromHours(1), limitingWrapper.Interval);
LogManager.Configuration = config;
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
}
[Fact]
public void CreatingFromConfigSetsIntervalCorrectly()
{
LoggingConfiguration config = XmlLoggingConfiguration.CreateFromXmlString(@"
<nlog>
<targets>
<wrapper-target name='limiting' type='LimitingWrapper' interval='1:2:5:00'>
<target name='debug' type='Debug' layout='${message}' />
</wrapper-target>
</targets>
<rules>
<logger name='*' level='Debug' writeTo='limiting' />
</rules>
</nlog>");
LimitingTargetWrapper limitingWrapper = (LimitingTargetWrapper)config.FindTargetByName("limiting");
DebugTarget debugTarget = (DebugTarget)config.FindTargetByName("debug");
Assert.NotNull(limitingWrapper);
Assert.NotNull(debugTarget);
Assert.Equal(1000, limitingWrapper.MessageLimit);
Assert.Equal(TimeSpan.FromDays(1)+TimeSpan.FromHours(2)+TimeSpan.FromMinutes(5), limitingWrapper.Interval);
LogManager.Configuration = config;
var logger = LogManager.GetLogger("A");
logger.Debug("a");
AssertDebugLastMessage("debug", "a");
}
private static void InitializeTargets(params Target[] targets)
{
foreach (Target target in targets)
{
target.Initialize(null);
}
}
private static Exception WriteNumberAsyncLogEventsStartingAt(int startIndex, int count, WrapperTargetBase wrapper)
{
Exception lastException = null;
for (int i = startIndex; i < startIndex + count; i++)
{
wrapper.WriteAsyncLogEvent(
new LogEventInfo(LogLevel.Debug, "test", $"Hello {i}").WithContinuation(ex => lastException = ex));
}
return lastException;
}
private class MyTarget : Target
{
public int WriteCount { get; private set; }
public string LastWrittenMessage { get; private set; }
protected override void Write(AsyncLogEventInfo logEvent)
{
base.Write(logEvent);
LastWrittenMessage = logEvent.LogEvent.FormattedMessage;
WriteCount++;
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
using Bitmask = System.UInt64;
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
namespace CleanSqlite
{
public partial class Sqlite3
{
/*
** 2009 November 25
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
** This file contains code used to insert the values of host parameters
** (aka "wildcards") into the SQL text output by sqlite3_trace().
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
//#include "vdbeInt.h"
#if !SQLITE_OMIT_TRACE
/*
** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
** bytes in this text up to but excluding the first character in
** a host parameter. If the text contains no host parameters, return
** the total number of bytes in the text.
*/
static int findNextHostParameter( string zSql, int iOffset, ref int pnToken )
{
int tokenType = 0;
int nTotal = 0;
int n;
pnToken = 0;
while ( iOffset < zSql.Length )
{
n = sqlite3GetToken( zSql, iOffset, ref tokenType );
Debug.Assert( n > 0 && tokenType != TK_ILLEGAL );
if ( tokenType == TK_VARIABLE )
{
pnToken = n;
break;
}
nTotal += n;
iOffset += n;// zSql += n;
}
return nTotal;
}
/*
** This function returns a pointer to a nul-terminated string in memory
** obtained from sqlite3DbMalloc(). If sqlite3.vdbeExecCnt is 1, then the
** string contains a copy of zRawSql but with host parameters expanded to
** their current bindings. Or, if sqlite3.vdbeExecCnt is greater than 1,
** then the returned string holds a copy of zRawSql with "-- " prepended
** to each line of text.
**
** The calling function is responsible for making sure the memory returned
** is eventually freed.
**
** ALGORITHM: Scan the input string looking for host parameters in any of
** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
** string literals, quoted identifier names, and comments. For text forms,
** the host parameter index is found by scanning the perpared
** statement for the corresponding OP_Variable opcode. Once the host
** parameter index is known, locate the value in p->aVar[]. Then render
** the value as a literal in place of the host parameter name.
*/
static string sqlite3VdbeExpandSql(
Vdbe p, /* The prepared statement being evaluated */
string zRawSql /* Raw text of the SQL statement */
)
{
sqlite3 db; /* The database connection */
int idx = 0; /* Index of a host parameter */
int nextIndex = 1; /* Index of next ? host parameter */
int n; /* Length of a token prefix */
int nToken = 0; /* Length of the parameter token */
int i; /* Loop counter */
Mem pVar; /* Value of a host parameter */
StrAccum _out = new StrAccum( 1000 ); /* Accumulate the _output here */
StringBuilder zBase = new StringBuilder( 100 ); /* Initial working space */
int izRawSql = 0;
db = p.db;
sqlite3StrAccumInit( _out, null, 100,
db.aLimit[SQLITE_LIMIT_LENGTH] );
_out.db = db;
if ( db.vdbeExecCnt > 1 )
{
while ( izRawSql < zRawSql.Length )
{
//string zStart = zRawSql;
while ( zRawSql[izRawSql++] != '\n' && izRawSql < zRawSql.Length )
;
sqlite3StrAccumAppend( _out, "-- ", 3 );
sqlite3StrAccumAppend( _out, zRawSql, (int)izRawSql );//zRawSql - zStart );
}
}
else
{
while ( izRawSql < zRawSql.Length )
{
n = findNextHostParameter( zRawSql, izRawSql, ref nToken );
Debug.Assert( n > 0 );
sqlite3StrAccumAppend( _out, zRawSql.Substring( izRawSql, n ), n );
izRawSql += n;
Debug.Assert( izRawSql < zRawSql.Length || nToken == 0 );
if ( nToken == 0 )
break;
if ( zRawSql[izRawSql] == '?' )
{
if ( nToken > 1 )
{
Debug.Assert( sqlite3Isdigit( zRawSql[izRawSql + 1] ) );
sqlite3GetInt32( zRawSql, izRawSql + 1, ref idx );
}
else
{
idx = nextIndex;
}
}
else
{
Debug.Assert( zRawSql[izRawSql] == ':' || zRawSql[izRawSql] == '$' || zRawSql[izRawSql] == '@' );
testcase( zRawSql[izRawSql] == ':' );
testcase( zRawSql[izRawSql] == '$' );
testcase( zRawSql[izRawSql] == '@' );
idx = sqlite3VdbeParameterIndex( p, zRawSql.Substring( izRawSql, nToken ), nToken );
Debug.Assert( idx > 0 );
}
izRawSql += nToken;
nextIndex = idx + 1;
Debug.Assert( idx > 0 && idx <= p.nVar );
pVar = p.aVar[idx - 1];
if ( ( pVar.flags & MEM_Null ) != 0 )
{
sqlite3StrAccumAppend( _out, "NULL", 4 );
}
else if ( ( pVar.flags & MEM_Int ) != 0 )
{
sqlite3XPrintf( _out, "%lld", pVar.u.i );
}
else if ( ( pVar.flags & MEM_Real ) != 0 )
{
sqlite3XPrintf( _out, "%!.15g", pVar.r );
}
else if ( ( pVar.flags & MEM_Str ) != 0 )
{
#if !SQLITE_OMIT_UTF16
u8 enc = ENC(db);
if( enc!=SQLITE_UTF8 ){
Mem utf8;
memset(&utf8, 0, sizeof(utf8));
utf8.db = db;
sqlite3VdbeMemSetStr(&utf8, pVar.z, pVar.n, enc, SQLITE_STATIC);
sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
sqlite3XPrintf(_out, "'%.*q'", utf8.n, utf8.z);
sqlite3VdbeMemRelease(&utf8);
}else
#endif
{
sqlite3XPrintf( _out, "'%.*q'", pVar.n, pVar.z );
}
}
else if ( ( pVar.flags & MEM_Zero ) != 0 )
{
sqlite3XPrintf( _out, "zeroblob(%d)", pVar.u.nZero );
}
else
{
Debug.Assert( ( pVar.flags & MEM_Blob ) != 0 );
sqlite3StrAccumAppend( _out, "x'", 2 );
for ( i = 0; i < pVar.n; i++ )
{
sqlite3XPrintf( _out, "%02x", pVar.zBLOB[i] & 0xff );
}
sqlite3StrAccumAppend( _out, "'", 1 );
}
}
}
return sqlite3StrAccumFinish( _out );
}
#endif //* #if !SQLITE_OMIT_TRACE */
}
}
| |
// 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.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Batch.Protocol
{
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// FileOperations operations.
/// </summary>
public partial interface IFileOperations
{
/// <summary>
/// Deletes the specified task file from the compute node where the
/// task ran.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to delete.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath
/// parameter represents a directory instead of a file, you can set
/// recursive to true to delete the directory and all of the files and
/// subdirectories in it. If recursive is false then the directory must
/// be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileDeleteFromTaskHeaders>> DeleteFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, bool? recursive = default(bool?), FileDeleteFromTaskOptions fileDeleteFromTaskOptions = default(FileDeleteFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to retrieve.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.IO.Stream,FileGetFromTaskHeaders>> GetFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, FileGetFromTaskOptions fileGetFromTaskOptions = default(FileGetFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the properties of the specified task file.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose file you want to get the properties of.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the properties of.
/// </param>
/// <param name='fileGetPropertiesFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileGetPropertiesFromTaskHeaders>> GetPropertiesFromTaskWithHttpMessagesAsync(string jobId, string taskId, string filePath, FileGetPropertiesFromTaskOptions fileGetPropertiesFromTaskOptions = default(FileGetPropertiesFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Deletes the specified task file from the compute node.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node from which you want to delete the file.
/// </param>
/// <param name='filePath'>
/// The path to the file that you want to delete.
/// </param>
/// <param name='recursive'>
/// Whether to delete children of a directory. If the filePath
/// parameter represents a directory instead of a file, you can set
/// recursive to true to delete the directory and all of the files and
/// subdirectories in it. If recursive is false then the directory must
/// be empty or deletion will fail.
/// </param>
/// <param name='fileDeleteFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileDeleteFromComputeNodeHeaders>> DeleteFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, bool? recursive = default(bool?), FileDeleteFromComputeNodeOptions fileDeleteFromComputeNodeOptions = default(FileDeleteFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Returns the content of the specified task file.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the task file that you want to get the content of.
/// </param>
/// <param name='fileGetFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<System.IO.Stream,FileGetFromComputeNodeHeaders>> GetFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, FileGetFromComputeNodeOptions fileGetFromComputeNodeOptions = default(FileGetFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Gets the properties of the specified compute node file.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node that contains the file.
/// </param>
/// <param name='filePath'>
/// The path to the compute node file that you want to get the
/// properties of.
/// </param>
/// <param name='fileGetPropertiesFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationHeaderResponse<FileGetPropertiesFromComputeNodeHeaders>> GetPropertiesFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, string filePath, FileGetPropertiesFromComputeNodeOptions fileGetPropertiesFromComputeNodeOptions = default(FileGetPropertiesFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='jobId'>
/// The ID of the job that contains the task.
/// </param>
/// <param name='taskId'>
/// The ID of the task whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory. This parameter can be used
/// in combination with the filter parameter to list specific type of
/// files.
/// </param>
/// <param name='fileListFromTaskOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromTaskHeaders>> ListFromTaskWithHttpMessagesAsync(string jobId, string taskId, bool? recursive = default(bool?), FileListFromTaskOptions fileListFromTaskOptions = default(FileListFromTaskOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified compute
/// node.
/// </summary>
/// <param name='poolId'>
/// The ID of the pool that contains the compute node.
/// </param>
/// <param name='nodeId'>
/// The ID of the compute node whose files you want to list.
/// </param>
/// <param name='recursive'>
/// Whether to list children of a directory.
/// </param>
/// <param name='fileListFromComputeNodeOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeWithHttpMessagesAsync(string poolId, string nodeId, bool? recursive = default(bool?), FileListFromComputeNodeOptions fileListFromComputeNodeOptions = default(FileListFromComputeNodeOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists the files in a task's directory on its compute node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromTaskNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromTaskHeaders>> ListFromTaskNextWithHttpMessagesAsync(string nextPageLink, FileListFromTaskNextOptions fileListFromTaskNextOptions = default(FileListFromTaskNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
/// <summary>
/// Lists all of the files in task directories on the specified compute
/// node.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='fileListFromComputeNodeNextOptions'>
/// Additional parameters for the operation
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="BatchErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<NodeFile>,FileListFromComputeNodeHeaders>> ListFromComputeNodeNextWithHttpMessagesAsync(string nextPageLink, FileListFromComputeNodeNextOptions fileListFromComputeNodeNextOptions = default(FileListFromComputeNodeNextOptions), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken));
}
}
| |
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
namespace MassTransit.Util
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
public abstract class ExpressionVisitor
{
protected virtual Expression Visit(Expression exp)
{
if (exp == null)
return exp;
switch (exp.NodeType)
{
case ExpressionType.Negate:
case ExpressionType.NegateChecked:
case ExpressionType.Not:
case ExpressionType.Convert:
case ExpressionType.ConvertChecked:
case ExpressionType.ArrayLength:
case ExpressionType.Quote:
case ExpressionType.TypeAs:
return VisitUnary((UnaryExpression) exp);
case ExpressionType.Add:
case ExpressionType.AddChecked:
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
case ExpressionType.Divide:
case ExpressionType.Modulo:
case ExpressionType.And:
case ExpressionType.AndAlso:
case ExpressionType.Or:
case ExpressionType.OrElse:
case ExpressionType.LessThan:
case ExpressionType.LessThanOrEqual:
case ExpressionType.GreaterThan:
case ExpressionType.GreaterThanOrEqual:
case ExpressionType.Equal:
case ExpressionType.NotEqual:
case ExpressionType.Coalesce:
case ExpressionType.ArrayIndex:
case ExpressionType.RightShift:
case ExpressionType.LeftShift:
case ExpressionType.ExclusiveOr:
return VisitBinary((BinaryExpression) exp);
case ExpressionType.TypeIs:
return VisitTypeIs((TypeBinaryExpression) exp);
case ExpressionType.Conditional:
return VisitConditional((ConditionalExpression) exp);
case ExpressionType.Constant:
return VisitConstant((ConstantExpression) exp);
case ExpressionType.Parameter:
return VisitParameter((ParameterExpression) exp);
case ExpressionType.MemberAccess:
return VisitMemberAccess((MemberExpression) exp);
case ExpressionType.Call:
return VisitMethodCall((MethodCallExpression) exp);
case ExpressionType.Lambda:
return VisitLambda((LambdaExpression) exp);
case ExpressionType.New:
return VisitNew((NewExpression) exp);
case ExpressionType.NewArrayInit:
case ExpressionType.NewArrayBounds:
return VisitNewArray((NewArrayExpression) exp);
case ExpressionType.Invoke:
return VisitInvocation((InvocationExpression) exp);
case ExpressionType.MemberInit:
return VisitMemberInit((MemberInitExpression) exp);
case ExpressionType.ListInit:
return VisitListInit((ListInitExpression) exp);
default:
throw new Exception(string.Format("Unhandled expression type: '{0}'", exp.NodeType));
}
}
protected virtual MemberBinding VisitBinding(MemberBinding binding)
{
switch (binding.BindingType)
{
case MemberBindingType.Assignment:
return VisitMemberAssignment((MemberAssignment) binding);
case MemberBindingType.MemberBinding:
return VisitMemberMemberBinding((MemberMemberBinding) binding);
case MemberBindingType.ListBinding:
return VisitMemberListBinding((MemberListBinding) binding);
default:
throw new Exception(string.Format("Unhandled binding type '{0}'", binding.BindingType));
}
}
protected virtual ElementInit VisitElementInitializer(ElementInit initializer)
{
ReadOnlyCollection<Expression> arguments = VisitExpressionList(initializer.Arguments);
if (arguments != initializer.Arguments)
{
return Expression.ElementInit(initializer.AddMethod, arguments);
}
return initializer;
}
protected virtual Expression VisitUnary(UnaryExpression u)
{
Expression operand = Visit(u.Operand);
if (operand != u.Operand)
{
return Expression.MakeUnary(u.NodeType, operand, u.Type, u.Method);
}
return u;
}
protected virtual Expression VisitBinary(BinaryExpression b)
{
Expression left = Visit(b.Left);
Expression right = Visit(b.Right);
Expression conversion = Visit(b.Conversion);
if (left != b.Left || right != b.Right || conversion != b.Conversion)
{
if (b.NodeType == ExpressionType.Coalesce && b.Conversion != null)
return Expression.Coalesce(left, right, conversion as LambdaExpression);
return Expression.MakeBinary(b.NodeType, left, right, b.IsLiftedToNull, b.Method);
}
return b;
}
protected virtual Expression VisitTypeIs(TypeBinaryExpression b)
{
Expression expr = Visit(b.Expression);
if (expr != b.Expression)
{
return Expression.TypeIs(expr, b.TypeOperand);
}
return b;
}
protected virtual Expression VisitConstant(ConstantExpression c)
{
return c;
}
protected virtual Expression VisitConditional(ConditionalExpression c)
{
Expression test = Visit(c.Test);
Expression ifTrue = Visit(c.IfTrue);
Expression ifFalse = Visit(c.IfFalse);
if (test != c.Test || ifTrue != c.IfTrue || ifFalse != c.IfFalse)
{
return Expression.Condition(test, ifTrue, ifFalse);
}
return c;
}
protected virtual Expression VisitParameter(ParameterExpression p)
{
return p;
}
protected virtual Expression VisitMemberAccess(MemberExpression m)
{
Expression exp = Visit(m.Expression);
if (exp != m.Expression)
{
return Expression.MakeMemberAccess(exp, m.Member);
}
return m;
}
protected virtual Expression VisitMethodCall(MethodCallExpression m)
{
Expression obj = Visit(m.Object);
IEnumerable<Expression> args = VisitExpressionList(m.Arguments);
if (obj != m.Object || args != m.Arguments)
{
return Expression.Call(obj, m.Method, args);
}
return m;
}
protected virtual ReadOnlyCollection<Expression> VisitExpressionList(ReadOnlyCollection<Expression> original)
{
List<Expression> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
Expression p = Visit(original[i]);
if (list != null)
{
list.Add(p);
}
else if (p != original[i])
{
list = new List<Expression>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(p);
}
}
if (list != null)
{
return list.AsReadOnly();
}
return original;
}
protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment assignment)
{
Expression e = Visit(assignment.Expression);
if (e != assignment.Expression)
{
return Expression.Bind(assignment.Member, e);
}
return assignment;
}
protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding binding)
{
IEnumerable<MemberBinding> bindings = VisitBindingList(binding.Bindings);
if (bindings != binding.Bindings)
{
return Expression.MemberBind(binding.Member, bindings);
}
return binding;
}
protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding binding)
{
IEnumerable<ElementInit> initializers = VisitElementInitializerList(binding.Initializers);
if (initializers != binding.Initializers)
{
return Expression.ListBind(binding.Member, initializers);
}
return binding;
}
protected virtual IEnumerable<MemberBinding> VisitBindingList(ReadOnlyCollection<MemberBinding> original)
{
List<MemberBinding> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
MemberBinding b = VisitBinding(original[i]);
if (list != null)
{
list.Add(b);
}
else if (b != original[i])
{
list = new List<MemberBinding>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(b);
}
}
if (list != null)
return list;
return original;
}
protected virtual IEnumerable<ElementInit> VisitElementInitializerList(ReadOnlyCollection<ElementInit> original)
{
List<ElementInit> list = null;
for (int i = 0, n = original.Count; i < n; i++)
{
ElementInit init = VisitElementInitializer(original[i]);
if (list != null)
{
list.Add(init);
}
else if (init != original[i])
{
list = new List<ElementInit>(n);
for (int j = 0; j < i; j++)
{
list.Add(original[j]);
}
list.Add(init);
}
}
if (list != null)
return list;
return original;
}
protected virtual Expression VisitLambda(LambdaExpression lambda)
{
Expression body = Visit(lambda.Body);
if (body != lambda.Body)
{
return Expression.Lambda(lambda.Type, body, lambda.Parameters);
}
return lambda;
}
protected virtual NewExpression VisitNew(NewExpression nex)
{
IEnumerable<Expression> args = VisitExpressionList(nex.Arguments);
if (args != nex.Arguments)
{
if (nex.Members != null)
return Expression.New(nex.Constructor, args, nex.Members);
return Expression.New(nex.Constructor, args);
}
return nex;
}
protected virtual Expression VisitMemberInit(MemberInitExpression init)
{
NewExpression n = VisitNew(init.NewExpression);
IEnumerable<MemberBinding> bindings = VisitBindingList(init.Bindings);
if (n != init.NewExpression || bindings != init.Bindings)
{
return Expression.MemberInit(n, bindings);
}
return init;
}
protected virtual Expression VisitListInit(ListInitExpression init)
{
NewExpression n = VisitNew(init.NewExpression);
IEnumerable<ElementInit> initializers = VisitElementInitializerList(init.Initializers);
if (n != init.NewExpression || initializers != init.Initializers)
{
return Expression.ListInit(n, initializers);
}
return init;
}
protected virtual Expression VisitNewArray(NewArrayExpression na)
{
IEnumerable<Expression> exprs = VisitExpressionList(na.Expressions);
if (exprs != na.Expressions)
{
if (na.NodeType == ExpressionType.NewArrayInit)
{
return Expression.NewArrayInit(na.Type.GetElementType(), exprs);
}
return Expression.NewArrayBounds(na.Type.GetElementType(), exprs);
}
return na;
}
protected virtual Expression VisitInvocation(InvocationExpression iv)
{
IEnumerable<Expression> args = VisitExpressionList(iv.Arguments);
Expression expr = Visit(iv.Expression);
if (args != iv.Arguments || expr != iv.Expression)
{
return Expression.Invoke(expr, args);
}
return iv;
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace Community.CsharpSqlite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2005 February 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains C code routines that used to generate VDBE code
** that implements the ALTER TABLE command.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** The code in this file only exists if we are not omitting the
** ALTER TABLE logic from the build.
*/
#if !SQLITE_OMIT_ALTERTABLE
/*
** This function is used by SQL generated to implement the
** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
** CREATE INDEX command. The second is a table name. The table name in
** the CREATE TABLE or CREATE INDEX statement is replaced with the third
** argument and the result returned. Examples:
**
** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
** . 'CREATE TABLE def(a, b, c)'
**
** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
** . 'CREATE INDEX i ON def(a, b, c)'
*/
static void renameTableFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string bResult = sqlite3_value_text( argv[0] );
string zSql = bResult == null ? "" : bResult;
string zTableName = sqlite3_value_text( argv[1] );
int token = 0;
Token tname = new Token();
int zCsr = 0;
int zLoc = 0;
int len = 0;
string zRet;
sqlite3 db = sqlite3_context_db_handle( context );
UNUSED_PARAMETER( NotUsed );
/* The principle used to locate the table name in the CREATE TABLE
** statement is that the table name is the first non-space token that
** is immediately followed by a TK_LP or TK_USING token.
*/
if ( zSql != "" )
{
do
{
if ( zCsr == zSql.Length )
{
/* Ran out of input before finding an opening bracket. Return NULL. */
return;
}
/* Store the token that zCsr points to in tname. */
zLoc = zCsr;
tname.z = zSql.Substring( zCsr );//(char*)zCsr;
tname.n = len;
/* Advance zCsr to the next token. Store that token type in 'token',
** and its length in 'len' (to be used next iteration of this loop).
*/
do
{
zCsr += len;
len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token );
} while ( token == TK_SPACE );
Debug.Assert( len > 0 );
} while ( token != TK_LP && token != TK_USING );
zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ),
zTableName, zSql.Substring( zLoc + tname.n ) );
sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC );
}
}
/*
** This C function implements an SQL user function that is used by SQL code
** generated by the ALTER TABLE ... RENAME command to modify the definition
** of any foreign key constraints that use the table being renamed as the
** parent table. It is passed three arguments:
**
** 1) The complete text of the CREATE TABLE statement being modified,
** 2) The old name of the table being renamed, and
** 3) The new name of the table being renamed.
**
** It returns the new CREATE TABLE statement. For example:
**
** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
** -> 'CREATE TABLE t1(a REFERENCES t3)'
*/
#if !SQLITE_OMIT_FOREIGN_KEY
static void renameParentFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
sqlite3 db = sqlite3_context_db_handle( context );
string zOutput = "";
string zResult;
string zInput = sqlite3_value_text( argv[0] );
string zOld = sqlite3_value_text( argv[1] );
string zNew = sqlite3_value_text( argv[2] );
int zIdx; /* Pointer to token */
int zLeft = 0; /* Pointer to remainder of String */
int n = 0; /* Length of token z */
int token = 0; /* Type of token */
UNUSED_PARAMETER( NotUsed );
for ( zIdx = 0; zIdx < zInput.Length; zIdx += n )//z=zInput; *z; z=z+n)
{
n = sqlite3GetToken( zInput, zIdx, ref token );
if ( token == TK_REFERENCES )
{
string zParent;
do
{
zIdx += n;
n = sqlite3GetToken( zInput, zIdx, ref token );
} while ( token == TK_SPACE );
zParent = zIdx + n < zInput.Length ? zInput.Substring( zIdx, n ) : "";//sqlite3DbStrNDup(db, zIdx, n);
if ( String.IsNullOrEmpty( zParent ) )
break;
sqlite3Dequote( ref zParent );
if ( zOld.Equals( zParent, StringComparison.InvariantCultureIgnoreCase ) )
{
string zOut = sqlite3MPrintf( db, "%s%.*s\"%w\"",
zOutput, zIdx - zLeft, zInput.Substring( zLeft ), zNew
);
sqlite3DbFree( db, ref zOutput );
zOutput = zOut;
zIdx += n;// zInput = &z[n];
zLeft = zIdx;
}
sqlite3DbFree( db, ref zParent );
}
}
zResult = sqlite3MPrintf( db, "%s%s", zOutput, zInput.Substring( zLeft ) );
sqlite3_result_text( context, zResult, -1, SQLITE_DYNAMIC );
sqlite3DbFree( db, ref zOutput );
}
#endif
#if !SQLITE_OMIT_TRIGGER
/* This function is used by SQL generated to implement the
** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
** statement. The second is a table name. The table name in the CREATE
** TRIGGER statement is replaced with the third argument and the result
** returned. This is analagous to renameTableFunc() above, except for CREATE
** TRIGGER, not CREATE INDEX and CREATE TABLE.
*/
static void renameTriggerFunc(
sqlite3_context context,
int NotUsed,
sqlite3_value[] argv
)
{
string zSql = sqlite3_value_text( argv[0] );
string zTableName = sqlite3_value_text( argv[1] );
int token = 0;
Token tname = new Token();
int dist = 3;
int zCsr = 0;
int zLoc = 0;
int len = 1;
string zRet;
sqlite3 db = sqlite3_context_db_handle( context );
UNUSED_PARAMETER( NotUsed );
/* The principle used to locate the table name in the CREATE TRIGGER
** statement is that the table name is the first token that is immediatedly
** preceded by either TK_ON or TK_DOT and immediatedly followed by one
** of TK_WHEN, TK_BEGIN or TK_FOR.
*/
if ( zSql != null )
{
do
{
if ( zCsr == zSql.Length )
{
/* Ran out of input before finding the table name. Return NULL. */
return;
}
/* Store the token that zCsr points to in tname. */
zLoc = zCsr;
tname.z = zSql.Substring( zCsr, len );//(char*)zCsr;
tname.n = len;
/* Advance zCsr to the next token. Store that token type in 'token',
** and its length in 'len' (to be used next iteration of this loop).
*/
do
{
zCsr += len;
len = ( zCsr == zSql.Length ) ? 1 : sqlite3GetToken( zSql, zCsr, ref token );
} while ( token == TK_SPACE );
Debug.Assert( len > 0 );
/* Variable 'dist' stores the number of tokens read since the most
** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
** token is read and 'dist' equals 2, the condition stated above
** to be met.
**
** Note that ON cannot be a database, table or column name, so
** there is no need to worry about syntax like
** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
*/
dist++;
if ( token == TK_DOT || token == TK_ON )
{
dist = 0;
}
} while ( dist != 2 || ( token != TK_WHEN && token != TK_FOR && token != TK_BEGIN ) );
/* Variable tname now contains the token that is the old table-name
** in the CREATE TRIGGER statement.
*/
zRet = sqlite3MPrintf( db, "%.*s\"%w\"%s", zLoc, zSql.Substring( 0, zLoc ),
zTableName, zSql.Substring( zLoc + tname.n ) );
sqlite3_result_text( context, zRet, -1, SQLITE_DYNAMIC );
}
}
#endif // * !SQLITE_OMIT_TRIGGER */
/*
** Register built-in functions used to help implement ALTER TABLE
*/
static FuncDef[] aAlterTableFuncs;
static void sqlite3AlterFunctions()
{
aAlterTableFuncs = new FuncDef[] {
FUNCTION("sqlite_rename_table", 2, 0, 0, renameTableFunc),
#if !SQLITE_OMIT_TRIGGER
FUNCTION("sqlite_rename_trigger", 2, 0, 0, renameTriggerFunc),
#endif
#if !SQLITE_OMIT_FOREIGN_KEY
FUNCTION("sqlite_rename_parent", 3, 0, 0, renameParentFunc),
#endif
};
int i;
#if SQLITE_OMIT_WSD
FuncDefHash pHash = GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
FuncDef[] aFunc = GLOBAL(FuncDef, aAlterTableFuncs);
#else
FuncDefHash pHash = sqlite3GlobalFunctions;
FuncDef[] aFunc = aAlterTableFuncs;
#endif
for ( i = 0; i < ArraySize( aAlterTableFuncs ); i++ )
{
sqlite3FuncDefInsert( pHash, aFunc[i] );
}
}
/*
** This function is used to create the text of expressions of the form:
**
** name=<constant1> OR name=<constant2> OR ...
**
** If argument zWhere is NULL, then a pointer string containing the text
** "name=<constant>" is returned, where <constant> is the quoted version
** of the string passed as argument zConstant. The returned buffer is
** allocated using sqlite3DbMalloc(). It is the responsibility of the
** caller to ensure that it is eventually freed.
**
** If argument zWhere is not NULL, then the string returned is
** "<where> OR name=<constant>", where <where> is the contents of zWhere.
** In this case zWhere is passed to sqlite3DbFree() before returning.
**
*/
static string whereOrName( sqlite3 db, string zWhere, string zConstant )
{
string zNew;
if ( String.IsNullOrEmpty( zWhere ) )
{
zNew = sqlite3MPrintf( db, "name=%Q", zConstant );
}
else
{
zNew = sqlite3MPrintf( db, "%s OR name=%Q", zWhere, zConstant );
sqlite3DbFree( db, ref zWhere );
}
return zNew;
}
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
/*
** Generate the text of a WHERE expression which can be used to select all
** tables that have foreign key constraints that refer to table pTab (i.e.
** constraints for which pTab is the parent table) from the sqlite_master
** table.
*/
static string whereForeignKeys( Parse pParse, Table pTab )
{
FKey p;
string zWhere = "";
for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo )
{
zWhere = whereOrName( pParse.db, zWhere, p.pFrom.zName );
}
return zWhere;
}
#endif
/*
** Generate the text of a WHERE expression which can be used to select all
** temporary triggers on table pTab from the sqlite_temp_master table. If
** table pTab has no temporary triggers, or is itself stored in the
** temporary database, NULL is returned.
*/
static string whereTempTriggers( Parse pParse, Table pTab )
{
Trigger pTrig;
string zWhere = "";
Schema pTempSchema = pParse.db.aDb[1].pSchema; /* Temp db schema */
/* If the table is not located in the temp.db (in which case NULL is
** returned, loop through the tables list of triggers. For each trigger
** that is not part of the temp.db schema, add a clause to the WHERE
** expression being built up in zWhere.
*/
if ( pTab.pSchema != pTempSchema )
{
sqlite3 db = pParse.db;
for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext )
{
if ( pTrig.pSchema == pTempSchema )
{
zWhere = whereOrName( db, zWhere, pTrig.zName );
}
}
}
if ( !String.IsNullOrEmpty( zWhere ) )
{
zWhere = sqlite3MPrintf( pParse.db, "type='trigger' AND (%s)", zWhere );
//sqlite3DbFree( pParse.db, ref zWhere );
//zWhere = zNew;
}
return zWhere;
}
/*
** Generate code to drop and reload the internal representation of table
** pTab from the database, including triggers and temporary triggers.
** Argument zName is the name of the table in the database schema at
** the time the generated code is executed. This can be different from
** pTab.zName if this function is being called to code part of an
** "ALTER TABLE RENAME TO" statement.
*/
static void reloadTableSchema( Parse pParse, Table pTab, string zName )
{
Vdbe v;
string zWhere;
int iDb; /* Index of database containing pTab */
#if !SQLITE_OMIT_TRIGGER
Trigger pTrig;
#endif
v = sqlite3GetVdbe( pParse );
if ( NEVER( v == null ) )
return;
Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
Debug.Assert( iDb >= 0 );
#if !SQLITE_OMIT_TRIGGER
/* Drop any table triggers from the internal schema. */
for ( pTrig = sqlite3TriggerList( pParse, pTab ); pTrig != null; pTrig = pTrig.pNext )
{
int iTrigDb = sqlite3SchemaToIndex( pParse.db, pTrig.pSchema );
Debug.Assert( iTrigDb == iDb || iTrigDb == 1 );
sqlite3VdbeAddOp4( v, OP_DropTrigger, iTrigDb, 0, 0, pTrig.zName, 0 );
}
#endif
/* Drop the table and index from the internal schema. */
sqlite3VdbeAddOp4( v, OP_DropTable, iDb, 0, 0, pTab.zName, 0 );
/* Reload the table, index and permanent trigger schemas. */
zWhere = sqlite3MPrintf( pParse.db, "tbl_name=%Q", zName );
if ( zWhere == null )
return;
sqlite3VdbeAddOp4( v, OP_ParseSchema, iDb, 0, 0, zWhere, P4_DYNAMIC );
#if !SQLITE_OMIT_TRIGGER
/* Now, if the table is not stored in the temp database, reload any temp
** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
*/
if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" )
{
sqlite3VdbeAddOp4( v, OP_ParseSchema, 1, 0, 0, zWhere, P4_DYNAMIC );
}
#endif
}
/*
** Parameter zName is the name of a table that is about to be altered
** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
** If the table is a system table, this function leaves an error message
** in pParse->zErr (system tables may not be altered) and returns non-zero.
**
** Or, if zName is not a system table, zero is returned.
*/
static int isSystemTable( Parse pParse, string zName )
{
if ( zName.StartsWith( "sqlite_", System.StringComparison.InvariantCultureIgnoreCase ) )
{
sqlite3ErrorMsg( pParse, "table %s may not be altered", zName );
return 1;
}
return 0;
}
/*
** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
** command.
*/
static void sqlite3AlterRenameTable(
Parse pParse, /* Parser context. */
SrcList pSrc, /* The table to rename. */
Token pName /* The new table name. */
)
{
int iDb; /* Database that contains the table */
string zDb; /* Name of database iDb */
Table pTab; /* Table being renamed */
string zName = null; /* NULL-terminated version of pName */
sqlite3 db = pParse.db; /* Database connection */
int nTabName; /* Number of UTF-8 characters in zTabName */
string zTabName; /* Original name of the table */
Vdbe v;
#if !SQLITE_OMIT_TRIGGER
string zWhere = ""; /* Where clause to locate temp triggers */
#endif
VTable pVTab = null; /* Non-zero if this is a v-tab with an xRename() */
int savedDbFlags; /* Saved value of db->flags */
savedDbFlags = db.flags;
//if ( NEVER( db.mallocFailed != 0 ) ) goto exit_rename_table;
Debug.Assert( pSrc.nSrc == 1 );
Debug.Assert( sqlite3BtreeHoldsAllMutexes( pParse.db ) );
pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase );
if ( pTab == null )
goto exit_rename_table;
iDb = sqlite3SchemaToIndex( pParse.db, pTab.pSchema );
zDb = db.aDb[iDb].zName;
db.flags |= SQLITE_PreferBuiltin;
/* Get a NULL terminated version of the new table name. */
zName = sqlite3NameFromToken( db, pName );
if ( zName == null )
goto exit_rename_table;
/* Check that a table or index named 'zName' does not already exist
** in database iDb. If so, this is an error.
*/
if ( sqlite3FindTable( db, zName, zDb ) != null || sqlite3FindIndex( db, zName, zDb ) != null )
{
sqlite3ErrorMsg( pParse,
"there is already another table or index with this name: %s", zName );
goto exit_rename_table;
}
/* Make sure it is not a system table being altered, or a reserved name
** that the table is being renamed to.
*/
if ( SQLITE_OK!=isSystemTable(pParse, pTab.zName) )
{
goto exit_rename_table;
}
if ( SQLITE_OK != sqlite3CheckObjectName( pParse, zName ) )
{
goto exit_rename_table;
}
#if !SQLITE_OMIT_VIEW
if ( pTab.pSelect != null )
{
sqlite3ErrorMsg( pParse, "view %s may not be altered", pTab.zName );
goto exit_rename_table;
}
#endif
#if !SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){
goto exit_rename_table;
}
#endif
if ( sqlite3ViewGetColumnNames( pParse, pTab ) != 0 )
{
goto exit_rename_table;
}
#if !SQLITE_OMIT_VIRTUALTABLE
if( IsVirtual(pTab) ){
pVTab = sqlite3GetVTable(db, pTab);
if( pVTab.pVtab.pModule.xRename==null ){
pVTab = null;
}
#endif
/* Begin a transaction and code the VerifyCookie for database iDb.
** Then modify the schema cookie (since the ALTER TABLE modifies the
** schema). Open a statement transaction if the table is a virtual
** table.
*/
v = sqlite3GetVdbe( pParse );
if ( v == null )
{
goto exit_rename_table;
}
sqlite3BeginWriteOperation( pParse, pVTab != null ? 1 : 0, iDb );
sqlite3ChangeCookie( pParse, iDb );
/* If this is a virtual table, invoke the xRename() function if
** one is defined. The xRename() callback will modify the names
** of any resources used by the v-table implementation (including other
** SQLite tables) that are identified by the name of the virtual table.
*/
#if !SQLITE_OMIT_VIRTUALTABLE
if ( pVTab !=null)
{
int i = ++pParse.nMem;
sqlite3VdbeAddOp4( v, OP_String8, 0, i, 0, zName, 0 );
sqlite3VdbeAddOp4( v, OP_VRename, i, 0, 0, pVtab, P4_VTAB );
sqlite3MayAbort(pParse);
}
#endif
/* figure out how many UTF-8 characters are in zName */
zTabName = pTab.zName;
nTabName = sqlite3Utf8CharLen( zTabName, -1 );
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
if ( ( db.flags & SQLITE_ForeignKeys ) != 0 )
{
/* If foreign-key support is enabled, rewrite the CREATE TABLE
** statements corresponding to all child tables of foreign key constraints
** for which the renamed table is the parent table. */
if ( ( zWhere = whereForeignKeys( pParse, pTab ) ) != null )
{
sqlite3NestedParse( pParse,
"UPDATE \"%w\".%s SET " +
"sql = sqlite_rename_parent(sql, %Q, %Q) " +
"WHERE %s;", zDb, SCHEMA_TABLE( iDb ), zTabName, zName, zWhere );
sqlite3DbFree( db, ref zWhere );
}
}
#endif
/* Modify the sqlite_master table to use the new table name. */
sqlite3NestedParse( pParse,
"UPDATE %Q.%s SET " +
#if SQLITE_OMIT_TRIGGER
"sql = sqlite_rename_table(sql, %Q), " +
#else
"sql = CASE " +
"WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)" +
"ELSE sqlite_rename_table(sql, %Q) END, " +
#endif
"tbl_name = %Q, " +
"name = CASE " +
"WHEN type='table' THEN %Q " +
"WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN " +
"'sqlite_autoindex_' || %Q || substr(name,%d+18) " +
"ELSE name END " +
"WHERE tbl_name=%Q AND " +
"(type='table' OR type='index' OR type='trigger');",
zDb, SCHEMA_TABLE( iDb ), zName, zName, zName,
#if !SQLITE_OMIT_TRIGGER
zName,
#endif
zName, nTabName, zTabName
);
#if !SQLITE_OMIT_AUTOINCREMENT
/* If the sqlite_sequence table exists in this database, then update
** it with the new table name.
*/
if ( sqlite3FindTable( db, "sqlite_sequence", zDb ) != null )
{
sqlite3NestedParse( pParse,
"UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
zDb, zName, pTab.zName
);
}
#endif
#if !SQLITE_OMIT_TRIGGER
/* If there are TEMP triggers on this table, modify the sqlite_temp_master
** table. Don't do this if the table being ALTERed is itself located in
** the temp database.
*/
if ( ( zWhere = whereTempTriggers( pParse, pTab ) ) != "" )
{
sqlite3NestedParse( pParse,
"UPDATE sqlite_temp_master SET " +
"sql = sqlite_rename_trigger(sql, %Q), " +
"tbl_name = %Q " +
"WHERE %s;", zName, zName, zWhere );
sqlite3DbFree( db, ref zWhere );
}
#endif
#if !(SQLITE_OMIT_FOREIGN_KEY) && !(SQLITE_OMIT_TRIGGER)
if ( ( db.flags & SQLITE_ForeignKeys ) != 0 )
{
FKey p;
for ( p = sqlite3FkReferences( pTab ); p != null; p = p.pNextTo )
{
Table pFrom = p.pFrom;
if ( pFrom != pTab )
{
reloadTableSchema( pParse, p.pFrom, pFrom.zName );
}
}
}
#endif
/* Drop and reload the internal table schema. */
reloadTableSchema( pParse, pTab, zName );
exit_rename_table:
sqlite3SrcListDelete( db, ref pSrc );
sqlite3DbFree( db, ref zName );
db.flags = savedDbFlags;
}
/*
** Generate code to make sure the file format number is at least minFormat.
** The generated code will increase the file format number if necessary.
*/
static void sqlite3MinimumFileFormat( Parse pParse, int iDb, int minFormat )
{
Vdbe v;
v = sqlite3GetVdbe( pParse );
/* The VDBE should have been allocated before this routine is called.
** If that allocation failed, we would have quit before reaching this
** point */
if ( ALWAYS( v ) )
{
int r1 = sqlite3GetTempReg( pParse );
int r2 = sqlite3GetTempReg( pParse );
int j1;
sqlite3VdbeAddOp3( v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT );
sqlite3VdbeUsesBtree( v, iDb );
sqlite3VdbeAddOp2( v, OP_Integer, minFormat, r2 );
j1 = sqlite3VdbeAddOp3( v, OP_Ge, r2, 0, r1 );
sqlite3VdbeAddOp3( v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2 );
sqlite3VdbeJumpHere( v, j1 );
sqlite3ReleaseTempReg( pParse, r1 );
sqlite3ReleaseTempReg( pParse, r2 );
}
}
/*
** This function is called after an "ALTER TABLE ... ADD" statement
** has been parsed. Argument pColDef contains the text of the new
** column definition.
**
** The Table structure pParse.pNewTable was extended to include
** the new column during parsing.
*/
static void sqlite3AlterFinishAddColumn( Parse pParse, Token pColDef )
{
Table pNew; /* Copy of pParse.pNewTable */
Table pTab; /* Table being altered */
int iDb; /* Database number */
string zDb; /* Database name */
string zTab; /* Table name */
string zCol; /* Null-terminated column definition */
Column pCol; /* The new column */
Expr pDflt; /* Default value for the new column */
sqlite3 db; /* The database connection; */
db = pParse.db;
if ( pParse.nErr != 0 /*|| db.mallocFailed != 0 */ )
return;
pNew = pParse.pNewTable;
Debug.Assert( pNew != null );
Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
iDb = sqlite3SchemaToIndex( db, pNew.pSchema );
zDb = db.aDb[iDb].zName;
zTab = pNew.zName.Substring( 16 );// zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
pCol = pNew.aCol[pNew.nCol - 1];
pDflt = pCol.pDflt;
pTab = sqlite3FindTable( db, zTab, zDb );
Debug.Assert( pTab != null );
#if !SQLITE_OMIT_AUTHORIZATION
/* Invoke the authorization callback. */
if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab.zName, 0) ){
return;
}
#endif
/* If the default value for the new column was specified with a
** literal NULL, then set pDflt to 0. This simplifies checking
** for an SQL NULL default below.
*/
if ( pDflt != null && pDflt.op == TK_NULL )
{
pDflt = null;
}
/* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
** If there is a NOT NULL constraint, then the default value for the
** column must not be NULL.
*/
if ( pCol.isPrimKey != 0 )
{
sqlite3ErrorMsg( pParse, "Cannot add a PRIMARY KEY column" );
return;
}
if ( pNew.pIndex != null )
{
sqlite3ErrorMsg( pParse, "Cannot add a UNIQUE column" );
return;
}
if ( ( db.flags & SQLITE_ForeignKeys ) != 0 && pNew.pFKey != null && pDflt != null )
{
sqlite3ErrorMsg( pParse,
"Cannot add a REFERENCES column with non-NULL default value" );
return;
}
if ( pCol.notNull != 0 && pDflt == null )
{
sqlite3ErrorMsg( pParse,
"Cannot add a NOT NULL column with default value NULL" );
return;
}
/* Ensure the default expression is something that sqlite3ValueFromExpr()
** can handle (i.e. not CURRENT_TIME etc.)
*/
if ( pDflt != null )
{
sqlite3_value pVal = null;
if ( sqlite3ValueFromExpr( db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, ref pVal ) != 0 )
{
// db.mallocFailed = 1;
return;
}
if ( pVal == null )
{
sqlite3ErrorMsg( pParse, "Cannot add a column with non-constant default" );
return;
}
sqlite3ValueFree( ref pVal );
}
/* Modify the CREATE TABLE statement. */
zCol = pColDef.z.Substring( 0, pColDef.n ).Replace( ";", " " ).Trim();//sqlite3DbStrNDup(db, (char*)pColDef.z, pColDef.n);
if ( zCol != null )
{
// char zEnd = zCol[pColDef.n-1];
int savedDbFlags = db.flags;
// while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
// zEnd-- = '\0';
// }
db.flags |= SQLITE_PreferBuiltin;
sqlite3NestedParse( pParse,
"UPDATE \"%w\".%s SET " +
"sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) " +
"WHERE type = 'table' AND name = %Q",
zDb, SCHEMA_TABLE( iDb ), pNew.addColOffset, zCol, pNew.addColOffset + 1,
zTab
);
sqlite3DbFree( db, ref zCol );
db.flags = savedDbFlags;
}
/* If the default value of the new column is NULL, then set the file
** format to 2. If the default value of the new column is not NULL,
** the file format becomes 3.
*/
sqlite3MinimumFileFormat( pParse, iDb, pDflt != null ? 3 : 2 );
/* Reload the schema of the modified table. */
reloadTableSchema( pParse, pTab, pTab.zName );
}
/*
** This function is called by the parser after the table-name in
** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
** pSrc is the full-name of the table being altered.
**
** This routine makes a (partial) copy of the Table structure
** for the table being altered and sets Parse.pNewTable to point
** to it. Routines called by the parser as the column definition
** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
** the copy. The copy of the Table structure is deleted by tokenize.c
** after parsing is finished.
**
** Routine sqlite3AlterFinishAddColumn() will be called to complete
** coding the "ALTER TABLE ... ADD" statement.
*/
static void sqlite3AlterBeginAddColumn( Parse pParse, SrcList pSrc )
{
Table pNew;
Table pTab;
Vdbe v;
int iDb;
int i;
int nAlloc;
sqlite3 db = pParse.db;
/* Look up the table being altered. */
Debug.Assert( pParse.pNewTable == null );
Debug.Assert( sqlite3BtreeHoldsAllMutexes( db ) );
// if ( db.mallocFailed != 0 ) goto exit_begin_add_column;
pTab = sqlite3LocateTable( pParse, 0, pSrc.a[0].zName, pSrc.a[0].zDatabase );
if ( pTab == null )
goto exit_begin_add_column;
if ( IsVirtual( pTab ) )
{
sqlite3ErrorMsg( pParse, "virtual tables may not be altered" );
goto exit_begin_add_column;
}
/* Make sure this is not an attempt to ALTER a view. */
if ( pTab.pSelect != null )
{
sqlite3ErrorMsg( pParse, "Cannot add a column to a view" );
goto exit_begin_add_column;
}
if ( SQLITE_OK != isSystemTable( pParse, pTab.zName ) )
{
goto exit_begin_add_column;
}
Debug.Assert( pTab.addColOffset > 0 );
iDb = sqlite3SchemaToIndex( db, pTab.pSchema );
/* Put a copy of the Table struct in Parse.pNewTable for the
** sqlite3AddColumn() function and friends to modify. But modify
** the name by adding an "sqlite_altertab_" prefix. By adding this
** prefix, we insure that the name will not collide with an existing
** table because user table are not allowed to have the "sqlite_"
** prefix on their name.
*/
pNew = new Table();// (Table*)sqlite3DbMallocZero( db, sizeof(Table))
if ( pNew == null )
goto exit_begin_add_column;
pParse.pNewTable = pNew;
pNew.nRef = 1;
pNew.nCol = pTab.nCol;
Debug.Assert( pNew.nCol > 0 );
nAlloc = ( ( ( pNew.nCol - 1 ) / 8 ) * 8 ) + 8;
Debug.Assert( nAlloc >= pNew.nCol && nAlloc % 8 == 0 && nAlloc - pNew.nCol < 8 );
pNew.aCol = new Column[nAlloc];// (Column*)sqlite3DbMallocZero( db, sizeof(Column) * nAlloc );
pNew.zName = sqlite3MPrintf( db, "sqlite_altertab_%s", pTab.zName );
if ( pNew.aCol == null || pNew.zName == null )
{
// db.mallocFailed = 1;
goto exit_begin_add_column;
}
// memcpy( pNew.aCol, pTab.aCol, sizeof(Column) * pNew.nCol );
for ( i = 0; i < pNew.nCol; i++ )
{
Column pCol = pTab.aCol[i].Copy();
// sqlite3DbStrDup( db, pCol.zName );
pCol.zColl = null;
pCol.zType = null;
pCol.pDflt = null;
pCol.zDflt = null;
pNew.aCol[i] = pCol;
}
pNew.pSchema = db.aDb[iDb].pSchema;
pNew.addColOffset = pTab.addColOffset;
pNew.nRef = 1;
/* Begin a transaction and increment the schema cookie. */
sqlite3BeginWriteOperation( pParse, 0, iDb );
v = sqlite3GetVdbe( pParse );
if ( v == null )
goto exit_begin_add_column;
sqlite3ChangeCookie( pParse, iDb );
exit_begin_add_column:
sqlite3SrcListDelete( db, ref pSrc );
return;
}
#endif // * SQLITE_ALTER_TABLE */
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Reflection;
using System.Xml;
using log4net;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Monitoring;
using OpenSim.Framework.Serialization;
using OpenSim.Framework.Serialization.External;
using OpenSim.Region.CoreModules.World.Archiver;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using Ionic.Zlib;
using GZipStream = Ionic.Zlib.GZipStream;
using CompressionMode = Ionic.Zlib.CompressionMode;
using PermissionMask = OpenSim.Framework.PermissionMask;
namespace OpenSim.Region.CoreModules.Avatar.Inventory.Archiver
{
public class InventoryArchiveWriteRequest
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
/// <summary>
/// Determine whether this archive will save assets. Default is true.
/// </summary>
public bool SaveAssets { get; set; }
/// <summary>
/// Determines which items will be included in the archive, according to their permissions.
/// Default is null, meaning no permission checks.
/// </summary>
public string FilterContent { get; set; }
/// <summary>
/// Counter for inventory items saved to archive for passing to compltion event
/// </summary>
public int CountItems { get; set; }
/// <summary>
/// Counter for inventory items skipped due to permission filter option for passing to compltion event
/// </summary>
public int CountFiltered { get; set; }
/// <value>
/// Used to select all inventory nodes in a folder but not the folder itself
/// </value>
private const string STAR_WILDCARD = "*";
private InventoryArchiverModule m_module;
private UserAccount m_userInfo;
private string m_invPath;
protected TarArchiveWriter m_archiveWriter;
protected UuidGatherer m_assetGatherer;
/// <value>
/// We only use this to request modules
/// </value>
protected Scene m_scene;
/// <value>
/// ID of this request
/// </value>
protected UUID m_id;
/// <value>
/// Used to collect the uuids of the users that we need to save into the archive
/// </value>
protected Dictionary<UUID, int> m_userUuids = new Dictionary<UUID, int>();
/// <value>
/// The stream to which the inventory archive will be saved.
/// </value>
private Stream m_saveStream;
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
UUID id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, string savePath)
: this(
id,
module,
scene,
userInfo,
invPath,
new GZipStream(new FileStream(savePath, FileMode.Create), CompressionMode.Compress, CompressionLevel.BestCompression))
{
}
/// <summary>
/// Constructor
/// </summary>
public InventoryArchiveWriteRequest(
UUID id, InventoryArchiverModule module, Scene scene,
UserAccount userInfo, string invPath, Stream saveStream)
{
m_id = id;
m_module = module;
m_scene = scene;
m_userInfo = userInfo;
m_invPath = invPath;
m_saveStream = saveStream;
m_assetGatherer = new UuidGatherer(m_scene.AssetService);
SaveAssets = true;
FilterContent = null;
}
protected void ReceivedAllAssets(ICollection<UUID> assetsFoundUuids, ICollection<UUID> assetsNotFoundUuids, bool timedOut)
{
Exception reportedException = null;
bool succeeded = true;
try
{
m_archiveWriter.Close();
}
catch (Exception e)
{
reportedException = e;
succeeded = false;
}
finally
{
m_saveStream.Close();
}
if (timedOut)
{
succeeded = false;
reportedException = new Exception("Loading assets timed out");
}
m_module.TriggerInventoryArchiveSaved(
m_id, succeeded, m_userInfo, m_invPath, m_saveStream, reportedException, CountItems, CountFiltered);
}
protected void SaveInvItem(InventoryItemBase inventoryItem, string path, Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("exclude"))
{
if (((List<String>)options["exclude"]).Contains(inventoryItem.Name) ||
((List<String>)options["exclude"]).Contains(inventoryItem.ID.ToString()))
{
if (options.ContainsKey("verbose"))
{
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Skipping inventory item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, path);
}
CountFiltered++;
return;
}
}
// Check For Permissions Filter Flags
if (!CanUserArchiveObject(m_userInfo.PrincipalID, inventoryItem))
{
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Insufficient permissions, skipping inventory item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, path);
// Count Items Excluded
CountFiltered++;
return;
}
if (options.ContainsKey("verbose"))
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Saving item {0} {1} (asset UUID {2})",
inventoryItem.ID, inventoryItem.Name, inventoryItem.AssetID);
string filename = path + CreateArchiveItemName(inventoryItem);
// Record the creator of this item for user record purposes (which might go away soon)
m_userUuids[inventoryItem.CreatorIdAsUuid] = 1;
string serialization = UserInventoryItemSerializer.Serialize(inventoryItem, options, userAccountService);
m_archiveWriter.WriteFile(filename, serialization);
AssetType itemAssetType = (AssetType)inventoryItem.AssetType;
// Count inventory items (different to asset count)
CountItems++;
// Don't chase down link asset items as they actually point to their target item IDs rather than an asset
if (SaveAssets && itemAssetType != AssetType.Link && itemAssetType != AssetType.LinkFolder)
m_assetGatherer.AddForInspection(inventoryItem.AssetID);
}
/// <summary>
/// Save an inventory folder
/// </summary>
/// <param name="inventoryFolder">The inventory folder to save</param>
/// <param name="path">The path to which the folder should be saved</param>
/// <param name="saveThisFolderItself">If true, save this folder itself. If false, only saves contents</param>
/// <param name="options"></param>
/// <param name="userAccountService"></param>
protected void SaveInvFolder(
InventoryFolderBase inventoryFolder, string path, bool saveThisFolderItself,
Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("excludefolders"))
{
if (((List<String>)options["excludefolders"]).Contains(inventoryFolder.Name) ||
((List<String>)options["excludefolders"]).Contains(inventoryFolder.ID.ToString()))
{
if (options.ContainsKey("verbose"))
{
m_log.InfoFormat(
"[INVENTORY ARCHIVER]: Skipping folder {0} at {1}",
inventoryFolder.Name, path);
}
return;
}
}
if (options.ContainsKey("verbose"))
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving folder {0}", inventoryFolder.Name);
if (saveThisFolderItself)
{
path += CreateArchiveFolderName(inventoryFolder);
// We need to make sure that we record empty folders
m_archiveWriter.WriteDir(path);
}
InventoryCollection contents
= m_scene.InventoryService.GetFolderContent(inventoryFolder.Owner, inventoryFolder.ID);
foreach (InventoryFolderBase childFolder in contents.Folders)
{
SaveInvFolder(childFolder, path, true, options, userAccountService);
}
foreach (InventoryItemBase item in contents.Items)
{
SaveInvItem(item, path, options, userAccountService);
}
}
/// <summary>
/// Checks whether the user has permission to export an inventory item to an IAR.
/// </summary>
/// <param name="UserID">The user</param>
/// <param name="InvItem">The inventory item</param>
/// <returns>Whether the user is allowed to export the object to an IAR</returns>
private bool CanUserArchiveObject(UUID UserID, InventoryItemBase InvItem)
{
if (FilterContent == null)
return true;// Default To Allow Export
bool permitted = true;
bool canCopy = (InvItem.CurrentPermissions & (uint)PermissionMask.Copy) != 0;
bool canTransfer = (InvItem.CurrentPermissions & (uint)PermissionMask.Transfer) != 0;
bool canMod = (InvItem.CurrentPermissions & (uint)PermissionMask.Modify) != 0;
if (FilterContent.Contains("C") && !canCopy)
permitted = false;
if (FilterContent.Contains("T") && !canTransfer)
permitted = false;
if (FilterContent.Contains("M") && !canMod)
permitted = false;
return permitted;
}
/// <summary>
/// Execute the inventory write request
/// </summary>
public void Execute(Dictionary<string, object> options, IUserAccountService userAccountService)
{
if (options.ContainsKey("noassets") && (bool)options["noassets"])
SaveAssets = false;
// Set Permission filter if flag is set
if (options.ContainsKey("checkPermissions"))
{
Object temp;
if (options.TryGetValue("checkPermissions", out temp))
FilterContent = temp.ToString().ToUpper();
}
try
{
InventoryFolderBase inventoryFolder = null;
InventoryItemBase inventoryItem = null;
InventoryFolderBase rootFolder = m_scene.InventoryService.GetRootFolder(m_userInfo.PrincipalID);
bool saveFolderContentsOnly = false;
// Eliminate double slashes and any leading / on the path.
string[] components
= m_invPath.Split(
new string[] { InventoryFolderImpl.PATH_DELIMITER }, StringSplitOptions.RemoveEmptyEntries);
int maxComponentIndex = components.Length - 1;
// If the path terminates with a STAR then later on we want to archive all nodes in the folder but not the
// folder itself. This may get more sophisicated later on
if (maxComponentIndex >= 0 && components[maxComponentIndex] == STAR_WILDCARD)
{
saveFolderContentsOnly = true;
maxComponentIndex--;
}
else if (maxComponentIndex == -1)
{
// If the user has just specified "/", then don't save the root "My Inventory" folder. This is
// more intuitive then requiring the user to specify "/*" for this.
saveFolderContentsOnly = true;
}
m_invPath = String.Empty;
for (int i = 0; i <= maxComponentIndex; i++)
{
m_invPath += components[i] + InventoryFolderImpl.PATH_DELIMITER;
}
// Annoyingly Split actually returns the original string if the input string consists only of delimiters
// Therefore if we still start with a / after the split, then we need the root folder
if (m_invPath.Length == 0)
{
inventoryFolder = rootFolder;
}
else
{
m_invPath = m_invPath.Remove(m_invPath.LastIndexOf(InventoryFolderImpl.PATH_DELIMITER));
List<InventoryFolderBase> candidateFolders
= InventoryArchiveUtils.FindFoldersByPath(m_scene.InventoryService, rootFolder, m_invPath);
if (candidateFolders.Count > 0)
inventoryFolder = candidateFolders[0];
}
// The path may point to an item instead
if (inventoryFolder == null)
inventoryItem = InventoryArchiveUtils.FindItemByPath(m_scene.InventoryService, rootFolder, m_invPath);
if (null == inventoryFolder && null == inventoryItem)
{
// We couldn't find the path indicated
string errorMessage = string.Format("Aborted save. Could not find inventory path {0}", m_invPath);
Exception e = new InventoryArchiverException(errorMessage);
m_module.TriggerInventoryArchiveSaved(m_id, false, m_userInfo, m_invPath, m_saveStream, e, 0, 0);
throw e;
}
m_archiveWriter = new TarArchiveWriter(m_saveStream);
m_log.InfoFormat("[INVENTORY ARCHIVER]: Adding control file to archive.");
// Write out control file. This has to be done first so that subsequent loaders will see this file first
// XXX: I know this is a weak way of doing it since external non-OAR aware tar executables will not do this
// not sure how to fix this though, short of going with a completely different file format.
m_archiveWriter.WriteFile(ArchiveConstants.CONTROL_FILE_PATH, CreateControlFile(options));
if (inventoryFolder != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found folder {0} {1} at {2}",
inventoryFolder.Name,
inventoryFolder.ID,
m_invPath == String.Empty ? InventoryFolderImpl.PATH_DELIMITER : m_invPath);
//recurse through all dirs getting dirs and files
SaveInvFolder(inventoryFolder, ArchiveConstants.INVENTORY_PATH, !saveFolderContentsOnly, options, userAccountService);
}
else if (inventoryItem != null)
{
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Found item {0} {1} at {2}",
inventoryItem.Name, inventoryItem.ID, m_invPath);
SaveInvItem(inventoryItem, ArchiveConstants.INVENTORY_PATH, options, userAccountService);
}
// Don't put all this profile information into the archive right now.
//SaveUsers();
if (SaveAssets)
{
m_assetGatherer.GatherAll();
m_log.DebugFormat(
"[INVENTORY ARCHIVER]: Saving {0} assets for items", m_assetGatherer.GatheredUuids.Count);
AssetsRequest ar
= new AssetsRequest(
new AssetsArchiver(m_archiveWriter),
m_assetGatherer.GatheredUuids, m_scene.AssetService,
m_scene.UserAccountService, m_scene.RegionInfo.ScopeID,
options, ReceivedAllAssets);
WorkManager.RunInThread(o => ar.Execute(), null, string.Format("AssetsRequest ({0})", m_scene.Name));
}
else
{
m_log.DebugFormat("[INVENTORY ARCHIVER]: Not saving assets since --noassets was specified");
ReceivedAllAssets(new List<UUID>(), new List<UUID>(), false);
}
}
catch (Exception)
{
m_saveStream.Close();
throw;
}
}
/// <summary>
/// Save information for the users that we've collected.
/// </summary>
protected void SaveUsers()
{
m_log.InfoFormat("[INVENTORY ARCHIVER]: Saving user information for {0} users", m_userUuids.Count);
foreach (UUID creatorId in m_userUuids.Keys)
{
// Record the creator of this item
UserAccount creator = m_scene.UserAccountService.GetUserAccount(m_scene.RegionInfo.ScopeID, creatorId);
if (creator != null)
{
m_archiveWriter.WriteFile(
ArchiveConstants.USERS_PATH + creator.FirstName + " " + creator.LastName + ".xml",
UserProfileSerializer.Serialize(creator.PrincipalID, creator.FirstName, creator.LastName));
}
else
{
m_log.WarnFormat("[INVENTORY ARCHIVER]: Failed to get creator profile for {0}", creatorId);
}
}
}
/// <summary>
/// Create the archive name for a particular folder.
/// </summary>
///
/// These names are prepended with an inventory folder's UUID so that more than one folder can have the
/// same name
///
/// <param name="folder"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(InventoryFolderBase folder)
{
return CreateArchiveFolderName(folder.Name, folder.ID);
}
/// <summary>
/// Create the archive name for a particular item.
/// </summary>
///
/// These names are prepended with an inventory item's UUID so that more than one item can have the
/// same name
///
/// <param name="item"></param>
/// <returns></returns>
public static string CreateArchiveItemName(InventoryItemBase item)
{
return CreateArchiveItemName(item.Name, item.ID);
}
/// <summary>
/// Create an archive folder name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveFolderName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}/",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create an archive item name given its constituent components
/// </summary>
/// <param name="name"></param>
/// <param name="id"></param>
/// <returns></returns>
public static string CreateArchiveItemName(string name, UUID id)
{
return string.Format(
"{0}{1}{2}.xml",
InventoryArchiveUtils.EscapeArchivePath(name),
ArchiveConstants.INVENTORY_NODE_NAME_COMPONENT_SEPARATOR,
id);
}
/// <summary>
/// Create the control file for the archive
/// </summary>
/// <param name="options"></param>
/// <returns></returns>
public string CreateControlFile(Dictionary<string, object> options)
{
int majorVersion, minorVersion;
if (options.ContainsKey("home"))
{
majorVersion = 1;
minorVersion = 2;
}
else
{
majorVersion = 0;
minorVersion = 3;
}
m_log.InfoFormat("[INVENTORY ARCHIVER]: Creating version {0}.{1} IAR", majorVersion, minorVersion);
StringWriter sw = new StringWriter();
XmlTextWriter xtw = new XmlTextWriter(sw);
xtw.Formatting = Formatting.Indented;
xtw.WriteStartDocument();
xtw.WriteStartElement("archive");
xtw.WriteAttributeString("major_version", majorVersion.ToString());
xtw.WriteAttributeString("minor_version", minorVersion.ToString());
xtw.WriteElementString("assets_included", SaveAssets.ToString());
xtw.WriteEndElement();
xtw.Flush();
xtw.Close();
String s = sw.ToString();
sw.Close();
return s;
}
}
}
| |
/***************************************************************************************************************************************
* Copyright (C) 2001-2012 LearnLift USA *
* Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com *
* *
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License *
* as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty *
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, *
* write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************************************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using MLifter.DAL;
using MLifter.DAL.DB;
using MLifter.DAL.DB.MsSqlCe;
using MLifter.DAL.DB.PostgreSQL;
using MLifter.DAL.Interfaces;
using MLifter.DAL.Interfaces.DB;
using MLifter.DAL.Tools;
using MLifter.DAL.XML;
using Npgsql;
namespace MLifter.DAL
{
/// <summary>
/// This is the logger for learning modules.
/// </summary>
public static class Log
{
private static int lastSessionId = -1;
private static ParentClass globalParent = new ParentClass(new DummyUser(new ConnectionStringStruct()), null);
private static bool hasParentChanged = true;
private static IDbSessionConnector GetSessionConnector(ParentClass parent)
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PgSqlSessionConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MsSqlCeSessionConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
private static IDbLearnLoggingConnector GetLearnLoggingConnector(ParentClass parent)
{
switch (parent.CurrentUser.ConnectionString.Typ)
{
case DatabaseType.PostgreSQL:
return PgSqlLearnLoggingConnector.GetInstance(parent);
case DatabaseType.MsSqlCe:
return MsSqlCeLearnLoggingConnector.GetInstance(parent);
default:
throw new UnsupportedDatabaseTypeException(parent.CurrentUser.ConnectionString.Typ);
}
}
/// <summary>
/// Gets the last session ID.
/// </summary>
/// <value>The last session ID.</value>
/// <remarks>Documented by Dev08, 2009-01-29</remarks>
public static int LastSessionID
{
get
{
return lastSessionId;
}
}
/// <summary>
/// Opens the user session.
/// </summary>
/// <param name="lm_id">The lm_id.</param>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev08, 2008-09-05</remarks>
public static void OpenUserSession(int lm_id, ParentClass parent)
{
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
{
lock (globalParent)
{
globalParent = parent;
hasParentChanged = true;
}
if (!writerThread.IsAlive)
{
writerThread.CurrentCulture = Thread.CurrentThread.CurrentCulture;
writerThread.CurrentUICulture = Thread.CurrentThread.CurrentUICulture;
writerThread.Start();
}
try { lastSessionId = GetSessionConnector(parent).OpenUserSession(lm_id); }
catch (Exception ex)
{
Trace.WriteLine("Error starting session: " + ex.Message);
throw new StartLearningSessionException();
}
}
}
/// <summary>
/// Recalculates the box sizes.
/// </summary>
/// <remarks>Documented by Dev05, 2009-05-06</remarks>
public static void RecalculateBoxSizes(ParentClass parent)
{
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
GetSessionConnector(parent).RecalculateBoxSizes(lastSessionId);
}
/// <summary>
/// Call if a Cards from a box is deleted.
/// </summary>
/// <param name="parent">The parent.</param>
/// <param name="boxNumber">The box number.</param>
/// <remarks>
/// Documented by CFI, 2009-05-06
/// </remarks>
public static void CardFromBoxDeleted(ParentClass parent, int boxNumber)
{
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
GetSessionConnector(parent).CardFromBoxDeleted(lastSessionId, boxNumber);
}
/// <summary>
/// Cards the added.
/// </summary>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev05, 2009-05-25</remarks>
public static void CardAdded(ParentClass parent)
{
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
GetSessionConnector(parent).CardAdded(lastSessionId);
}
/// <summary>
/// Closes the user session.
/// </summary>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev08, 2008-09-05</remarks>
public static void CloseUserSession(ParentClass parent)
{
if (lastSessionId < 0) //return if CloseUserSession(...) happens before OpenUserSession(...)
return;
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
{
try
{
GetSessionConnector(parent).CloseUserSession(lastSessionId);
FlushLogQueue(parent); //force writing all Log entries
}
catch (Exception ex) { Trace.WriteLine("Error ending session: " + ex.Message); }
}
lastSessionId = -1;
}
/// <summary>
/// Restarts the learning success.
/// </summary>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev08, 2008-11-19</remarks>
public static IDictionary RestartLearningSuccess(ParentClass parent)
{
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return parent.GetParentDictionary();
return GetSessionConnector(parent).RestartLearningSuccess(parent.CurrentUser.ConnectionString.LmId);
}
/// <summary>
/// Creates the learn log entry.
/// </summary>
/// <param name="learnLogStruct">The learn log struct.</param>
/// <param name="parent">The parent.</param>
/// <remarks>Documented by Dev08, 2008-09-05</remarks>
public static void CreateLearnLogEntry(LearnLogStruct learnLogStruct, ParentClass parent)
{
if (lastSessionId < 0) //Only write if there is a valid userSession
return;
if (parent.CurrentUser.ConnectionString.Typ == DatabaseType.Xml)
return;
else
{
try
{
lock (logQueue)
{
logQueue.Enqueue(learnLogStruct);
Monitor.Pulse(logQueue);
}
}
catch (Exception ex) { Trace.WriteLine("Error writing log: " + ex.Message); }
}
}
private static Thread writerThread = new Thread(new ThreadStart(LearnLogWriter));
private static Queue<LearnLogStruct> logQueue = new Queue<LearnLogStruct>();
private static void LearnLogWriter()
{
Thread.CurrentThread.IsBackground = true;
Thread.CurrentThread.Name = "LogWriterThread";
ParentClass parent = new ParentClass(new DummyUser(new ConnectionStringStruct()), null);
while (true)
{
try
{
LearnLogStruct? lls = null;
lock (logQueue)
{
while (logQueue.Count == 0)
Monitor.Wait(logQueue);
if (logQueue.Count > 0)
lls = logQueue.Dequeue();
}
if (lls.HasValue)
{
if (hasParentChanged)
{
lock (globalParent)
{
parent = globalParent;
hasParentChanged = false;
}
}
IDbLearnLoggingConnector learnLogConnector = GetLearnLoggingConnector(parent);
learnLogConnector.CreateLearnLogEntry(lls.Value);
}
}
catch (Exception ex) { Trace.WriteLine("Error in learnLogWriter: " + ex.Message); }
}
}
private static void FlushLogQueue(ParentClass parent)
{
lock (logQueue)
{
IDbLearnLoggingConnector con = GetLearnLoggingConnector(parent);
while (logQueue.Count > 0)
con.CreateLearnLogEntry(logQueue.Dequeue());
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Globalization;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace NGraphics
{
public class SvgReader
{
readonly IFormatProvider icult = System.Globalization.CultureInfo.InvariantCulture;
public double PixelsPerInch { get; private set; }
public Graphic Graphic { get; private set; }
readonly Dictionary<string, XElement> defs = new Dictionary<string, XElement> ();
// readonly XNamespace ns;
public SvgReader (System.IO.TextReader reader, double pixelsPerInch = 160.0)
{
PixelsPerInch = pixelsPerInch;
Read (XDocument.Load (reader));
}
void Read (XDocument doc)
{
var svg = doc.Root;
var ns = svg.Name.Namespace;
//
// Find the defs (gradients)
//
foreach (var d in svg.Descendants ()) {
var idA = d.Attribute ("id");
if (idA != null) {
defs [ReadString (idA).Trim ()] = d;
}
}
//
// Get the dimensions
//
var widthA = svg.Attribute ("width");
var heightA = svg.Attribute ("height");
var width = ReadNumber (widthA);
var height = ReadNumber (heightA);
var size = new Size (width, height);
var viewBox = new Rect (size);
var viewBoxA = svg.Attribute ("viewBox") ?? svg.Attribute ("viewPort");
if (viewBoxA != null) {
viewBox = ReadRectangle (viewBoxA.Value);
}
if (widthA != null && widthA.Value.Contains ("%")) {
size.Width *= viewBox.Width;
}
if (heightA != null && heightA.Value.Contains ("%")) {
size.Height *= viewBox.Height;
}
//
// Add the elements
//
Graphic = new Graphic (size, viewBox);
AddElements (Graphic.Children, svg.Elements (), null, Brushes.Black);
}
void AddElements (IList<IDrawable> list, IEnumerable<XElement> es, Pen inheritPen, Brush inheritBrush)
{
foreach (var e in es)
AddElement (list, e, inheritPen, inheritBrush);
}
void AddElement (IList<IDrawable> list, XElement e, Pen inheritPen, Brush inheritBrush)
{
//
// Style
//
Element r = null;
Pen pen = null;
Brush brush = null;
bool hasPen, hasBrush;
ApplyStyle (e.Attributes ().ToDictionary (k => k.Name.LocalName, v => v.Value), ref pen, out hasPen, ref brush, out hasBrush);
var style = ReadString (e.Attribute ("style"));
if (!string.IsNullOrWhiteSpace (style)) {
ApplyStyle (style, ref pen, out hasPen, ref brush, out hasBrush);
}
pen = hasPen ? pen : inheritPen;
brush = hasBrush ? brush : inheritBrush;
//var id = ReadString (e.Attribute ("id"));
//
// Elements
//
switch (e.Name.LocalName) {
case "text":
{
var x = ReadNumber (e.Attribute ("x"));
var y = ReadNumber (e.Attribute ("y"));
var text = e.Value.Trim ();
var fontFamilyAttribute = e.Attribute("font-family");
var font = new Font ();
if (fontFamilyAttribute != null)
font.Family = fontFamilyAttribute.Value.Trim('\'');
var fontSizeAttribute = e.Attribute("font-size");
if (fontSizeAttribute != null)
font.Size = ReadNumber(fontSizeAttribute.Value);
r = new Text (text, new Rect (new Point (x, y), new Size (double.MaxValue, double.MaxValue)), font, TextAlignment.Left, pen, brush);
}
break;
case "rect":
{
var x = ReadNumber (e.Attribute ("x"));
var y = ReadNumber (e.Attribute ("y"));
var width = ReadNumber (e.Attribute ("width"));
var height = ReadNumber (e.Attribute ("height"));
r = new Rectangle (new Point (x, y), new Size (width, height), pen, brush);
}
break;
case "ellipse":
{
var cx = ReadNumber (e.Attribute ("cx"));
var cy = ReadNumber (e.Attribute ("cy"));
var rx = ReadNumber (e.Attribute ("rx"));
var ry = ReadNumber (e.Attribute ("ry"));
r = new Ellipse (new Point (cx - rx, cy - ry), new Size (2 * rx, 2 * ry), pen, brush);
}
break;
case "circle":
{
var cx = ReadNumber (e.Attribute ("cx"));
var cy = ReadNumber (e.Attribute ("cy"));
var rr = ReadNumber (e.Attribute ("r"));
r = new Ellipse (new Point (cx - rr, cy - rr), new Size (2 * rr, 2 * rr), pen, brush);
}
break;
case "path":
{
var dA = e.Attribute ("d");
if (dA != null && !string.IsNullOrWhiteSpace (dA.Value)) {
var p = new Path (pen, brush);
ReadPath (p, dA.Value);
r = p;
}
}
break;
case "polygon":
{
var pA = e.Attribute ("points");
if (pA != null && !string.IsNullOrWhiteSpace (pA.Value)) {
var path = new Path (pen, brush);
ReadPoints (path, pA.Value, true);
r = path;
}
}
break;
case "polyline":
{
var pA = e.Attribute ("points");
if (pA != null && !string.IsNullOrWhiteSpace (pA.Value)) {
var path = new Path (pen, brush);
ReadPoints (path, pA.Value, false);
r = path;
}
}
break;
case "g":
{
var g = new Group ();
var groupId = e.Attribute("id");
if (groupId != null && !string.IsNullOrEmpty(groupId.Value))
g.Id = groupId.Value;
AddElements (g.Children, e.Elements (), pen, brush);
r = g;
}
break;
case "use":
{
var href = ReadString (e.Attributes ().FirstOrDefault (x => x.Name.LocalName == "href"));
if (!string.IsNullOrWhiteSpace (href)) {
XElement useE;
if (defs.TryGetValue (href.Trim ().Replace ("#", ""), out useE)) {
var useList = new List<IDrawable> ();
AddElement (useList, useE, pen, brush);
r = useList.OfType<Element> ().FirstOrDefault ();
}
}
}
break;
case "title":
Graphic.Title = ReadString (e);
break;
case "desc":
case "description":
Graphic.Description = ReadString (e);
break;
case "defs":
// Already read in earlier pass
break;
case "namedview":
case "metadata":
case "image":
// Ignore
break;
case "line":
{
var x1 = ReadNumber ( e.Attribute("x1") );
var x2 = ReadNumber ( e.Attribute("x2") );
var y1 = ReadNumber ( e.Attribute("y1") );
var y2 = ReadNumber ( e.Attribute("y2") );
r = new Line(new Point(x1, y1), new Point(x2, y2), pen);
}
break;
case "foreignObject":
{
var x = ReadNumber ( e.Attribute("x") );
var y = ReadNumber ( e.Attribute("y") );
var width = ReadNumber ( e.Attribute("width") );
var height = ReadNumber ( e.Attribute("height") );
r = new ForeignObject(new Point(x, y), new Size(width, height));
}
break;
case "pgf":
{
var id = e.Attribute("id");
System.Diagnostics.Debug.WriteLine("Ignoring pgf element" + (id != null ? ": '" + id.Value + "'" : ""));
}
break;
case "switch":
{
// Evaluate requiredFeatures, requiredExtensions and systemLanguage
foreach (var ee in e.Elements())
{
var requiredFeatures = ee.Attribute("requiredFeatures");
var requiredExtensions = ee.Attribute("requiredExtensions");
var systemLanguage = ee.Attribute("systemLanguage");
// currently no support for any of these restrictions
if (requiredFeatures == null && requiredExtensions == null && systemLanguage == null)
AddElement (list, ee, pen, brush);
}
}
break;
// color definition that can be referred to by other elements
case "linearGradient":
break;
default:
throw new NotSupportedException ("SVG element \"" + e.Name.LocalName + "\" is not supported");
}
if (r != null) {
r.Transform = ReadTransform (ReadString (e.Attribute ("transform")));
list.Add (r);
}
}
Regex keyValueRe = new Regex (@"\s*(\w+)\s*:\s*(.*)");
void ApplyStyle (string style, ref Pen pen, out bool hasPen, ref Brush brush, out bool hasBrush)
{
var d = new Dictionary<string, string> ();
var kvs = style.Split (new[]{ ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var kv in kvs) {
var m = keyValueRe.Match (kv);
if (m.Success) {
var k = m.Groups [1].Value;
var v = m.Groups [2].Value;
d [k] = v;
}
}
ApplyStyle (d, ref pen, out hasPen, ref brush, out hasBrush);
}
string GetString (Dictionary<string, string> style, string name, string defaultValue = "")
{
string v;
if (style.TryGetValue (name, out v))
return v;
return defaultValue;
}
Regex fillUrlRe = new Regex (@"url\s*\(\s*#([^\)]+)\)");
void ApplyStyle (Dictionary<string, string> style, ref Pen pen, out bool hasPen, ref Brush brush, out bool hasBrush)
{
//
// Pen attributes
//
var strokeWidth = GetString (style, "stroke-width");
if (!string.IsNullOrWhiteSpace (strokeWidth)) {
if (pen == null)
pen = new Pen ();
pen.Width = ReadNumber (strokeWidth);
}
var strokeOpacity = GetString (style, "stroke-opacity");
if (!string.IsNullOrWhiteSpace (strokeOpacity)) {
if (pen == null)
pen = new Pen ();
pen.Color = pen.Color.WithAlpha (ReadNumber (strokeOpacity));
}
//
// Pen
//
var stroke = GetString (style, "stroke").Trim ();
if (string.IsNullOrEmpty (stroke)) {
// No change
hasPen = false;
} else if (stroke.Equals("none", StringComparison.OrdinalIgnoreCase)) {
hasPen = true;
pen = null;
} else {
hasPen = true;
if (pen == null)
pen = new Pen ();
Color color;
if (Colors.TryParse (stroke, out color)) {
if (pen.Color.Alpha == 1)
pen.Color = color;
else
pen.Color = color.WithAlpha (pen.Color.Alpha);
}
}
//
// Brush attributes
//
var fillOpacity = GetString (style, "fill-opacity");
if (!string.IsNullOrWhiteSpace (fillOpacity)) {
if (brush == null)
brush = new SolidBrush ();
var sb = brush as SolidBrush;
if (sb != null)
sb.Color = sb.Color.WithAlpha (ReadNumber (fillOpacity));
}
//
// Brush
//
var fill = GetString (style, "fill").Trim ();
if (string.IsNullOrEmpty (fill)) {
// No change
hasBrush = false;
} else if (fill.Equals("none", StringComparison.OrdinalIgnoreCase)) {
hasBrush = true;
brush = null;
} else {
hasBrush = true;
Color color;
if (Colors.TryParse (fill, out color)) {
var sb = brush as SolidBrush;
if (sb == null) {
brush = new SolidBrush (color);
} else {
if (sb.Color.Alpha == 1)
sb.Color = color;
else
sb.Color = color.WithAlpha (sb.Color.Alpha);
}
} else {
var urlM = fillUrlRe.Match (fill);
if (urlM.Success) {
var id = urlM.Groups [1].Value.Trim ();
brush = GetGradientBrush(id, null);
} else {
throw new NotSupportedException ("Fill " + fill);
}
}
}
}
protected GradientBrush GetGradientBrush(string fill, GradientBrush child)
{
XElement defE;
if (defs.TryGetValue (fill, out defE)) {
GradientBrush brush = null;
switch (defE.Name.LocalName) {
case "linearGradient":
brush = CreateLinearGradientBrush (defE);
break;
case "radialGradient":
brush = CreateRadialGradientBrush (defE);
break;
default:
throw new NotSupportedException ("Fill " + defE.Name);
}
if (child != null)
{
if (child is RadialGradientBrush && brush is RadialGradientBrush)
{
((RadialGradientBrush)brush).Center = ((RadialGradientBrush)child).Center;
((RadialGradientBrush)brush).Focus = ((RadialGradientBrush)child).Focus;
((RadialGradientBrush)brush).Radius = ((RadialGradientBrush)child).Radius;
} else if (child is LinearGradientBrush && brush is LinearGradientBrush)
{
((LinearGradientBrush)brush).Start = ((LinearGradientBrush)child).Start;
((LinearGradientBrush)brush).End = ((LinearGradientBrush)child).End;
}
brush.AddStops(child.Stops);
}
XNamespace xlink = "http://www.w3.org/1999/xlink";
var parent = defE.Attribute(xlink + "href");
if (parent != null && !string.IsNullOrEmpty(parent.Value))
{
brush = GetGradientBrush(parent.Value.Substring(1), brush);
}
return brush;
} else {
throw new Exception ("Invalid fill url reference: " + fill);
}
}
Transform ReadTransform (string raw)
{
if (string.IsNullOrWhiteSpace (raw))
return Transform.Identity;
var s = raw.Trim ();
var calls = s.Split (new[]{ ')' }, StringSplitOptions.RemoveEmptyEntries);
var t = Transform.Identity;
foreach (var c in calls) {
var args = c.Split (new[]{ '(', ',', ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
var nt = Transform.Identity;
switch (args [0]) {
case "matrix":
if (args.Length == 7) {
nt = new Transform (
ReadNumber(args[1]),
ReadNumber(args[2]),
ReadNumber(args[3]),
ReadNumber(args[4]),
ReadNumber(args[5]),
ReadNumber(args[6]));
} else {
throw new NotSupportedException ("Matrices are expected to have 6 elements, this one has " + (args.Length - 1));
}
break;
case "translate":
if (args.Length >= 3) {
nt = Transform.Translate (new Size (ReadNumber (args [1]), ReadNumber (args [2])));
} else if (args.Length >= 2) {
nt = Transform.Translate (new Size (ReadNumber (args[1]), 0));
}
break;
case "scale":
if (args.Length >= 3) {
nt = Transform.Scale (new Size (ReadNumber (args[1]), ReadNumber (args[2])));
} else if (args.Length >= 2) {
var sx = ReadNumber (args [1]);
nt = Transform.Scale (new Size (sx, sx));
}
break;
case "rotate":
var a = ReadNumber (args [1]);
if (args.Length >= 4) {
var x = ReadNumber (args [2]);
var y = ReadNumber (args [3]);
var t1 = Transform.Translate (new Size (x, y));
var t2 = Transform.Rotate (a);
var t3 = Transform.Translate (new Size (-x, -y));
nt = t1 * t2 * t3;
} else {
nt = Transform.Rotate (a);
}
break;
default:
throw new NotSupportedException ("Can't transform " + args[0]);
}
t = t * nt;
}
return t;
}
static readonly char[] WSC = new char[] { ',', ' ', '\t', '\n', '\r' };
static Regex pathRegex = new Regex(@"[MLHVCSQTAZmlhvcsqtaz][^MLHVCSQTAZmlhvcsqtaz]*", RegexOptions.Singleline);
void ReadPath (Path p, string pathDescriptor)
{
Match m = pathRegex.Match(pathDescriptor);
while(m.Success)
{
var match = m.Value.TrimStart ();
var op = match[0];
var args = match.Substring(1).Split (WSC, StringSplitOptions.RemoveEmptyEntries);
Point previousPoint = new Point ();
if (p.Operations.Count > 0 && !(p.Operations.Last() is ClosePath))
previousPoint = p.Operations.Last().EndPoint;
if ((op == 'M' || op == 'm') && args.Length >= 2) {
var point = new Point (ReadNumber (args [0]), ReadNumber (args [1]));
if (op == 'm')
point += previousPoint;
p.MoveTo (point);
} else if ((op == 'L' || op == 'l') && args.Length >= 2) {
var point = new Point (ReadNumber (args [0]), ReadNumber (args [1]));
if (op == 'l')
point += previousPoint;
p.LineTo (point);
} else if ((op == 'C' || op == 'c') && args.Length >= 6) {
var c1 = new Point (ReadNumber (args [0]), ReadNumber (args [1]));
var c2 = new Point (ReadNumber (args [2]), ReadNumber (args [3]));
var pt = new Point (ReadNumber (args [4]), ReadNumber (args [5]));
if (op == 'c')
{
c1 += previousPoint;
c2 += previousPoint;
pt += previousPoint;
}
p.CurveTo (c1, c2, pt);
} else if ((op == 'S' || op == 's') && args.Length >= 4) {
var c = new Point (ReadNumber (args [0]), ReadNumber (args [1]));
var pt = new Point (ReadNumber (args [2]), ReadNumber (args [3]));
if (op == 's')
{
c += previousPoint;
pt += previousPoint;
}
p.ContinueCurveTo (c, pt);
} else if ((op == 'A' || op == 'a') && args.Length >= 7) {
var r = new Size (ReadNumber (args [0]), ReadNumber (args [1]));
// var xr = ReadNumber (args [i + 2]);
var laf = ReadNumber (args [3]) != 0;
var swf = ReadNumber (args [4]) != 0;
var pt = new Point (ReadNumber (args [5]), ReadNumber (args [6]));
if (op == 'a')
pt += previousPoint;
p.ArcTo (r, laf, swf, pt);
} else if ((op == 'V' || op == 'v') && args.Length >= 1 && p.Operations.Count > 0) {
var previousX = previousPoint.X;
var y = ReadNumber(args[0]);
if (op == 'v')
y += previousPoint.Y;
var point = new Point(previousX, y);
p.LineTo(point);
} else if ((op == 'H' || op == 'h') && args.Length >= 1 && p.Operations.Count > 0) {
var previousY = previousPoint.Y;
var x = ReadNumber(args[0]);
if (op == 'h')
x += previousPoint.X;
var point = new Point(x, previousY);
p.LineTo(point);
} else if (op == 'z' || op == 'Z') {
p.Close ();
} else {
throw new NotSupportedException ("Path Operation " + op);
}
m = m.NextMatch();
}
}
void ReadPoints (Path p, string pathDescriptor, bool closePath)
{
var args = pathDescriptor.Split (new[]{' '}, StringSplitOptions.RemoveEmptyEntries);
var i = 0;
var n = args.Length;
if (n == 0)
throw new Exception ("Not supported point");
while (i < n) {
var xy = args[i].Split(new[]{','}, StringSplitOptions.RemoveEmptyEntries);
var x = ReadNumber (xy[0]);
var y = ReadNumber (xy[1]);
if (i == 0) {
p.MoveTo (x, y);
} else
p.LineTo (x, y);
i++;
}
if (closePath)
p.Close ();
}
string ReadString (XElement e, string defaultValue = "")
{
if (e == null)
return defaultValue;
return e.Value ?? defaultValue;
}
string ReadString (XAttribute a, string defaultValue = "")
{
if (a == null)
return defaultValue;
return a.Value ?? defaultValue;
}
RadialGradientBrush CreateRadialGradientBrush (XElement e)
{
var b = new RadialGradientBrush ();
b.Center.X = ReadNumber (e.Attribute ("cx"));
b.Center.Y = ReadNumber (e.Attribute ("cy"));
b.Focus.X = ReadNumber (e.Attribute ("fx"));
b.Focus.Y = ReadNumber (e.Attribute ("fy"));
var r = ReadNumber (e.Attribute ("r"));
b.Radius = new Size (r);
ReadStops (e, b.Stops);
return b;
}
LinearGradientBrush CreateLinearGradientBrush (XElement e)
{
var b = new LinearGradientBrush ();
b.Start.X = ReadNumber (e.Attribute ("x1"));
b.Start.Y = ReadNumber (e.Attribute ("y1"));
b.End.X = ReadNumber (e.Attribute ("x2"));
b.End.Y = ReadNumber (e.Attribute ("y2"));
var gradientUnits = e.Attribute("gradientUnits");
if (gradientUnits != null)
{
b.Absolute = gradientUnits.Value == "userSpaceOnUse";
}
ReadStops (e, b.Stops);
return b;
}
void ReadStops (XElement e, List<GradientStop> stops)
{
var ns = e.Name.Namespace;
foreach (var se in e.Elements (ns + "stop")) {
var s = new GradientStop ();
s.Offset = ReadNumber (se.Attribute ("offset"));
var styleAttribute = se.Attribute("style");
if (styleAttribute != null)
{
var styleSettings = styleAttribute.Value.Split(';');
foreach(var style in styleSettings)
{
if (style.Contains("stop-color") && style.IndexOf(':') != -1)
{
s.Color = ReadColor(style.Substring(style.IndexOf(':')+1));
break;
}
}
}
var stopColorAttribute = se.Attribute("stop-color");
if (stopColorAttribute != null)
s.Color = ReadColor (stopColorAttribute.Value);
stops.Add (s);
}
stops.Sort ((x, y) => x.Offset.CompareTo (y.Offset));
}
Color ReadColor (XElement e, string attrib)
{
var a = e.Attribute (attrib);
if (a == null)
return Colors.Black;
return ReadColor (a.Value);
}
Regex rgbRe = new Regex("([0-9]+).*?([0-9]+).*?([0-9]+)");
Color ReadColor (string raw)
{
if (string.IsNullOrWhiteSpace (raw) || raw.Equals("none", StringComparison.OrdinalIgnoreCase))
return Colors.Clear;
var s = raw.Trim ();
if (s.Length == 7 && s [0] == '#')
{
var r = int.Parse (s.Substring (1, 2), NumberStyles.HexNumber, icult);
var g = int.Parse (s.Substring (3, 2), NumberStyles.HexNumber, icult);
var b = int.Parse (s.Substring (5, 2), NumberStyles.HexNumber, icult);
return new Color (r / 255.0, g / 255.0, b / 255.0, 1);
}
var match = rgbRe.Match(s);
if (match.Success && match.Groups.Count == 4)
{
var r = int.Parse( match.Groups[1].Value );
var g = int.Parse( match.Groups[2].Value );
var b = int.Parse( match.Groups[3].Value );
return new Color (r / 255.0, g / 255.0, b / 255.0, 1);
}
Color color;
if (Colors.TryParse (s, out color))
return color;
throw new NotSupportedException ("Color " + s);
}
double ReadNumber (XAttribute a)
{
if (a == null)
return 0;
return ReadNumber (a.Value);
}
double ReadNumber (string raw)
{
if (string.IsNullOrWhiteSpace (raw))
return 0;
var s = raw.Trim ();
var m = 1.0;
if (s.EndsWith ("px", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
} else if (s.EndsWith ("in", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
m = PixelsPerInch;
} else if (s.EndsWith ("cm", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
m = PixelsPerInch / 2.54;
} else if (s.EndsWith ("mm", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
m = PixelsPerInch / 25.4;
} else if (s.EndsWith ("pt", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
m = PixelsPerInch / 72.0;
} else if (s.EndsWith ("pc", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 2);
m = PixelsPerInch / 6.0;
} else if (s.EndsWith ("%", StringComparison.Ordinal)) {
s = s.Substring (0, s.Length - 1);
m = 0.01;
}
double v;
if (!double.TryParse (s, NumberStyles.Float, icult, out v)) {
v = 0;
}
return m * v;
}
static readonly char[] WS = new char[] { ' ', '\t', '\n', '\r' };
Rect ReadRectangle (string s)
{
var r = new Rect ();
var p = s.Split (WS, StringSplitOptions.RemoveEmptyEntries);
if (p.Length > 0)
r.X = ReadNumber (p [0]);
if (p.Length > 1)
r.Y = ReadNumber (p [1]);
if (p.Length > 2)
r.Width = ReadNumber (p [2]);
if (p.Length > 3)
r.Height = ReadNumber (p [3]);
return r;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Orleans;
using Orleans.Runtime;
using UnitTests.GrainInterfaces;
using UnitTests.Tester;
using Xunit;
#pragma warning disable 618
namespace UnitTests.General
{
public class BasicActivationTests : HostedTestClusterEnsureDefaultStarted
{
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_ActivateAndUpdate()
{
long g1Key = GetRandomGrainId();
long g2Key = GetRandomGrainId();
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(g1Key);
ITestGrain g2 = GrainClient.GrainFactory.GetGrain<ITestGrain>(g2Key);
Assert.Equal(g1Key, g1.GetPrimaryKeyLong());
Assert.Equal(g1Key, g1.GetKey().Result);
Assert.Equal(g1Key.ToString(), g1.GetLabel().Result);
Assert.Equal(g2Key, g2.GetKey().Result);
Assert.Equal(g2Key.ToString(), g2.GetLabel().Result);
g1.SetLabel("one").Wait();
Assert.Equal("one", g1.GetLabel().Result);
Assert.Equal(g2Key.ToString(), g2.GetLabel().Result);
ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>(g1Key);
Assert.Equal("one", g1a.GetLabel().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_Guid_ActivateAndUpdate()
{
Guid guid1 = Guid.NewGuid();
Guid guid2 = Guid.NewGuid();
IGuidTestGrain g1 = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid1);
IGuidTestGrain g2 = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid2);
Assert.Equal(guid1, g1.GetPrimaryKey());
Assert.Equal(guid1, g1.GetKey().Result);
Assert.Equal(guid1.ToString(), g1.GetLabel().Result);
Assert.Equal(guid2, g2.GetKey().Result);
Assert.Equal(guid2.ToString(), g2.GetLabel().Result);
g1.SetLabel("one").Wait();
Assert.Equal("one", g1.GetLabel().Result);
Assert.Equal(guid2.ToString(), g2.GetLabel().Result);
IGuidTestGrain g1a = GrainClient.GrainFactory.GetGrain<IGuidTestGrain>(guid1);
Assert.Equal("one", g1a.GetLabel().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("ErrorHandling"), TestCategory("GetGrain")]
public void BasicActivation_Fail()
{
bool failed;
long key = 0;
try
{
// Key values of -2 are not allowed in this case
ITestGrain fail = GrainClient.GrainFactory.GetGrain<ITestGrain>(-2);
key = fail.GetKey().Result;
failed = false;
}
catch (Exception e)
{
Assert.IsAssignableFrom<OrleansException>(e.GetBaseException()) ;
failed = true;
}
if (!failed) Assert.True(false, "Should have failed, but instead returned " + key);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_ULong_MaxValue()
{
ulong key1AsUlong = UInt64.MaxValue; // == -1L
long key1 = (long)key1AsUlong;
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1);
Assert.Equal(key1, g1.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetKey().Result);
Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result);
g1.SetLabel("MaxValue").Wait();
Assert.Equal("MaxValue", g1.GetLabel().Result);
ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong);
Assert.Equal("MaxValue", g1a.GetLabel().Result);
Assert.Equal(key1, g1a.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1a.GetKey().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_ULong_MinValue()
{
ulong key1AsUlong = UInt64.MinValue; // == zero
long key1 = (long)key1AsUlong;
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1);
Assert.Equal(key1, g1.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetKey().Result);
Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result);
g1.SetLabel("MinValue").Wait();
Assert.Equal("MinValue", g1.GetLabel().Result);
ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong);
Assert.Equal("MinValue", g1a.GetLabel().Result);
Assert.Equal(key1, g1a.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1a.GetKey().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_Long_MaxValue()
{
long key1 = Int32.MaxValue;
ulong key1AsUlong = (ulong)key1;
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1);
Assert.Equal(key1, g1.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetKey().Result);
Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result);
g1.SetLabel("MaxValue").Wait();
Assert.Equal("MaxValue", g1.GetLabel().Result);
ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong);
Assert.Equal("MaxValue", g1a.GetLabel().Result);
Assert.Equal(key1, g1a.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1a.GetKey().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("GetGrain")]
public void BasicActivation_Long_MinValue()
{
long key1 = Int64.MinValue;
ulong key1AsUlong = (ulong)key1;
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(key1);
Assert.Equal((long)key1AsUlong, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetPrimaryKeyLong());
Assert.Equal(key1, g1.GetKey().Result);
Assert.Equal(key1.ToString(CultureInfo.InvariantCulture), g1.GetLabel().Result);
g1.SetLabel("MinValue").Wait();
Assert.Equal("MinValue", g1.GetLabel().Result);
ITestGrain g1a = GrainClient.GrainFactory.GetGrain<ITestGrain>((long)key1AsUlong);
Assert.Equal("MinValue", g1a.GetLabel().Result);
Assert.Equal(key1, g1a.GetPrimaryKeyLong());
Assert.Equal((long)key1AsUlong, g1a.GetKey().Result);
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate")]
public void BasicActivation_MultipleGrainInterfaces()
{
ITestGrain simple = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId());
simple.GetMultipleGrainInterfaces_List().Wait();
logger.Info("GetMultipleGrainInterfaces_List() worked");
simple.GetMultipleGrainInterfaces_Array().Wait();
logger.Info("GetMultipleGrainInterfaces_Array() worked");
}
[Fact, TestCategory("Functional"), TestCategory("ActivateDeactivate"), TestCategory("Reentrancy")]
public void BasicActivation_Reentrant_RecoveryAfterExpiredMessage()
{
List<Task> promises = new List<Task>();
TimeSpan prevTimeout = GrainClient.GetResponseTimeout();
// set short response time and ask to do long operation, to trigger expired msgs in the silo queues.
TimeSpan shortTimeout = TimeSpan.FromMilliseconds(1000);
GrainClient.SetResponseTimeout(shortTimeout);
ITestGrain grain = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId());
int num = 10;
for (long i = 0; i < num; i++)
{
Task task = grain.DoLongAction(TimeSpan.FromMilliseconds(shortTimeout.TotalMilliseconds * 3), "A_" + i);
promises.Add(task);
}
try
{
Task.WhenAll(promises).Wait();
}catch(Exception)
{
logger.Info("Done with stress iteration.");
}
// wait a bit to make sure expired msgs in the silo is trigered.
Thread.Sleep(TimeSpan.FromSeconds(10));
// set the regular response time back, expect msgs ot succeed.
GrainClient.SetResponseTimeout(prevTimeout);
logger.Info("About to send a next legit request that should succeed.");
grain.DoLongAction(TimeSpan.FromMilliseconds(1), "B_" + 0).Wait();
logger.Info("The request succeeded.");
}
[Fact, TestCategory("Functional"), TestCategory("RequestContext"), TestCategory("GetGrain")]
public void BasicActivation_TestRequestContext()
{
ITestGrain g1 = GrainClient.GrainFactory.GetGrain<ITestGrain>(GetRandomGrainId());
Task<Tuple<string, string>> promise1 = g1.TestRequestContext();
Tuple<string, string> requstContext = promise1.Result;
logger.Info("Request Context is: " + requstContext);
Assert.NotNull(requstContext.Item2);
Assert.NotNull(requstContext.Item1);
}
}
}
#pragma warning restore 618
| |
using System;
using System.Runtime.InteropServices;
namespace VulkanCore
{
/// <summary>
/// Structure containing callback functions for memory allocation.
/// </summary>
public unsafe struct AllocationCallbacks
{
/// <summary>
/// Initializes a new instance of the <see cref="AllocationCallbacks"/> structure.
/// </summary>
/// <param name="alloc">The application-defined memory allocation function.</param>
/// <param name="realloc">The application-defined memory reallocation function.</param>
/// <param name="free">The application-defined memory free function</param>
/// <param name="internalAlloc">
/// The application-defined function that is called by the implementation when the
/// implementation makes internal allocations.
/// </param>
/// <param name="internalFree">
/// The application-defined function that is called by the implementation when the
/// implementation frees internal allocations.
/// </param>
/// <param name="userData">
/// The value to be interpreted by the implementation of the callbacks.
/// <para>
/// When any of the callbacks in <see cref="AllocationCallbacks"/> are called, the Vulkan
/// implementation will pass this value as the first parameter to the callback.
/// </para>
/// <para>
/// This value can vary each time an allocator is passed into a command, even when the same
/// object takes an allocator in multiple commands.
/// </para>
/// </param>
public AllocationCallbacks(AllocationFunction alloc, ReallocationFunction realloc, FreeFunction free,
InternalAllocationNotification internalAlloc = null, InternalFreeNotification internalFree = null,
IntPtr userData = default(IntPtr))
{
Allocation = alloc;
Reallocation = realloc;
Free = free;
InternalAllocation = internalAlloc;
InternalFree = internalFree;
UserData = userData;
}
/// <summary>
/// The value to be interpreted by the implementation of the callbacks.
/// <para>
/// When any of the callbacks in <see cref="AllocationCallbacks"/> are called, the Vulkan
/// implementation will pass this value as the first parameter to the callback.
/// </para>
/// <para>
/// This value can vary each time an allocator is passed into a command, even when the same
/// object takes an allocator in multiple commands.
/// </para>
/// </summary>
public IntPtr UserData;
/// <summary>
/// The application-defined memory allocation function.
/// </summary>
public AllocationFunction Allocation;
/// <summary>
/// Gets the application-defined memory reallocation function.
/// </summary>
public ReallocationFunction Reallocation;
/// <summary>
/// Gets the application-defined memory free function.
/// </summary>
public FreeFunction Free;
/// <summary>
/// The application-defined function that is called by the implementation when the
/// implementation makes internal allocations. This value may be <c>null</c>.
/// </summary>
public InternalAllocationNotification InternalAllocation;
/// <summary>
/// The application-defined function that is called by the implementation when
/// the implementation frees internal allocations. This value may be <c>null</c>.
/// </summary>
public InternalFreeNotification InternalFree;
[StructLayout(LayoutKind.Sequential)]
internal struct Native
{
public IntPtr UserData;
public IntPtr Allocation;
public IntPtr Reallocation;
public IntPtr Free;
public IntPtr InternalAllocation;
public IntPtr InternalFree;
}
internal void ToNative(Native* native)
{
native->UserData = UserData;
native->Allocation = Interop.GetFunctionPointerForDelegate(Allocation);
native->Reallocation = Interop.GetFunctionPointerForDelegate(Reallocation);
native->Free = Interop.GetFunctionPointerForDelegate(Free);
native->InternalAllocation = InternalAllocation == null
? IntPtr.Zero
: Interop.GetFunctionPointerForDelegate(InternalAllocation);
native->InternalFree = InternalFree == null
? IntPtr.Zero
: Interop.GetFunctionPointerForDelegate(InternalFree);
}
/// <summary>
/// Application-defined memory allocation function.
/// <para>
/// If this function is unable to allocate the requested memory, it must return <see
/// cref="IntPtr.Zero"/>. If the allocation was successful, it must return a valid handle to
/// memory allocation containing at least <paramref name="size"/> bytes, and with the pointer
/// value being a multiple of <paramref name="alignment"/>.
/// </para>
/// <para>
/// For example, this function (or <see cref="ReallocationFunction"/>) could cause
/// termination of running Vulkan instance(s) on a failed allocation for debugging purposes,
/// either directly or indirectly. In these circumstances, it cannot be assumed that any part
/// of any affected <see cref="Instance"/> objects are going to operate correctly (even <see
/// cref="Instance.Dispose"/>), and the application must ensure it cleans up properly via
/// other means (e.g. process termination).
/// </para>
/// <para>
/// If this function returns <see cref="IntPtr.Zero"/>, and if the implementation is unable
/// to continue correct processing of the current command without the requested allocation,
/// it must treat this as a run-time error, and generate <see
/// cref="Result.ErrorOutOfHostMemory"/> at the appropriate time for the command in which the
/// condition was detected.
/// </para>
/// <para>
/// If the implementation is able to continue correct processing of the current command
/// without the requested allocation, then it may do so, and must not generate <see
/// cref="Result.ErrorOutOfHostMemory"/> as a result of this failed allocation.
/// </para>
/// </summary>
/// <param name="userData">
/// Value specified for <see cref="UserData"/> in the allocator specified by the application.
/// </param>
/// <param name="size">Size in bytes of the requested allocation.</param>
/// <param name="alignment">
/// Requested alignment of the allocation in bytes and must be a power of two.
/// </param>
/// <param name="allocationScope">
/// Value specifying the allocation scope of the lifetime of the allocation.
/// </param>
public delegate IntPtr AllocationFunction(
IntPtr userData, Size size, Size alignment, SystemAllocationScope allocationScope);
/// <summary>
/// Application-defined memory reallocation function.
/// <para>
/// Must return an allocation with enough space for <paramref name="size"/> bytes, and the
/// contents of the original allocation from bytes zero to `min(original size, new size) - 1`
/// must be preserved in the returned allocation. If <paramref name="size"/> is larger than
/// the old size, the contents of the additional space are undefined. If satisfying these
/// requirements involves creating a new allocation, then the old allocation should be freed.
/// </para>
/// <para>
/// If <paramref name="original"/> is <see cref="IntPtr.Zero"/>, then the function must
/// behave equivalently to a call to <see cref="AllocationFunction"/> with the same parameter
/// values (without <paramref name="original"/>).
/// </para>
/// <para>
/// If <paramref name="size"/> is zero, then the function must behave equivalently to a call
/// to <see cref="FreeFunction"/> with the same <paramref name="userData"/> parameter value,
/// and 'memory' equal to <paramref name="original"/>.
/// </para>
/// <para>
/// If <paramref name="original"/> is not <see cref="IntPtr.Zero"/>, the implementation must
/// ensure that <paramref name="alignment"/> is equal to the <paramref name="alignment"/>
/// used to originally allocate <paramref name="original"/>.
/// </para>
/// <para>
/// If this function fails and <paramref name="original"/> is not <see cref="IntPtr.Zero"/>
/// the application must not free the old allocation.
/// </para>
/// <para>This function must follow the same rules for return values as <see cref="AllocationFunction"/>.</para>
/// </summary>
/// <param name="userData">
/// Value specified for <see cref="UserData"/> in the allocator specified by the application.
/// </param>
/// <param name="original">
/// Must be either <see cref="IntPtr.Zero"/> or a pointer previously returned by <see
/// cref="Reallocation"/> or <see cref="Allocation"/> of the same allocator.
/// </param>
/// <param name="size">Size in bytes of the requested allocation.</param>
/// <param name="alignment">
/// Requested alignment of the allocation in bytes and must be a power of two.
/// </param>
/// <param name="allocationScope">
/// Value specifying the allocation scope of the lifetime of the allocation.
/// </param>
public delegate IntPtr ReallocationFunction(
IntPtr userData, IntPtr original, Size size, Size alignment, SystemAllocationScope allocationScope);
/// <summary>
/// Application-defined memory free function.
/// <para>
/// <paramref name="memory"/> may be <see cref="IntPtr.Zero"/>, which the callback must
/// handle safely. If <paramref name="memory"/> is not <see cref="IntPtr.Zero"/>, it must be
/// a handle to previously allocated by <see cref="AllocationFunction"/> or <see
/// cref="ReallocationFunction"/>. The application should free this memory.
/// </para>
/// </summary>
/// <param name="userData">
/// Value specified for <see cref="UserData"/> in the allocator specified
/// by the application.
/// </param>
/// <param name="memory">Allocation to be freed.</param>
public delegate void FreeFunction(IntPtr userData, IntPtr memory);
/// <summary>
/// Application-defined memory allocation notification function.
/// <para>This is a purely informational callback.</para>
/// </summary>
/// <param name="userData">
/// Value specified for <see cref="UserData"/> in the allocator specified by the application.
/// </param>
/// <param name="size">Size in bytes of the requested allocation.</param>
/// <param name="allocationType">Requested type of an allocation.</param>
/// <param name="allocationScope">
/// Value specifying the allocation scope of the lifetime of the allocation.
/// </param>
public delegate void InternalAllocationNotification(
IntPtr userData, Size size, InternalAllocationType allocationType, SystemAllocationScope allocationScope);
/// <summary>
/// Application-defined memory free notification function.
/// </summary>
/// <param name="userData">
/// Value specified for <see cref="UserData"/> in the allocator specified by the application.
/// </param>
/// <param name="size">Size in bytes of the requested allocation.</param>
/// <param name="allocationType">Requested type of an allocation.</param>
/// <param name="allocationScope">
/// Value specifying the allocation scope of the lifetime of the allocation.
/// </param>
public delegate void InternalFreeNotification(
IntPtr userData, Size size, InternalAllocationType allocationType, SystemAllocationScope allocationScope);
}
/// <summary>
/// Allocation scope.
/// </summary>
public enum SystemAllocationScope
{
/// <summary>
/// Specifies that the allocation is scoped to the duration of the Vulkan command.
/// </summary>
Command = 0,
/// <summary>
/// Specifies that the allocation is scoped to the lifetime of the Vulkan object that is
/// being created or used.
/// </summary>
Object = 1,
/// <summary>
/// Specifies that the allocation is scoped to the lifetime of a <see cref="PipelineCache"/>
/// or <see cref="Ext.ValidationCacheExt"/> object.
/// </summary>
Cache = 2,
/// <summary>
/// Specifies that the allocation is scoped to the lifetime of the Vulkan device.
/// </summary>
Device = 3,
/// <summary>
/// Specifies that the allocation is scoped to the lifetime of the Vulkan instance.
/// </summary>
Instance = 4
}
/// <summary>
/// Allocation type.
/// </summary>
public enum InternalAllocationType
{
/// <summary>
/// Specifies that the allocation is intended for execution by the host.
/// </summary>
Executable = 0
}
}
| |
// 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.Immutable;
namespace System.Reflection.Metadata.Ecma335
{
// TODO: debug metadata blobs
// TODO: revisit ctors (public vs internal vs static factories)?
public readonly struct BlobEncoder
{
public BlobBuilder Builder { get; }
public BlobEncoder(BlobBuilder builder)
{
if (builder == null)
{
Throw.BuilderArgumentNull();
}
Builder = builder;
}
/// <summary>
/// Encodes Field Signature blob.
/// </summary>
/// <returns>Encoder of the field type.</returns>
public SignatureTypeEncoder FieldSignature()
{
Builder.WriteByte((byte)SignatureKind.Field);
return new SignatureTypeEncoder(Builder);
}
/// <summary>
/// Encodes Method Specification Signature blob.
/// </summary>
/// <param name="genericArgumentCount">Number of generic arguments.</param>
/// <returns>Encoder of generic arguments.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [0, 0xffff].</exception>
public GenericTypeArgumentsEncoder MethodSpecificationSignature(int genericArgumentCount)
{
if (unchecked((uint)genericArgumentCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericArgumentCount));
}
Builder.WriteByte((byte)SignatureKind.MethodSpecification);
Builder.WriteCompressedInteger(genericArgumentCount);
return new GenericTypeArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes Method Signature blob.
/// </summary>
/// <param name="convention">Calling convention.</param>
/// <param name="genericParameterCount">Number of generic parameters.</param>
/// <param name="isInstanceMethod">True to encode an instance method signature, false to encode a static method signature.</param>
/// <returns>An Encoder of the rest of the signature including return value and parameters.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception>
public MethodSignatureEncoder MethodSignature(
SignatureCallingConvention convention = SignatureCallingConvention.Default,
int genericParameterCount = 0,
bool isInstanceMethod = false)
{
if (unchecked((uint)genericParameterCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericParameterCount));
}
var attributes =
(genericParameterCount != 0 ? SignatureAttributes.Generic : 0) |
(isInstanceMethod ? SignatureAttributes.Instance : 0);
Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, attributes).RawValue);
if (genericParameterCount != 0)
{
Builder.WriteCompressedInteger(genericParameterCount);
}
return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs);
}
/// <summary>
/// Encodes Property Signature blob.
/// </summary>
/// <param name="isInstanceProperty">True to encode an instance property signature, false to encode a static property signature.</param>
/// <returns>An Encoder of the rest of the signature including return value and parameters, which has the same structure as Method Signature.</returns>
public MethodSignatureEncoder PropertySignature(bool isInstanceProperty = false)
{
Builder.WriteByte(new SignatureHeader(SignatureKind.Property, SignatureCallingConvention.Default, (isInstanceProperty ? SignatureAttributes.Instance : 0)).RawValue);
return new MethodSignatureEncoder(Builder, hasVarArgs: false);
}
/// <summary>
/// Encodes Custom Attribute Signature blob.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="fixedArguments">Use first, to encode fixed arguments.</param>
/// <param name="namedArguments">Use second, to encode named arguments.</param>
public void CustomAttributeSignature(out FixedArgumentsEncoder fixedArguments, out CustomAttributeNamedArgumentsEncoder namedArguments)
{
Builder.WriteUInt16(0x0001);
fixedArguments = new FixedArgumentsEncoder(Builder);
namedArguments = new CustomAttributeNamedArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes Custom Attribute Signature blob.
/// </summary>
/// <param name="fixedArguments">Called first, to encode fixed arguments.</param>
/// <param name="namedArguments">Called second, to encode named arguments.</param>
/// <exception cref="ArgumentNullException"><paramref name="fixedArguments"/> or <paramref name="namedArguments"/> is null.</exception>
public void CustomAttributeSignature(Action<FixedArgumentsEncoder> fixedArguments, Action<CustomAttributeNamedArgumentsEncoder> namedArguments)
{
if (fixedArguments == null) Throw.ArgumentNull(nameof(fixedArguments));
if (namedArguments == null) Throw.ArgumentNull(nameof(namedArguments));
FixedArgumentsEncoder fixedArgumentsEncoder;
CustomAttributeNamedArgumentsEncoder namedArgumentsEncoder;
CustomAttributeSignature(out fixedArgumentsEncoder, out namedArgumentsEncoder);
fixedArguments(fixedArgumentsEncoder);
namedArguments(namedArgumentsEncoder);
}
/// <summary>
/// Encodes Local Variable Signature.
/// </summary>
/// <param name="variableCount">Number of local variables.</param>
/// <returns>Encoder of a sequence of local variables.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="variableCount"/> is not in range [0, 0x1fffffff].</exception>
public LocalVariablesEncoder LocalVariableSignature(int variableCount)
{
if (unchecked((uint)variableCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(variableCount));
}
Builder.WriteByte((byte)SignatureKind.LocalVariables);
Builder.WriteCompressedInteger(variableCount);
return new LocalVariablesEncoder(Builder);
}
/// <summary>
/// Encodes Type Specification Signature.
/// </summary>
/// <returns>
/// Type encoder of the structured type represented by the Type Specification (it shall not encode a primitive type).
/// </returns>
public SignatureTypeEncoder TypeSpecificationSignature()
{
return new SignatureTypeEncoder(Builder);
}
/// <summary>
/// Encodes a Permission Set blob.
/// </summary>
/// <param name="attributeCount">Number of attributes in the set.</param>
/// <returns>Permission Set encoder.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="attributeCount"/> is not in range [0, 0x1fffffff].</exception>
public PermissionSetEncoder PermissionSetBlob(int attributeCount)
{
if (unchecked((uint)attributeCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(attributeCount));
}
Builder.WriteByte((byte)'.');
Builder.WriteCompressedInteger(attributeCount);
return new PermissionSetEncoder(Builder);
}
/// <summary>
/// Encodes Permission Set arguments.
/// </summary>
/// <param name="argumentCount">Number of arguments in the set.</param>
/// <returns>Encoder of the arguments of the set.</returns>
public NamedArgumentsEncoder PermissionSetArguments(int argumentCount)
{
if (unchecked((uint)argumentCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(argumentCount));
}
Builder.WriteCompressedInteger(argumentCount);
return new NamedArgumentsEncoder(Builder);
}
}
public readonly struct MethodSignatureEncoder
{
public BlobBuilder Builder { get; }
public bool HasVarArgs { get; }
public MethodSignatureEncoder(BlobBuilder builder, bool hasVarArgs)
{
Builder = builder;
HasVarArgs = hasVarArgs;
}
/// <summary>
/// Encodes return type and parameters.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="parameterCount">Number of parameters.</param>
/// <param name="returnType">Use first, to encode the return types.</param>
/// <param name="parameters">Use second, to encode the actual parameters.</param>
public void Parameters(int parameterCount, out ReturnTypeEncoder returnType, out ParametersEncoder parameters)
{
if (unchecked((uint)parameterCount) > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.ArgumentOutOfRange(nameof(parameterCount));
}
Builder.WriteCompressedInteger(parameterCount);
returnType = new ReturnTypeEncoder(Builder);
parameters = new ParametersEncoder(Builder, hasVarArgs: HasVarArgs);
}
/// <summary>
/// Encodes return type and parameters.
/// </summary>
/// <param name="parameterCount">Number of parameters.</param>
/// <param name="returnType">Called first, to encode the return type.</param>
/// <param name="parameters">Called second, to encode the actual parameters.</param>
/// <exception cref="ArgumentNullException"><paramref name="returnType"/> or <paramref name="parameters"/> is null.</exception>
public void Parameters(int parameterCount, Action<ReturnTypeEncoder> returnType, Action<ParametersEncoder> parameters)
{
if (returnType == null) Throw.ArgumentNull(nameof(returnType));
if (parameters == null) Throw.ArgumentNull(nameof(parameters));
ReturnTypeEncoder returnTypeEncoder;
ParametersEncoder parametersEncoder;
Parameters(parameterCount, out returnTypeEncoder, out parametersEncoder);
returnType(returnTypeEncoder);
parameters(parametersEncoder);
}
}
public readonly struct LocalVariablesEncoder
{
public BlobBuilder Builder { get; }
public LocalVariablesEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LocalVariableTypeEncoder AddVariable()
{
return new LocalVariableTypeEncoder(Builder);
}
}
public readonly struct LocalVariableTypeEncoder
{
public BlobBuilder Builder { get; }
public LocalVariableTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false, bool isPinned = false)
{
if (isPinned)
{
Builder.WriteByte((byte)SignatureTypeCode.Pinned);
}
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
}
public readonly struct ParameterTypeEncoder
{
public BlobBuilder Builder { get; }
public ParameterTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false)
{
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
}
public readonly struct PermissionSetEncoder
{
public BlobBuilder Builder { get; }
public PermissionSetEncoder(BlobBuilder builder)
{
Builder = builder;
}
public PermissionSetEncoder AddPermission(string typeName, ImmutableArray<byte> encodedArguments)
{
if (typeName == null)
{
Throw.ArgumentNull(nameof(typeName));
}
if (encodedArguments.IsDefault)
{
Throw.ArgumentNull(nameof(encodedArguments));
}
if (encodedArguments.Length > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.BlobTooLarge(nameof(encodedArguments));
}
Builder.WriteSerializedString(typeName);
Builder.WriteCompressedInteger(encodedArguments.Length);
Builder.WriteBytes(encodedArguments);
return this;
}
public PermissionSetEncoder AddPermission(string typeName, BlobBuilder encodedArguments)
{
if (typeName == null)
{
Throw.ArgumentNull(nameof(typeName));
}
if (encodedArguments == null)
{
Throw.ArgumentNull(nameof(encodedArguments));
}
if (encodedArguments.Count > BlobWriterImpl.MaxCompressedIntegerValue)
{
Throw.BlobTooLarge(nameof(encodedArguments));
}
Builder.WriteSerializedString(typeName);
Builder.WriteCompressedInteger(encodedArguments.Count);
encodedArguments.WriteContentTo(Builder);
return this;
}
}
public readonly struct GenericTypeArgumentsEncoder
{
public BlobBuilder Builder { get; }
public GenericTypeArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public SignatureTypeEncoder AddArgument()
{
return new SignatureTypeEncoder(Builder);
}
}
public readonly struct FixedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public FixedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralEncoder AddArgument()
{
return new LiteralEncoder(Builder);
}
}
public readonly struct LiteralEncoder
{
public BlobBuilder Builder { get; }
public LiteralEncoder(BlobBuilder builder)
{
Builder = builder;
}
public VectorEncoder Vector()
{
return new VectorEncoder(Builder);
}
/// <summary>
/// Encodes the type and the items of a vector literal.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="arrayType">Use first, to encode the type of the vector.</param>
/// <param name="vector">Use second, to encode the items of the vector.</param>
public void TaggedVector(out CustomAttributeArrayTypeEncoder arrayType, out VectorEncoder vector)
{
arrayType = new CustomAttributeArrayTypeEncoder(Builder);
vector = new VectorEncoder(Builder);
}
/// <summary>
/// Encodes the type and the items of a vector literal.
/// </summary>
/// <param name="arrayType">Called first, to encode the type of the vector.</param>
/// <param name="vector">Called second, to encode the items of the vector.</param>
/// <exception cref="ArgumentNullException"><paramref name="arrayType"/> or <paramref name="vector"/> is null.</exception>
public void TaggedVector(Action<CustomAttributeArrayTypeEncoder> arrayType, Action<VectorEncoder> vector)
{
if (arrayType == null) Throw.ArgumentNull(nameof(arrayType));
if (vector == null) Throw.ArgumentNull(nameof(vector));
CustomAttributeArrayTypeEncoder arrayTypeEncoder;
VectorEncoder vectorEncoder;
TaggedVector(out arrayTypeEncoder, out vectorEncoder);
arrayType(arrayTypeEncoder);
vector(vectorEncoder);
}
/// <summary>
/// Encodes a scalar literal.
/// </summary>
/// <returns>Encoder of the literal value.</returns>
public ScalarEncoder Scalar()
{
return new ScalarEncoder(Builder);
}
/// <summary>
/// Encodes the type and the value of a literal.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="type">Called first, to encode the type of the literal.</param>
/// <param name="scalar">Called second, to encode the value of the literal.</param>
public void TaggedScalar(out CustomAttributeElementTypeEncoder type, out ScalarEncoder scalar)
{
type = new CustomAttributeElementTypeEncoder(Builder);
scalar = new ScalarEncoder(Builder);
}
/// <summary>
/// Encodes the type and the value of a literal.
/// </summary>
/// <param name="type">Called first, to encode the type of the literal.</param>
/// <param name="scalar">Called second, to encode the value of the literal.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/> or <paramref name="scalar"/> is null.</exception>
public void TaggedScalar(Action<CustomAttributeElementTypeEncoder> type, Action<ScalarEncoder> scalar)
{
if (type == null) Throw.ArgumentNull(nameof(type));
if (scalar == null) Throw.ArgumentNull(nameof(scalar));
CustomAttributeElementTypeEncoder typeEncoder;
ScalarEncoder scalarEncoder;
TaggedScalar(out typeEncoder, out scalarEncoder);
type(typeEncoder);
scalar(scalarEncoder);
}
}
public readonly struct ScalarEncoder
{
public BlobBuilder Builder { get; }
public ScalarEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes <c>null</c> literal of type <see cref="Array"/>.
/// </summary>
public void NullArray()
{
Builder.WriteInt32(-1);
}
/// <summary>
/// Encodes constant literal.
/// </summary>
/// <param name="value">
/// Constant of type
/// <see cref="bool"/>,
/// <see cref="byte"/>,
/// <see cref="sbyte"/>,
/// <see cref="short"/>,
/// <see cref="ushort"/>,
/// <see cref="int"/>,
/// <see cref="uint"/>,
/// <see cref="long"/>,
/// <see cref="ulong"/>,
/// <see cref="float"/>,
/// <see cref="double"/>,
/// <see cref="char"/> (encoded as two-byte Unicode character),
/// <see cref="string"/> (encoded as SerString), or
/// <see cref="Enum"/> (encoded as the underlying integer value).
/// </param>
/// <exception cref="ArgumentException">Unexpected constant type.</exception>
public void Constant(object value)
{
string str = value as string;
if (str != null || value == null)
{
String(str);
}
else
{
Builder.WriteConstant(value);
}
}
/// <summary>
/// Encodes literal of type <see cref="Type"/> (possibly null).
/// </summary>
/// <param name="serializedTypeName">The name of the type, or null.</param>
/// <exception cref="ArgumentException"><paramref name="serializedTypeName"/> is empty.</exception>
public void SystemType(string serializedTypeName)
{
if (serializedTypeName != null && serializedTypeName.Length == 0)
{
Throw.ArgumentEmptyString(nameof(serializedTypeName));
}
String(serializedTypeName);
}
private void String(string value)
{
Builder.WriteSerializedString(value);
}
}
public readonly struct LiteralsEncoder
{
public BlobBuilder Builder { get; }
public LiteralsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralEncoder AddLiteral()
{
return new LiteralEncoder(Builder);
}
}
public readonly struct VectorEncoder
{
public BlobBuilder Builder { get; }
public VectorEncoder(BlobBuilder builder)
{
Builder = builder;
}
public LiteralsEncoder Count(int count)
{
if (count < 0)
{
Throw.ArgumentOutOfRange(nameof(count));
}
Builder.WriteUInt32((uint)count);
return new LiteralsEncoder(Builder);
}
}
public readonly struct NameEncoder
{
public BlobBuilder Builder { get; }
public NameEncoder(BlobBuilder builder)
{
Builder = builder;
}
public void Name(string name)
{
if (name == null) Throw.ArgumentNull(nameof(name));
if (name.Length == 0) Throw.ArgumentEmptyString(nameof(name));
Builder.WriteSerializedString(name);
}
}
public readonly struct CustomAttributeNamedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeNamedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
public NamedArgumentsEncoder Count(int count)
{
if (unchecked((uint)count) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(count));
}
Builder.WriteUInt16((ushort)count);
return new NamedArgumentsEncoder(Builder);
}
}
public readonly struct NamedArgumentsEncoder
{
public BlobBuilder Builder { get; }
public NamedArgumentsEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes a named argument (field or property).
/// Returns a triplet of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="isField">True to encode a field, false to encode a property.</param>
/// <param name="type">Use first, to encode the type of the argument.</param>
/// <param name="name">Use second, to encode the name of the field or property.</param>
/// <param name="literal">Use third, to encode the literal value of the argument.</param>
public void AddArgument(bool isField, out NamedArgumentTypeEncoder type, out NameEncoder name, out LiteralEncoder literal)
{
Builder.WriteByte(isField ? (byte)CustomAttributeNamedArgumentKind.Field : (byte)CustomAttributeNamedArgumentKind.Property);
type = new NamedArgumentTypeEncoder(Builder);
name = new NameEncoder(Builder);
literal = new LiteralEncoder(Builder);
}
/// <summary>
/// Encodes a named argument (field or property).
/// </summary>
/// <param name="isField">True to encode a field, false to encode a property.</param>
/// <param name="type">Called first, to encode the type of the argument.</param>
/// <param name="name">Called second, to encode the name of the field or property.</param>
/// <param name="literal">Called third, to encode the literal value of the argument.</param>
/// <exception cref="ArgumentNullException"><paramref name="type"/>, <paramref name="name"/> or <paramref name="literal"/> is null.</exception>
public void AddArgument(bool isField, Action<NamedArgumentTypeEncoder> type, Action<NameEncoder> name, Action<LiteralEncoder> literal)
{
if (type == null) Throw.ArgumentNull(nameof(type));
if (name == null) Throw.ArgumentNull(nameof(name));
if (literal == null) Throw.ArgumentNull(nameof(literal));
NamedArgumentTypeEncoder typeEncoder;
NameEncoder nameEncoder;
LiteralEncoder literalEncoder;
AddArgument(isField, out typeEncoder, out nameEncoder, out literalEncoder);
type(typeEncoder);
name(nameEncoder);
literal(literalEncoder);
}
}
public readonly struct NamedArgumentTypeEncoder
{
public BlobBuilder Builder { get; }
public NamedArgumentTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomAttributeElementTypeEncoder ScalarType()
{
return new CustomAttributeElementTypeEncoder(Builder);
}
public void Object()
{
Builder.WriteByte((byte)SerializationTypeCode.TaggedObject);
}
public CustomAttributeArrayTypeEncoder SZArray()
{
return new CustomAttributeArrayTypeEncoder(Builder);
}
}
public readonly struct CustomAttributeArrayTypeEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeArrayTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public void ObjectArray()
{
Builder.WriteByte((byte)SerializationTypeCode.SZArray);
Builder.WriteByte((byte)SerializationTypeCode.TaggedObject);
}
public CustomAttributeElementTypeEncoder ElementType()
{
Builder.WriteByte((byte)SerializationTypeCode.SZArray);
return new CustomAttributeElementTypeEncoder(Builder);
}
}
public readonly struct CustomAttributeElementTypeEncoder
{
public BlobBuilder Builder { get; }
public CustomAttributeElementTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
private void WriteTypeCode(SerializationTypeCode value)
{
Builder.WriteByte((byte)value);
}
public void Boolean() => WriteTypeCode(SerializationTypeCode.Boolean);
public void Char() => WriteTypeCode(SerializationTypeCode.Char);
public void SByte() => WriteTypeCode(SerializationTypeCode.SByte);
public void Byte() => WriteTypeCode(SerializationTypeCode.Byte);
public void Int16() => WriteTypeCode(SerializationTypeCode.Int16);
public void UInt16() => WriteTypeCode(SerializationTypeCode.UInt16);
public void Int32() => WriteTypeCode(SerializationTypeCode.Int32);
public void UInt32() => WriteTypeCode(SerializationTypeCode.UInt32);
public void Int64() => WriteTypeCode(SerializationTypeCode.Int64);
public void UInt64() => WriteTypeCode(SerializationTypeCode.UInt64);
public void Single() => WriteTypeCode(SerializationTypeCode.Single);
public void Double() => WriteTypeCode(SerializationTypeCode.Double);
public void String() => WriteTypeCode(SerializationTypeCode.String);
public void PrimitiveType(PrimitiveSerializationTypeCode type)
{
switch (type)
{
case PrimitiveSerializationTypeCode.Boolean:
case PrimitiveSerializationTypeCode.Byte:
case PrimitiveSerializationTypeCode.SByte:
case PrimitiveSerializationTypeCode.Char:
case PrimitiveSerializationTypeCode.Int16:
case PrimitiveSerializationTypeCode.UInt16:
case PrimitiveSerializationTypeCode.Int32:
case PrimitiveSerializationTypeCode.UInt32:
case PrimitiveSerializationTypeCode.Int64:
case PrimitiveSerializationTypeCode.UInt64:
case PrimitiveSerializationTypeCode.Single:
case PrimitiveSerializationTypeCode.Double:
case PrimitiveSerializationTypeCode.String:
WriteTypeCode((SerializationTypeCode)type);
return;
default:
Throw.ArgumentOutOfRange(nameof(type));
return;
}
}
public void SystemType()
{
WriteTypeCode(SerializationTypeCode.Type);
}
public void Enum(string enumTypeName)
{
if (enumTypeName == null) Throw.ArgumentNull(nameof(enumTypeName));
if (enumTypeName.Length == 0) Throw.ArgumentEmptyString(nameof(enumTypeName));
WriteTypeCode(SerializationTypeCode.Enum);
Builder.WriteSerializedString(enumTypeName);
}
}
public readonly struct SignatureTypeEncoder
{
public BlobBuilder Builder { get; }
public SignatureTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
private void WriteTypeCode(SignatureTypeCode value)
{
Builder.WriteByte((byte)value);
}
private void ClassOrValue(bool isValueType)
{
Builder.WriteByte(isValueType ? (byte)SignatureTypeKind.ValueType : (byte)SignatureTypeKind.Class);
}
public void Boolean() => WriteTypeCode(SignatureTypeCode.Boolean);
public void Char() => WriteTypeCode(SignatureTypeCode.Char);
public void SByte() => WriteTypeCode(SignatureTypeCode.SByte);
public void Byte() => WriteTypeCode(SignatureTypeCode.Byte);
public void Int16() => WriteTypeCode(SignatureTypeCode.Int16);
public void UInt16() => WriteTypeCode(SignatureTypeCode.UInt16);
public void Int32() => WriteTypeCode(SignatureTypeCode.Int32);
public void UInt32() => WriteTypeCode(SignatureTypeCode.UInt32);
public void Int64() => WriteTypeCode(SignatureTypeCode.Int64);
public void UInt64() => WriteTypeCode(SignatureTypeCode.UInt64);
public void Single() => WriteTypeCode(SignatureTypeCode.Single);
public void Double() => WriteTypeCode(SignatureTypeCode.Double);
public void String() => WriteTypeCode(SignatureTypeCode.String);
public void IntPtr() => WriteTypeCode(SignatureTypeCode.IntPtr);
public void UIntPtr() => WriteTypeCode(SignatureTypeCode.UIntPtr);
public void Object() => WriteTypeCode(SignatureTypeCode.Object);
/// <summary>
/// Writes primitive type code.
/// </summary>
/// <param name="type">Any primitive type code except for <see cref="PrimitiveTypeCode.TypedReference"/> and <see cref="PrimitiveTypeCode.Void"/>.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="type"/> is not valid in this context.</exception>
public void PrimitiveType(PrimitiveTypeCode type)
{
switch (type)
{
case PrimitiveTypeCode.Boolean:
case PrimitiveTypeCode.Byte:
case PrimitiveTypeCode.SByte:
case PrimitiveTypeCode.Char:
case PrimitiveTypeCode.Int16:
case PrimitiveTypeCode.UInt16:
case PrimitiveTypeCode.Int32:
case PrimitiveTypeCode.UInt32:
case PrimitiveTypeCode.Int64:
case PrimitiveTypeCode.UInt64:
case PrimitiveTypeCode.Single:
case PrimitiveTypeCode.Double:
case PrimitiveTypeCode.IntPtr:
case PrimitiveTypeCode.UIntPtr:
case PrimitiveTypeCode.String:
case PrimitiveTypeCode.Object:
Builder.WriteByte((byte)type);
return;
case PrimitiveTypeCode.TypedReference:
case PrimitiveTypeCode.Void:
default:
Throw.ArgumentOutOfRange(nameof(type));
return;
}
}
/// <summary>
/// Encodes an array type.
/// Returns a pair of encoders that must be used in the order they appear in the parameter list.
/// </summary>
/// <param name="elementType">Use first, to encode the type of the element.</param>
/// <param name="arrayShape">Use second, to encode the shape of the array.</param>
public void Array(out SignatureTypeEncoder elementType, out ArrayShapeEncoder arrayShape)
{
Builder.WriteByte((byte)SignatureTypeCode.Array);
elementType = this;
arrayShape = new ArrayShapeEncoder(Builder);
}
/// <summary>
/// Encodes an array type.
/// </summary>
/// <param name="elementType">Called first, to encode the type of the element.</param>
/// <param name="arrayShape">Called second, to encode the shape of the array.</param>
/// <exception cref="ArgumentNullException"><paramref name="elementType"/> or <paramref name="arrayShape"/> is null.</exception>
public void Array(Action<SignatureTypeEncoder> elementType, Action<ArrayShapeEncoder> arrayShape)
{
if (elementType == null) Throw.ArgumentNull(nameof(elementType));
if (arrayShape == null) Throw.ArgumentNull(nameof(arrayShape));
SignatureTypeEncoder elementTypeEncoder;
ArrayShapeEncoder arrayShapeEncoder;
Array(out elementTypeEncoder, out arrayShapeEncoder);
elementType(elementTypeEncoder);
arrayShape(arrayShapeEncoder);
}
/// <summary>
/// Encodes a reference to a type.
/// </summary>
/// <param name="type"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param>
/// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param>
/// <exception cref="ArgumentException"><paramref name="type"/> doesn't have the expected handle kind.</exception>
public void Type(EntityHandle type, bool isValueType)
{
// Get the coded index before we start writing anything (might throw argument exception):
// Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change
int codedIndex = CodedIndex.TypeDefOrRef(type);
ClassOrValue(isValueType);
Builder.WriteCompressedInteger(codedIndex);
}
/// <summary>
/// Starts a function pointer signature.
/// </summary>
/// <param name="convention">Calling convention.</param>
/// <param name="attributes">Function pointer attributes.</param>
/// <param name="genericParameterCount">Generic parameter count.</param>
/// <exception cref="ArgumentException"><paramref name="attributes"/> is invalid.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericParameterCount"/> is not in range [0, 0xffff].</exception>
public MethodSignatureEncoder FunctionPointer(
SignatureCallingConvention convention = SignatureCallingConvention.Default,
FunctionPointerAttributes attributes = FunctionPointerAttributes.None,
int genericParameterCount = 0)
{
// Spec:
// The EXPLICITTHIS (0x40) bit can be set only in signatures for function pointers.
// If EXPLICITTHIS (0x40) in the signature is set, then HASTHIS (0x20) shall also be set.
if (attributes != FunctionPointerAttributes.None &&
attributes != FunctionPointerAttributes.HasThis &&
attributes != FunctionPointerAttributes.HasExplicitThis)
{
throw new ArgumentException(SR.InvalidSignature, nameof(attributes));
}
if (unchecked((uint)genericParameterCount) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(genericParameterCount));
}
Builder.WriteByte((byte)SignatureTypeCode.FunctionPointer);
Builder.WriteByte(new SignatureHeader(SignatureKind.Method, convention, (SignatureAttributes)attributes).RawValue);
if (genericParameterCount != 0)
{
Builder.WriteCompressedInteger(genericParameterCount);
}
return new MethodSignatureEncoder(Builder, hasVarArgs: convention == SignatureCallingConvention.VarArgs);
}
/// <summary>
/// Starts a generic instantiation signature.
/// </summary>
/// <param name="genericType"><see cref="TypeDefinitionHandle"/> or <see cref="TypeReferenceHandle"/>.</param>
/// <param name="genericArgumentCount">Generic argument count.</param>
/// <param name="isValueType">True to mark the type as value type, false to mark it as a reference type in the signature.</param>
/// <exception cref="ArgumentException"><paramref name="genericType"/> doesn't have the expected handle kind.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="genericArgumentCount"/> is not in range [1, 0xffff].</exception>
public GenericTypeArgumentsEncoder GenericInstantiation(EntityHandle genericType, int genericArgumentCount, bool isValueType)
{
if (unchecked((uint)(genericArgumentCount - 1)) > ushort.MaxValue - 1)
{
Throw.ArgumentOutOfRange(nameof(genericArgumentCount));
}
// Get the coded index before we start writing anything (might throw argument exception):
// Note: We don't allow TypeSpec as per https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/specs/Ecma-335-Issues.md#proposed-specification-change
int codedIndex = CodedIndex.TypeDefOrRef(genericType);
Builder.WriteByte((byte)SignatureTypeCode.GenericTypeInstance);
ClassOrValue(isValueType);
Builder.WriteCompressedInteger(codedIndex);
Builder.WriteCompressedInteger(genericArgumentCount);
return new GenericTypeArgumentsEncoder(Builder);
}
/// <summary>
/// Encodes a reference to type parameter of a containing generic method.
/// </summary>
/// <param name="parameterIndex">Parameter index.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception>
public void GenericMethodTypeParameter(int parameterIndex)
{
if (unchecked((uint)parameterIndex) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(parameterIndex));
}
Builder.WriteByte((byte)SignatureTypeCode.GenericMethodParameter);
Builder.WriteCompressedInteger(parameterIndex);
}
/// <summary>
/// Encodes a reference to type parameter of a containing generic type.
/// </summary>
/// <param name="parameterIndex">Parameter index.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="parameterIndex"/> is not in range [0, 0xffff].</exception>
public void GenericTypeParameter(int parameterIndex)
{
if (unchecked((uint)parameterIndex) > ushort.MaxValue)
{
Throw.ArgumentOutOfRange(nameof(parameterIndex));
}
Builder.WriteByte((byte)SignatureTypeCode.GenericTypeParameter);
Builder.WriteCompressedInteger(parameterIndex);
}
/// <summary>
/// Starts pointer signature.
/// </summary>
public SignatureTypeEncoder Pointer()
{
Builder.WriteByte((byte)SignatureTypeCode.Pointer);
return this;
}
/// <summary>
/// Encodes <code>void*</code>.
/// </summary>
public void VoidPointer()
{
Builder.WriteByte((byte)SignatureTypeCode.Pointer);
Builder.WriteByte((byte)SignatureTypeCode.Void);
}
/// <summary>
/// Starts SZ array (vector) signature.
/// </summary>
public SignatureTypeEncoder SZArray()
{
Builder.WriteByte((byte)SignatureTypeCode.SZArray);
return this;
}
/// <summary>
/// Starts a signature of a type with custom modifiers.
/// </summary>
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
}
public readonly struct CustomModifiersEncoder
{
public BlobBuilder Builder { get; }
public CustomModifiersEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes a custom modifier.
/// </summary>
/// <param name="type"><see cref="TypeDefinitionHandle"/>, <see cref="TypeReferenceHandle"/> or <see cref="TypeSpecificationHandle"/>.</param>
/// <param name="isOptional">Is optional modifier.</param>
/// <returns>Encoder of subsequent modifiers.</returns>
/// <exception cref="ArgumentException"><paramref name="type"/> is nil or of an unexpected kind.</exception>
public CustomModifiersEncoder AddModifier(EntityHandle type, bool isOptional)
{
if (type.IsNil)
{
Throw.InvalidArgument_Handle(nameof(type));
}
if (isOptional)
{
Builder.WriteByte((byte)SignatureTypeCode.OptionalModifier);
}
else
{
Builder.WriteByte((byte)SignatureTypeCode.RequiredModifier);
}
Builder.WriteCompressedInteger(CodedIndex.TypeDefOrRefOrSpec(type));
return this;
}
}
public readonly struct ArrayShapeEncoder
{
public BlobBuilder Builder { get; }
public ArrayShapeEncoder(BlobBuilder builder)
{
Builder = builder;
}
/// <summary>
/// Encodes array shape.
/// </summary>
/// <param name="rank">The number of dimensions in the array (shall be 1 or more).</param>
/// <param name="sizes">
/// Dimension sizes. The array may be shorter than <paramref name="rank"/> but not longer.
/// </param>
/// <param name="lowerBounds">
/// Dimension lower bounds, or <c>default(<see cref="ImmutableArray{Int32}"/>)</c> to set all <paramref name="rank"/> lower bounds to 0.
/// The array may be shorter than <paramref name="rank"/> but not longer.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="rank"/> is outside of range [1, 0xffff],
/// smaller than <paramref name="sizes"/>.Length, or
/// smaller than <paramref name="lowerBounds"/>.Length.
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="sizes"/> is null.</exception>
public void Shape(int rank, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds)
{
// The specification doesn't impose a limit on the max number of array dimensions.
// The CLR supports <64. More than 0xffff is causing crashes in various tools (ildasm).
if (unchecked((uint)(rank - 1)) > ushort.MaxValue - 1)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
if (sizes.IsDefault)
{
Throw.ArgumentNull(nameof(sizes));
}
// rank
Builder.WriteCompressedInteger(rank);
// sizes
if (sizes.Length > rank)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
Builder.WriteCompressedInteger(sizes.Length);
foreach (int size in sizes)
{
Builder.WriteCompressedInteger(size);
}
// lower bounds
if (lowerBounds.IsDefault) // TODO: remove -- update Roslyn
{
Builder.WriteCompressedInteger(rank);
for (int i = 0; i < rank; i++)
{
Builder.WriteCompressedSignedInteger(0);
}
}
else
{
if (lowerBounds.Length > rank)
{
Throw.ArgumentOutOfRange(nameof(rank));
}
Builder.WriteCompressedInteger(lowerBounds.Length);
foreach (int lowerBound in lowerBounds)
{
Builder.WriteCompressedSignedInteger(lowerBound);
}
}
}
}
public readonly struct ReturnTypeEncoder
{
public BlobBuilder Builder { get; }
public ReturnTypeEncoder(BlobBuilder builder)
{
Builder = builder;
}
public CustomModifiersEncoder CustomModifiers()
{
return new CustomModifiersEncoder(Builder);
}
public SignatureTypeEncoder Type(bool isByRef = false)
{
if (isByRef)
{
Builder.WriteByte((byte)SignatureTypeCode.ByReference);
}
return new SignatureTypeEncoder(Builder);
}
public void TypedReference()
{
Builder.WriteByte((byte)SignatureTypeCode.TypedReference);
}
public void Void()
{
Builder.WriteByte((byte)SignatureTypeCode.Void);
}
}
public readonly struct ParametersEncoder
{
public BlobBuilder Builder { get; }
public bool HasVarArgs { get; }
public ParametersEncoder(BlobBuilder builder, bool hasVarArgs = false)
{
Builder = builder;
HasVarArgs = hasVarArgs;
}
public ParameterTypeEncoder AddParameter()
{
return new ParameterTypeEncoder(Builder);
}
public ParametersEncoder StartVarArgs()
{
if (!HasVarArgs)
{
Throw.SignatureNotVarArg();
}
Builder.WriteByte((byte)SignatureTypeCode.Sentinel);
return new ParametersEncoder(Builder, hasVarArgs: false);
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
namespace DBus
{
using Protocol;
public class BusObject
{
static Dictionary<object,BusObject> boCache = new Dictionary<object,BusObject>();
protected Connection conn;
string bus_name;
ObjectPath object_path;
public BusObject ()
{
}
public BusObject (Connection conn, string bus_name, ObjectPath object_path)
{
this.conn = conn;
this.bus_name = bus_name;
this.object_path = object_path;
}
public Connection Connection
{
get {
return conn;
}
}
public string BusName
{
get {
return bus_name;
}
}
public ObjectPath Path
{
get {
return object_path;
}
}
public void ToggleSignal (string iface, string member, Delegate dlg, bool adding)
{
MatchRule rule = new MatchRule ();
rule.MessageType = MessageType.Signal;
rule.Fields.Add (FieldCode.Interface, new MatchTest (iface));
rule.Fields.Add (FieldCode.Member, new MatchTest (member));
rule.Fields.Add (FieldCode.Path, new MatchTest (object_path));
// FIXME: Cause a regression compared to 0.6 as name wasn't matched before
// the problem arises because busname is not used by DBus daemon and
// instead it uses the canonical name of the sender (i.e. similar to ':1.13')
// rule.Fields.Add (FieldCode.Sender, new MatchTest (bus_name));
if (adding) {
if (conn.Handlers.ContainsKey (rule))
conn.Handlers[rule] = Delegate.Combine (conn.Handlers[rule], dlg);
else {
conn.Handlers[rule] = dlg;
conn.AddMatch (rule.ToString ());
}
} else if (conn.Handlers.ContainsKey (rule)) {
conn.Handlers[rule] = Delegate.Remove (conn.Handlers[rule], dlg);
if (conn.Handlers[rule] == null) {
conn.RemoveMatch (rule.ToString ());
conn.Handlers.Remove (rule);
}
}
}
public void SendSignal (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
SendSignal (iface, member, inSigStr, writer, retType, null, out exception);
}
internal void SendSignal (string iface, string member, string inSigStr, MessageWriter writer, Type retType, DisposableList disposableList, out Exception exception)
{
exception = null;
Signature outSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer signal = new MessageContainer {
Type = MessageType.Signal,
Path = object_path,
Interface = iface,
Member = member,
Signature = outSig,
};
Message signalMsg = signal.Message;
signalMsg.AttachBodyTo (writer);
conn.Send (signalMsg);
}
public MessageReader SendMethodCall (string iface, string member, string inSigStr, MessageWriter writer, Type retType, out Exception exception)
{
return SendMethodCall (iface, member, inSigStr, writer, retType, null, out exception);
}
public MessageReader SendMethodCall (string iface, string member, string inSigStr, MessageWriter writer, Type retType, DisposableList disposableList, out Exception exception)
{
if (string.IsNullOrEmpty (bus_name))
throw new ArgumentNullException ("bus_name");
if (object_path == null)
throw new ArgumentNullException ("object_path");
exception = null;
Signature inSig = String.IsNullOrEmpty (inSigStr) ? Signature.Empty : new Signature (inSigStr);
MessageContainer method_call = new MessageContainer {
Path = object_path,
Interface = iface,
Member = member,
Destination = bus_name,
Signature = inSig
};
Message callMsg = method_call.Message;
callMsg.AttachBodyTo (writer);
bool needsReply = true;
callMsg.ReplyExpected = needsReply;
callMsg.Signature = inSig;
if (!needsReply) {
conn.Send (callMsg);
return null;
}
#if PROTO_REPLY_SIGNATURE
if (needsReply) {
Signature outSig = Signature.GetSig (retType);
callMsg.Header[FieldCode.ReplySignature] = outSig;
}
#endif
Message retMsg = conn.SendWithReplyAndBlock (callMsg, disposableList != null);
if (disposableList != null && retMsg.UnixFDArray != null)
foreach (var fd in retMsg.UnixFDArray.FDs)
disposableList.Add (fd);
MessageReader retVal = null;
//handle the reply message
switch (retMsg.Header.MessageType) {
case MessageType.MethodReturn:
retVal = new MessageReader (retMsg);
break;
case MessageType.Error:
MessageContainer error = MessageContainer.FromMessage (retMsg);
string errMsg = String.Empty;
if (retMsg.Signature.Value.StartsWith ("s")) {
MessageReader reader = new MessageReader (retMsg);
errMsg = reader.ReadString ();
}
exception = new Exception (error.ErrorName + ": " + errMsg);
break;
default:
throw new Exception ("Got unexpected message of type " + retMsg.Header.MessageType + " while waiting for a MethodReturn or Error");
}
return retVal;
}
public void Invoke (MethodBase methodBase, string methodName, object[] inArgs, out object[] outArgs, out object retVal, out Exception exception)
{
Invoke (methodBase, methodName, inArgs, null, out outArgs, out retVal, out exception);
}
public void Invoke (MethodBase methodBase, string methodName, object[] inArgs, DisposableList disposableList, out object[] outArgs, out object retVal, out Exception exception)
{
outArgs = new object[0];
retVal = null;
exception = null;
MethodInfo mi = methodBase as MethodInfo;
if (mi != null && mi.IsSpecialName && (methodName.StartsWith ("add_") || methodName.StartsWith ("remove_"))) {
string[] parts = methodName.Split (new char[]{'_'}, 2);
string ename = parts[1];
Delegate dlg = (Delegate)inArgs[0];
ToggleSignal (Mapper.GetInterfaceName (mi), ename, dlg, parts[0] == "add");
return;
}
Type[] inTypes = Mapper.GetTypes (ArgDirection.In, mi.GetParameters ());
Signature inSig = Signature.GetSig (inTypes);
string iface = null;
if (mi != null)
iface = Mapper.GetInterfaceName (mi);
if (mi != null && mi.IsSpecialName) {
methodName = methodName.Replace ("get_", "Get");
methodName = methodName.Replace ("set_", "Set");
}
MessageWriter writer = new MessageWriter (conn);
if (inArgs != null && inArgs.Length != 0) {
for (int i = 0 ; i != inTypes.Length ; i++)
writer.Write (inTypes[i], inArgs[i]);
}
MessageReader reader = SendMethodCall (iface, methodName, inSig.Value, writer, mi.ReturnType, out exception);
if (reader == null)
return;
retVal = reader.ReadValue (mi.ReturnType);
}
public static object GetObject (Connection conn, string bus_name, ObjectPath object_path, Type declType)
{
Type proxyType = TypeImplementer.Root.GetImplementation (declType);
object instObj = Activator.CreateInstance (proxyType);
BusObject inst = GetBusObject (instObj);
inst.conn = conn;
inst.bus_name = bus_name;
inst.object_path = object_path;
return instObj;
}
public static BusObject GetBusObject (object instObj)
{
if (instObj is BusObject)
return (BusObject)instObj;
BusObject inst;
if (boCache.TryGetValue (instObj, out inst))
return inst;
inst = new BusObject ();
boCache[instObj] = inst;
return inst;
}
public Delegate GetHookupDelegate (EventInfo ei)
{
DynamicMethod hookupMethod = TypeImplementer.GetHookupMethod (ei);
Delegate d = hookupMethod.CreateDelegate (ei.EventHandlerType, this);
return d;
}
}
}
| |
// 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.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows.Media;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.Internal.VisualStudio.PlatformUI;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.SolutionExplorer
{
internal sealed partial class DiagnosticItem : BaseItem
{
private readonly DiagnosticDescriptor _descriptor;
private ReportDiagnostic _effectiveSeverity;
private readonly AnalyzerItem _analyzerItem;
private static readonly ContextMenuController s_diagnosticContextMenuController =
new ContextMenuController(
ID.RoslynCommands.DiagnosticContextMenu,
items => items.All(item => item is DiagnosticItem));
public override event PropertyChangedEventHandler PropertyChanged;
public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity)
: base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
{
_analyzerItem = analyzerItem;
_descriptor = descriptor;
_effectiveSeverity = effectiveSeverity;
}
public override ImageMoniker IconMoniker
{
get
{
return MapEffectiveSeverityToIconMoniker(_effectiveSeverity);
}
}
public AnalyzerItem AnalyzerItem
{
get
{
return _analyzerItem;
}
}
public DiagnosticDescriptor Descriptor
{
get
{
return _descriptor;
}
}
public ReportDiagnostic EffectiveSeverity
{
get
{
return _effectiveSeverity;
}
}
public override object GetBrowseObject()
{
return new BrowseObject(this);
}
public override IContextMenuController ContextMenuController
{
get
{
return s_diagnosticContextMenuController;
}
}
internal void UpdateEffectiveSeverity(ReportDiagnostic newEffectiveSeverity)
{
if (_effectiveSeverity != newEffectiveSeverity)
{
_effectiveSeverity = newEffectiveSeverity;
NotifyPropertyChanged(nameof(EffectiveSeverity));
NotifyPropertyChanged(nameof(IconMoniker));
}
}
private ImageMoniker MapEffectiveSeverityToIconMoniker(ReportDiagnostic effectiveSeverity)
{
switch (effectiveSeverity)
{
case ReportDiagnostic.Error:
return KnownMonikers.CodeErrorRule;
case ReportDiagnostic.Warn:
return KnownMonikers.CodeWarningRule;
case ReportDiagnostic.Info:
return KnownMonikers.CodeInformationRule;
case ReportDiagnostic.Hidden:
return KnownMonikers.CodeHiddenRule;
case ReportDiagnostic.Suppress:
return KnownMonikers.CodeSuppressedRule;
default:
return default(ImageMoniker);
}
}
private void NotifyPropertyChanged(string propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
internal void SetSeverity(ReportDiagnostic value, string pathToRuleSet)
{
UpdateRuleSetFile(pathToRuleSet, value);
}
private void UpdateRuleSetFile(string pathToRuleSet, ReportDiagnostic value)
{
var ruleSetDocument = XDocument.Load(pathToRuleSet);
var newAction = ConvertReportDiagnosticToAction(value);
var analyzerID = _analyzerItem.AnalyzerReference.Display;
var rules = FindOrCreateRulesElement(ruleSetDocument, analyzerID);
var rule = FindOrCreateRuleElement(rules, _descriptor.Id);
rule.Attribute("Action").Value = newAction;
var allMatchingRules = ruleSetDocument.Root
.Descendants("Rule")
.Where(r => r.Attribute("Id").Value.Equals(_descriptor.Id));
foreach (var matchingRule in allMatchingRules)
{
matchingRule.Attribute("Action").Value = newAction;
}
ruleSetDocument.Save(pathToRuleSet);
}
private XElement FindOrCreateRuleElement(XElement rules, string id)
{
var ruleElement = rules
.Elements("Rule")
.FirstOrDefault(r => r.Attribute("Id").Value.Equals(id));
if (ruleElement == null)
{
ruleElement = new XElement("Rule",
new XAttribute("Id", id),
new XAttribute("Action", "Warning"));
rules.Add(ruleElement);
}
return ruleElement;
}
private XElement FindOrCreateRulesElement(XDocument ruleSetDocument, string analyzerID)
{
var rulesElement = ruleSetDocument.Root
.Elements("Rules")
.FirstOrDefault(r => r.Attribute("AnalyzerId").Value.Equals(analyzerID));
if (rulesElement == null)
{
rulesElement = new XElement("Rules",
new XAttribute("AnalyzerId", analyzerID),
new XAttribute("RuleNamespace", analyzerID));
ruleSetDocument.Root.Add(rulesElement);
}
return rulesElement;
}
private static string ConvertReportDiagnosticToAction(ReportDiagnostic value)
{
switch (value)
{
case ReportDiagnostic.Default:
return "Default";
case ReportDiagnostic.Error:
return "Error";
case ReportDiagnostic.Warn:
return "Warning";
case ReportDiagnostic.Info:
return "Info";
case ReportDiagnostic.Hidden:
return "Hidden";
case ReportDiagnostic.Suppress:
return "None";
default:
throw ExceptionUtilities.Unreachable;
}
}
}
}
| |
//! \file ArcBDF.cs
//! \date Sun Aug 23 03:17:14 2015
//! \brief Zyx multi-frame image package.
//
// Copyright (C) 2015 by morkt
//
// 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.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using System.Linq;
using System.Windows.Media;
using GameRes.Utility;
namespace GameRes.Formats.Zyx
{
internal class BdfFrame : Entry
{
public int Number;
public int Width;
public int Height;
public bool Incremental;
}
internal class BdfArchive : ArcFile
{
public byte[] FirstFrame;
public ImageMetaData Info { get; private set; }
public BdfArchive (ArcView arc, ArchiveFormat impl, ICollection<Entry> dir)
: base (arc, impl, dir)
{
var base_frame = dir.First() as BdfFrame;
Info = new ImageMetaData {
Width = (uint)base_frame.Width,
Height = (uint)base_frame.Height,
BPP = 24
};
}
public byte[] ReadFrame (BdfFrame frame)
{
byte[] pixels;
if (!frame.Incremental)
{
if (null != FirstFrame && 0 == frame.Number)
return FirstFrame;
pixels = new byte[frame.Width * frame.Height * 3];
using (var input = File.CreateStream (frame.Offset, frame.Size))
DecodeFrame (input, pixels);
if (null == FirstFrame && 0 == frame.Number)
FirstFrame = pixels;
}
else
{
if (null == FirstFrame)
{
var base_frame = Dir.First() as BdfFrame;
FirstFrame = new byte[base_frame.Width * base_frame.Height * 3];
using (var input = File.CreateStream (base_frame.Offset, base_frame.Size))
DecodeFrame (input, FirstFrame);
}
pixels = FirstFrame.Clone() as byte[];
int i = 1;
foreach (BdfFrame entry in Dir.Skip(1))
{
if (i++ > frame.Number)
break;
using (var input = File.CreateStream (entry.Offset, entry.Size))
DecodeFrame (input, pixels, entry.Incremental);
}
}
return pixels;
}
private void DecodeFrame (IBinaryStream input, byte[] output, bool incremental = false)
{
int v2 = incremental ? 6 : 4;
int dst = 0;
while (dst < output.Length)
{
int count, offset;
int cmd = input.ReadByte();
if (-1 == cmd)
break;
switch (cmd)
{
case 0:
{
int src = dst-3;
count = input.ReadByte();
for (int i = 0; i < count; ++i)
{
output[dst++] = output[src];
output[dst++] = output[src+1];
output[dst++] = output[src+2];
}
break;
}
case 1:
{
count = 3 * input.ReadByte();
offset = 3 * input.ReadByte();
int src = dst - offset;
Binary.CopyOverlapped (output, src, dst, count);
dst += count;
break;
}
case 2:
{
count = 3 * input.ReadByte();
offset = 3 * input.ReadUInt16();
int src = dst - offset;
Binary.CopyOverlapped (output, src, dst, count);
dst += count;
break;
}
case 3:
{
offset = 3 * input.ReadByte();
int src = dst - offset;
output[dst++] = output[src++];
output[dst++] = output[src++];
output[dst++] = output[src++];
break;
}
case 4:
{
offset = 3 * input.ReadUInt16();
int src = dst - offset;
output[dst++] = output[src++];
output[dst++] = output[src++];
output[dst++] = output[src++];
break;
}
default:
if (v2 < 5 || cmd > 6)
{
count = (cmd - v2) * 3;
input.Read (output, dst, count);
dst += count;
}
else
{
if (5 == cmd)
{
count = input.ReadByte();
}
else
{
count = input.ReadUInt16();
}
dst += 3 * count;
}
break;
}
}
}
}
[Export(typeof(ArchiveFormat))]
public class BdfOpener : ArchiveFormat
{
public override string Tag { get { return "BDF"; } }
public override string Description { get { return "Zyx multi-frame image package"; } }
public override uint Signature { get { return 0; } }
public override bool IsHierarchic { get { return false; } }
public override bool CanWrite { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
int count = file.View.ReadInt32 (0);
if (count <= 0 || count > 100)
return null;
int first_offset = file.View.ReadInt32 (4);
if (0 != first_offset)
return null;
string base_name = Path.GetFileNameWithoutExtension (file.Name);
int base_offset = 4 + count * 0x1C;
int index_offset = 4;
var dir = new List<Entry> (count);
for (int i = 0; i < count; ++i)
{
var entry = new BdfFrame {
Number = i,
Name = string.Format ("{0}#{1:D2}", base_name, i),
Type = "image",
Offset = base_offset + file.View.ReadUInt32 (index_offset),
Size = file.View.ReadUInt32 (index_offset+4),
Incremental = 0 != file.View.ReadInt32 (index_offset+8),
Width = file.View.ReadInt32 (index_offset+0x14),
Height = file.View.ReadInt32 (index_offset+0x18),
};
if (entry.Size > 0)
{
if (entry.Size < 4 || entry.Width <= 0 || entry.Height <= 0
|| !entry.CheckPlacement (file.MaxOffset))
return null;
dir.Add (entry);
}
index_offset += 0x1C;
}
return new BdfArchive (file, this, dir);
}
public override IImageDecoder OpenImage (ArcFile arc, Entry entry)
{
var bdf = arc as BdfArchive;
var frame = entry as BdfFrame;
if (null == bdf || null == frame)
return base.OpenImage (arc, entry);
return new BdfImageDecoder (bdf, frame);
}
}
internal sealed class BdfImageDecoder : BinaryImageDecoder
{
BdfArchive m_bdf;
BdfFrame m_frame;
public BdfImageDecoder (BdfArchive arc, BdfFrame entry)
: base (arc.File.CreateStream (entry.Offset, entry.Size), arc.Info)
{
m_bdf = arc;
m_frame = entry;
}
protected override ImageData GetImageData ()
{
var pixels = m_bdf.ReadFrame (m_frame);
return ImageData.Create (Info, PixelFormats.Bgr24, null, pixels);
}
}
}
| |
/*
* Copyright 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using BitCoinSharp.IO;
using log4net;
namespace BitCoinSharp
{
/// <summary>
/// BitCoin transactions don't specify what they do directly. Instead <a href="https://en.bitcoin.it/wiki/Script">a small binary stack language</a>
/// is used to define programs that when evaluated return whether the transaction
/// "accepts" or rejects the other transactions connected to it.
/// </summary>
/// <remarks>
/// This implementation of the scripting language is incomplete. It contains enough support to run standard
/// transactions generated by the official client, but non-standard transactions will fail.
/// </remarks>
public class Script
{
private static readonly ILog _log = LogManager.GetLogger(typeof (Script));
// Some constants used for decoding the scripts.
public const int OpPushData1 = 76;
public const int OpPushData2 = 77;
public const int OpPushData4 = 78;
public const int OpDup = 118;
public const int OpHash160 = 169;
public const int OpEqualVerify = 136;
public const int OpCheckSig = 172;
private byte[] _program;
private int _cursor;
// The stack consists of an ordered series of data buffers growing from zero up.
private readonly Stack<byte[]> _stack;
// The program is a set of byte[]s where each element is either [opcode] or [data, data, data ...]
private IList<byte[]> _chunks;
private byte[] _programCopy; // TODO: remove this
private readonly NetworkParameters _params;
/// <summary>
/// Concatenates two scripts to form a new one. This is used when verifying transactions.
/// </summary>
/// <exception cref="BitCoinSharp.ScriptException" />
public static Script Join(Script a, Script b)
{
Debug.Assert(a._params == b._params);
var fullProg = new byte[a._programCopy.Length + b._programCopy.Length];
Array.Copy(a._programCopy, 0, fullProg, 0, a._programCopy.Length);
Array.Copy(b._programCopy, 0, fullProg, a._programCopy.Length, b._programCopy.Length);
return new Script(a._params, fullProg, 0, fullProg.Length);
}
/// <summary>
/// Construct a Script using the given network parameters and a range of the programBytes array.
/// </summary>
/// <param name="params">Network parameters.</param>
/// <param name="programBytes">Array of program bytes from a transaction.</param>
/// <param name="offset">How many bytes into programBytes to start reading from.</param>
/// <param name="length">How many bytes to read.</param>
/// <exception cref="BitCoinSharp.ScriptException" />
public Script(NetworkParameters @params, byte[] programBytes, int offset, int length)
{
_params = @params;
_stack = new Stack<byte[]>();
Parse(programBytes, offset, length);
}
/// <summary>
/// If true, running a program will log its instructions.
/// </summary>
public bool Tracing { get; set; }
/// <summary>
/// Returns the program opcodes as a string, for example "[1234] DUP HAHS160"
/// </summary>
public override string ToString()
{
var buf = new StringBuilder();
foreach (var chunk in _chunks)
{
if (chunk.Length == 1)
{
string opName;
var opcode = chunk[0];
switch (opcode)
{
case OpDup:
opName = "DUP";
break;
case OpHash160:
opName = "HASH160";
break;
case OpCheckSig:
opName = "CHECKSIG";
break;
case OpEqualVerify:
opName = "EQUALVERIFY";
break;
default:
opName = "?(" + opcode + ")";
break;
}
buf.Append(opName);
buf.Append(" ");
}
else
{
// Data chunk
buf.Append("[");
buf.Append(chunk.Length);
buf.Append("]");
buf.Append(Utils.BytesToHexString(chunk));
buf.Append(" ");
}
}
return buf.ToString();
}
/// <exception cref="BitCoinSharp.ScriptException" />
private byte[] GetData(int len)
{
try
{
var buf = new byte[len];
Array.Copy(_program, _cursor, buf, 0, len);
_cursor += len;
return buf;
}
catch (IndexOutOfRangeException e)
{
// We want running out of data in the array to be treated as a recoverable script parsing exception,
// not something that abnormally terminates the app.
throw new ScriptException("Failed read of " + len + " bytes", e);
}
}
private byte ReadByte()
{
return _program[_cursor++];
}
/// <summary>
/// To run a script, first we parse it which breaks it up into chunks representing pushes of
/// data or logical opcodes. Then we can run the parsed chunks.
/// </summary>
/// <remarks>
/// The reason for this split, instead of just interpreting directly, is to make it easier
/// to reach into a programs structure and pull out bits of data without having to run it.
/// This is necessary to render the to/from addresses of transactions in a user interface.
/// The official client does something similar.
/// </remarks>
/// <exception cref="BitCoinSharp.ScriptException" />
private void Parse(byte[] programBytes, int offset, int length)
{
// TODO: this is inefficient
_programCopy = new byte[length];
Array.Copy(programBytes, offset, _programCopy, 0, length);
_program = _programCopy;
offset = 0;
_chunks = new List<byte[]>(10); // Arbitrary choice of initial size.
_cursor = offset;
while (_cursor < offset + length)
{
var opcode = (int) ReadByte();
if (opcode >= 0xF0)
{
// Not a single byte opcode.
opcode = (opcode << 8) | ReadByte();
}
if (opcode > 0 && opcode < OpPushData1)
{
// Read some bytes of data, where how many is the opcode value itself.
_chunks.Add(GetData(opcode)); // opcode == len here.
}
else if (opcode == OpPushData1)
{
var len = ReadByte();
_chunks.Add(GetData(len));
}
else if (opcode == OpPushData2)
{
// Read a short, then read that many bytes of data.
var len = ReadByte() | (ReadByte() << 8);
_chunks.Add(GetData(len));
}
else if (opcode == OpPushData4)
{
// Read a uint32, then read that many bytes of data.
_log.Error("PUSHDATA4: Unimplemented");
}
else
{
_chunks.Add(new[] {(byte) opcode});
}
}
}
/// <summary>
/// Returns true if this transaction is of a format that means it was a direct IP to IP transaction. These
/// transactions are deprecated and no longer used, support for creating them has been removed from the official
/// client.
/// </summary>
public bool IsSentToIp
{
get { return _chunks.Count == 2 && (_chunks[1][0] == OpCheckSig && _chunks[0].Length > 1); }
}
/// <summary>
/// If a program matches the standard template DUP HASH160 <pubkey hash> EQUALVERIFY CHECKSIG
/// then this function retrieves the third element, otherwise it throws a ScriptException.
/// </summary>
/// <remarks>
/// This is useful for fetching the destination address of a transaction.
/// </remarks>
/// <exception cref="BitCoinSharp.ScriptException" />
public byte[] PubKeyHash
{
get
{
if (_chunks.Count != 5)
throw new ScriptException("Script not of right size to be a scriptPubKey, " +
"expecting 5 but got " + _chunks.Count);
if (_chunks[0][0] != OpDup ||
_chunks[1][0] != OpHash160 ||
_chunks[3][0] != OpEqualVerify ||
_chunks[4][0] != OpCheckSig)
throw new ScriptException("Script not in the standard scriptPubKey form");
// Otherwise, the third element is the hash of the public key, ie the BitCoin address.
return _chunks[2];
}
}
/// <summary>
/// If a program has two data buffers (constants) and nothing else, the second one is returned.
/// For a scriptSig this should be the public key of the sender.
/// </summary>
/// <remarks>
/// This is useful for fetching the source address of a transaction.
/// </remarks>
/// <exception cref="BitCoinSharp.ScriptException" />
public byte[] PubKey
{
get
{
if (_chunks.Count == 1)
{
// Direct IP to IP transactions only have the public key in their scriptSig.
return _chunks[0];
}
if (_chunks.Count != 2)
throw new ScriptException("Script not of right size to be a scriptSig, expecting 2" +
" but got " + _chunks.Count);
if (!(_chunks[0].Length > 1) && (_chunks[1].Length > 1))
throw new ScriptException("Script not in the standard scriptSig form: " +
_chunks.Count + " chunks");
return _chunks[1];
}
}
/// <summary>
/// Convenience wrapper around getPubKey. Only works for scriptSigs.
/// </summary>
/// <exception cref="BitCoinSharp.ScriptException" />
public Address FromAddress
{
get { return new Address(_params, Utils.Sha256Hash160(PubKey)); }
}
/// <summary>
/// Gets the destination address from this script, if it's in the required form (see getPubKey).
/// </summary>
/// <exception cref="BitCoinSharp.ScriptException" />
public Address ToAddress
{
get { return new Address(_params, PubKeyHash); }
}
/// <summary>
/// Runs the script with the given Transaction as the "context". Some operations like CHECKSIG
/// require a transaction to operate on (eg to hash). The context transaction is typically
/// the transaction having its inputs verified, ie the one where the scriptSig comes from.
/// </summary>
/// <exception cref="BitCoinSharp.ScriptException" />
public bool Run(Transaction context)
{
foreach (var chunk in _chunks)
{
if (chunk.Length == 1)
{
var opcode = chunk[0];
switch (opcode)
{
case OpDup:
ProcessOpDup();
break;
case OpHash160:
ProcessOpHash160();
break;
case OpEqualVerify:
ProcessOpEqualVerify();
break;
case OpCheckSig:
ProcessOpCheckSig(context);
break;
default:
_log.DebugFormat("Unknown/unimplemented opcode: {0}", opcode);
break;
}
}
else
{
// Data block, push it onto the stack.
_log.DebugFormat("Push {0}", Utils.BytesToHexString(chunk));
_stack.Push(chunk);
}
}
var result = _stack.Pop();
if (result.Length != 1)
throw new ScriptException("Script left junk at the top of the stack: " + Utils.BytesToHexString(result));
return result[0] == 1;
}
internal void LogStack()
{
var stack = _stack.ToList();
for (var i = 0; i < stack.Count; i++)
{
_log.DebugFormat("Stack[{0}]: {1}", i, Utils.BytesToHexString(stack[i]));
}
}
// WARNING: Unfinished and untested!
/// <exception cref="BitCoinSharp.ScriptException" />
private void ProcessOpCheckSig(Transaction context)
{
_stack.Pop();
var sigAndHashType = _stack.Pop();
// The signature has an extra byte on the end to indicate the type of hash. The signature
// is over the contents of the program, minus the signature itself of course.
var hashType = sigAndHashType[sigAndHashType.Length - 1];
// The high bit of the hashType byte is set to indicate "anyone can pay".
var anyoneCanPay = hashType >= 0x80;
// Mask out the top bit.
hashType &= 0x7F;
Transaction.SigHash sigHash;
switch (hashType)
{
case 1:
sigHash = Transaction.SigHash.All;
break;
case 2:
sigHash = Transaction.SigHash.None;
break;
case 3:
sigHash = Transaction.SigHash.Single;
break;
default:
// TODO: This should probably not be an exception.
throw new ScriptException("Unknown sighash byte: " + sigAndHashType[sigAndHashType.Length - 1]);
}
var sig = new byte[sigAndHashType.Length - 1];
Array.Copy(sigAndHashType, 0, sig, 0, sig.Length);
_log.DebugFormat("CHECKSIG: hashtype={0} anyoneCanPay={1}", sigHash, anyoneCanPay);
if (context == null)
{
// TODO: Fix the unit tests to run scripts in transaction context then remove this.
PushBool(true);
return;
}
// TODO: Implement me!
// Transaction tx = context.simplify(sigHash, 0, anyoneCanPay);
// The steps to do so are as follows:
// - Use the hashtype to fiddle the transaction as appropriate
// - Serialize the transaction and hash it
// - Use EC code to verify the hash matches the signature
PushBool(true);
}
private void PushBool(bool val)
{
_stack.Push(new[] {val ? (byte) 1 : (byte) 0});
}
/// <exception cref="BitCoinSharp.ScriptException" />
private void ProcessOpEqualVerify()
{
_log.Debug("EQUALVERIFY");
var a = _stack.Pop();
var b = _stack.Pop();
if (!a.SequenceEqual(b))
throw new ScriptException("EQUALVERIFY failed: " + Utils.BytesToHexString(a) + " vs " +
Utils.BytesToHexString(b));
}
/// <summary>
/// Replaces the top item in the stack with a hash160 of it
/// </summary>
private void ProcessOpHash160()
{
var buf = _stack.Pop();
var hash = Utils.Sha256Hash160(buf);
_stack.Push(hash);
_log.DebugFormat("HASH160: output is {0}", Utils.BytesToHexString(hash));
}
/// <summary>
/// Duplicates the top item on the stack
/// </summary>
private void ProcessOpDup()
{
_log.Debug("DUP");
_stack.Push(_stack.Peek().ToArray());
}
////////////////////// Interface for writing scripts from scratch ////////////////////////////////
/// <summary>
/// Writes out the given byte buffer to the output stream with the correct opcode prefix
/// </summary>
/// <exception cref="System.IO.IOException" />
internal static void WriteBytes(Stream os, byte[] buf)
{
if (buf.Length < OpPushData1)
{
os.Write((byte) buf.Length);
os.Write(buf);
}
else if (buf.Length < 256)
{
os.Write(OpPushData1);
os.Write((byte) buf.Length);
os.Write(buf);
}
else if (buf.Length < 65536)
{
os.Write(OpPushData2);
os.Write((byte) buf.Length);
os.Write((byte) (buf.Length >> 8));
}
else
{
throw new NotSupportedException();
}
}
internal static byte[] CreateOutputScript(Address to)
{
using (var bits = new MemoryStream())
{
// TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes.
bits.Write(OpDup);
bits.Write(OpHash160);
WriteBytes(bits, to.Hash160);
bits.Write(OpEqualVerify);
bits.Write(OpCheckSig);
return bits.ToArray();
}
}
internal static byte[] CreateInputScript(byte[] signature, byte[] pubkey)
{
// TODO: Do this by creating a Script *first* then having the script reassemble itself into bytes.
using (var bits = new MemoryStream())
{
WriteBytes(bits, signature);
WriteBytes(bits, pubkey);
return bits.ToArray();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Description;
using WebAdressBook.Areas.HelpPage.Models;
namespace WebAdressBook.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 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 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)
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
model = GenerateApiModel(apiDescription, sampleGenerator);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator)
{
HelpPageApiModel apiModel = new HelpPageApiModel();
apiModel.ApiDescription = apiDescription;
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(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}", e.Message));
}
return apiModel;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
//---------------------------------------------------------------------------
//
// <copyright file=MouseBinding.cs company=Microsoft>
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
//
// Description: The MouseBinding class is used by the developer to create Mouse Input Bindings
//
// See spec at : http://avalon/coreui/Specs/Commanding(new).mht
//
//* MouseBinding class serves the purpose of Input Bindings for Mouse Device.
//
// History:
// 06/01/2003 : chandras - Created
// 05/01/2004 : chandras- changed to new design.
//---------------------------------------------------------------------------
using System;
using System.Windows.Input;
using System.Windows;
using System.Windows.Markup;
using System.ComponentModel;
using SR=MS.Internal.PresentationCore.SR;
using SRID=MS.Internal.PresentationCore.SRID;
namespace System.Windows.Input
{
/// <summary>
/// MouseBinding - Implements InputBinding (generic InputGesture-Command map)
/// MouseBinding acts like a map for MouseGesture and Commands.
/// Most of the logic is in InputBinding and MouseGesture, this only
/// facilitates user to specify MouseAction directly without going in
/// MouseGesture path. Also it provides the MouseGestureTypeConverter
/// on the Gesture property to have MouseGesture, like "RightClick"
/// defined in Markup as Gesture="RightClick" working.
/// </summary>
public class MouseBinding : InputBinding
{
//------------------------------------------------------
//
// Constructors
//
//------------------------------------------------------
#region Constructors
/// <summary>
/// constructor
/// </summary>
public MouseBinding() : base()
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="command">Command Associated</param>
/// <param name="mouseAction">Mouse Action</param>
internal MouseBinding(ICommand command, MouseAction mouseAction)
: this(command, new MouseGesture(mouseAction))
{
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="command">Command Associated</param>
/// <param name="gesture">Mmouse Gesture associated</param>
public MouseBinding(ICommand command, MouseGesture gesture) : base(command, gesture)
{
SynchronizePropertiesFromGesture(gesture);
// Hooking the handler explicitly becuase base constructor uses _gesture
// It cannot use Gesture property itself because it is a virtual
gesture.PropertyChanged += new PropertyChangedEventHandler(OnMouseGesturePropertyChanged);
}
#endregion Constructors
//------------------------------------------------------
//
// Properties
//
//------------------------------------------------------
#region Properties
/// <summary>
/// MouseGesture
/// </summary>
[TypeConverter(typeof(MouseGestureConverter))]
[ValueSerializer(typeof(MouseGestureValueSerializer))]
public override InputGesture Gesture
{
get
{
return base.Gesture as MouseGesture;
}
set
{
MouseGesture oldMouseGesture = Gesture as MouseGesture;
MouseGesture mouseGesture = value as MouseGesture;
if (mouseGesture != null)
{
base.Gesture = mouseGesture;
SynchronizePropertiesFromGesture(mouseGesture);
if (oldMouseGesture != mouseGesture)
{
if (oldMouseGesture != null)
{
oldMouseGesture.PropertyChanged -= new PropertyChangedEventHandler(OnMouseGesturePropertyChanged);
}
mouseGesture.PropertyChanged += new PropertyChangedEventHandler(OnMouseGesturePropertyChanged);
}
}
else
{
throw new ArgumentException(SR.Get(SRID.InputBinding_ExpectedInputGesture, typeof(MouseGesture)));
}
}
}
/// <summary>
/// Dependency property for MouseAction
/// </summary>
public static readonly DependencyProperty MouseActionProperty =
DependencyProperty.Register("MouseAction", typeof(MouseAction), typeof(MouseBinding), new UIPropertyMetadata(MouseAction.None, new PropertyChangedCallback(OnMouseActionPropertyChanged)));
/// <summary>
/// MouseAction
/// </summary>
public MouseAction MouseAction
{
get
{
return (MouseAction)GetValue(MouseActionProperty);
}
set
{
SetValue(MouseActionProperty, value);
}
}
private static void OnMouseActionPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MouseBinding mouseBinding = (MouseBinding)d;
mouseBinding.SynchronizeGestureFromProperties((MouseAction)(e.NewValue));
}
#endregion
#region Freezable
protected override Freezable CreateInstanceCore()
{
return new MouseBinding();
}
protected override void CloneCore(Freezable sourceFreezable)
{
base.CloneCore(sourceFreezable);
CloneGesture();
}
protected override void CloneCurrentValueCore(Freezable sourceFreezable)
{
base.CloneCurrentValueCore(sourceFreezable);
CloneGesture();
}
protected override void GetAsFrozenCore(Freezable sourceFreezable)
{
base.GetAsFrozenCore(sourceFreezable);
CloneGesture();
}
protected override void GetCurrentValueAsFrozenCore(Freezable sourceFreezable)
{
base.GetCurrentValueAsFrozenCore(sourceFreezable);
CloneGesture();
}
#endregion
#region Private Methods
/// <summary>
/// Synchronized Properties from Gesture
/// </summary>
private void SynchronizePropertiesFromGesture(MouseGesture mouseGesture)
{
if (!_settingGesture)
{
_settingGesture = true;
try
{
MouseAction = mouseGesture.MouseAction;
}
finally
{
_settingGesture = false;
}
}
}
/// <summary>
/// Synchronized Gesture from properties
/// </summary>
private void SynchronizeGestureFromProperties(MouseAction mouseAction)
{
if (!_settingGesture)
{
_settingGesture = true;
try
{
if (Gesture == null)
{
Gesture = new MouseGesture(mouseAction);
}
else
{
((MouseGesture)Gesture).MouseAction = mouseAction;
}
}
finally
{
_settingGesture = false;
}
}
}
private void OnMouseGesturePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (string.Compare(e.PropertyName, "MouseAction", StringComparison.Ordinal) == 0)
{
MouseGesture mouseGesture = Gesture as MouseGesture;
if (mouseGesture != null)
{
SynchronizePropertiesFromGesture(mouseGesture);
}
}
}
private void CloneGesture()
{
MouseGesture mouseGesture = Gesture as MouseGesture;
if (mouseGesture != null)
{
mouseGesture.PropertyChanged += new PropertyChangedEventHandler(OnMouseGesturePropertyChanged);
}
}
#endregion
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
#region Data
private bool _settingGesture = false;
#endregion
}
}
| |
#if !DISABLE_PLAYFABENTITY_API
using System;
using System.Collections.Generic;
using PlayFab.SharedModels;
namespace PlayFab.ProfilesModels
{
public enum EffectType
{
Allow,
Deny
}
/// <summary>
/// An entity object and its associated meta data.
/// </summary>
[Serializable]
public class EntityDataObject : PlayFabBaseModel
{
/// <summary>
/// Un-escaped JSON object, if DataAsObject is true.
/// </summary>
public object DataObject;
/// <summary>
/// Escaped string JSON body of the object, if DataAsObject is default or false.
/// </summary>
public string EscapedDataObject;
/// <summary>
/// Name of this object.
/// </summary>
public string ObjectName;
}
/// <summary>
/// Combined entity type and ID structure which uniquely identifies a single entity.
/// </summary>
[Serializable]
public class EntityKey : PlayFabBaseModel
{
/// <summary>
/// Unique ID of the entity.
/// </summary>
public string Id;
/// <summary>
/// Entity type. See https://docs.microsoft.com/gaming/playfab/features/data/entities/available-built-in-entity-types
/// </summary>
public string Type;
}
[Serializable]
public class EntityLineage : PlayFabBaseModel
{
/// <summary>
/// The Character Id of the associated entity.
/// </summary>
public string CharacterId;
/// <summary>
/// The Group Id of the associated entity.
/// </summary>
public string GroupId;
/// <summary>
/// The Master Player Account Id of the associated entity.
/// </summary>
public string MasterPlayerAccountId;
/// <summary>
/// The Namespace Id of the associated entity.
/// </summary>
public string NamespaceId;
/// <summary>
/// The Title Id of the associated entity.
/// </summary>
public string TitleId;
/// <summary>
/// The Title Player Account Id of the associated entity.
/// </summary>
public string TitlePlayerAccountId;
}
[Serializable]
public class EntityPermissionStatement : PlayFabBaseModel
{
/// <summary>
/// The action this statement effects. May be 'Read', 'Write' or '*' for both read and write.
/// </summary>
public string Action;
/// <summary>
/// A comment about the statement. Intended solely for bookkeeping and debugging.
/// </summary>
public string Comment;
/// <summary>
/// Additional conditions to be applied for entity resources.
/// </summary>
public object Condition;
/// <summary>
/// The effect this statement will have. It may be either Allow or Deny
/// </summary>
public EffectType Effect;
/// <summary>
/// The principal this statement will effect.
/// </summary>
public object Principal;
/// <summary>
/// The resource this statements effects. Similar to 'pfrn:data--title![Title ID]/Profile/*'
/// </summary>
public string Resource;
}
[Serializable]
public class EntityProfileBody : PlayFabBaseModel
{
/// <summary>
/// Avatar URL for the entity.
/// </summary>
public string AvatarUrl;
/// <summary>
/// The creation time of this profile in UTC.
/// </summary>
public DateTime Created;
/// <summary>
/// The display name of the entity. This field may serve different purposes for different entity types. i.e.: for a title
/// player account it could represent the display name of the player, whereas on a character it could be character's name.
/// </summary>
public string DisplayName;
/// <summary>
/// The entity id and type.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The chain of responsibility for this entity. Use Lineage.
/// </summary>
public string EntityChain;
/// <summary>
/// The experiment variants of this profile.
/// </summary>
public List<string> ExperimentVariants;
/// <summary>
/// The files on this profile.
/// </summary>
public Dictionary<string,EntityProfileFileMetadata> Files;
/// <summary>
/// The language on this profile.
/// </summary>
public string Language;
/// <summary>
/// Leaderboard metadata for the entity.
/// </summary>
public string LeaderboardMetadata;
/// <summary>
/// The lineage of this profile.
/// </summary>
public EntityLineage Lineage;
/// <summary>
/// The objects on this profile.
/// </summary>
public Dictionary<string,EntityDataObject> Objects;
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
/// <summary>
/// The statistics on this profile.
/// </summary>
public Dictionary<string,EntityStatisticValue> Statistics;
/// <summary>
/// The version number of the profile in persistent storage at the time of the read. Used for optional optimistic
/// concurrency during update.
/// </summary>
public int VersionNumber;
}
/// <summary>
/// An entity file's meta data. To get a download URL call File/GetFiles API.
/// </summary>
[Serializable]
public class EntityProfileFileMetadata : PlayFabBaseModel
{
/// <summary>
/// Checksum value for the file, can be used to check if the file on the server has changed.
/// </summary>
public string Checksum;
/// <summary>
/// Name of the file
/// </summary>
public string FileName;
/// <summary>
/// Last UTC time the file was modified
/// </summary>
public DateTime LastModified;
/// <summary>
/// Storage service's reported byte count
/// </summary>
public int Size;
}
[Serializable]
public class EntityStatisticChildValue : PlayFabBaseModel
{
/// <summary>
/// Child name value, if child statistic
/// </summary>
public string ChildName;
/// <summary>
/// Child statistic metadata
/// </summary>
public string Metadata;
/// <summary>
/// Child statistic value
/// </summary>
public int Value;
}
[Serializable]
public class EntityStatisticValue : PlayFabBaseModel
{
/// <summary>
/// Child statistic values
/// </summary>
public Dictionary<string,EntityStatisticChildValue> ChildStatistics;
/// <summary>
/// Statistic metadata
/// </summary>
public string Metadata;
/// <summary>
/// Statistic name
/// </summary>
public string Name;
/// <summary>
/// Statistic value
/// </summary>
public int? Value;
/// <summary>
/// Statistic version
/// </summary>
public int Version;
}
/// <summary>
/// Given an entity type and entity identifier will retrieve the profile from the entity store. If the profile being
/// retrieved is the caller's, then the read operation is consistent, if not it is an inconsistent read. An inconsistent
/// read means that we do not guarantee all committed writes have occurred before reading the profile, allowing for a stale
/// read. If consistency is important the Version Number on the result can be used to compare which version of the profile
/// any reader has.
/// </summary>
[Serializable]
public class GetEntityProfileRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
}
[Serializable]
public class GetEntityProfileResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profile
/// </summary>
public EntityProfileBody Profile;
}
/// <summary>
/// Given a set of entity types and entity identifiers will retrieve all readable profiles properties for the caller.
/// Profiles that the caller is not allowed to read will silently not be included in the results.
/// </summary>
[Serializable]
public class GetEntityProfilesRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Determines whether the objects will be returned as an escaped JSON string or as a un-escaped JSON object. Default is
/// JSON string.
/// </summary>
public bool? DataAsObject;
/// <summary>
/// Entity keys of the profiles to load. Must be between 1 and 25
/// </summary>
public List<EntityKey> Entities;
}
[Serializable]
public class GetEntityProfilesResponse : PlayFabResultCommon
{
/// <summary>
/// Entity profiles
/// </summary>
public List<EntityProfileBody> Profiles;
}
/// <summary>
/// Retrieves the title access policy that is used before the profile's policy is inspected during a request. If never
/// customized this will return the default starter policy built by PlayFab.
/// </summary>
[Serializable]
public class GetGlobalPolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
}
[Serializable]
public class GetGlobalPolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
/// <summary>
/// Given a master player account id (PlayFab ID), returns all title player accounts associated with it.
/// </summary>
[Serializable]
public class GetTitlePlayersFromMasterPlayerAccountIdsRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// Master player account ids.
/// </summary>
public List<string> MasterPlayerAccountIds;
/// <summary>
/// Id of title to get players from.
/// </summary>
public string TitleId;
}
[Serializable]
public class GetTitlePlayersFromMasterPlayerAccountIdsResponse : PlayFabResultCommon
{
/// <summary>
/// Optional id of title to get players from, required if calling using a master_player_account.
/// </summary>
public string TitleId;
/// <summary>
/// Dictionary of master player ids mapped to title player entity keys and id pairs
/// </summary>
public Dictionary<string,EntityKey> TitlePlayerAccounts;
}
public enum OperationTypes
{
Created,
Updated,
Deleted,
None
}
/// <summary>
/// This will set the access policy statements on the given entity profile. This is not additive, any existing statements
/// will be replaced with the statements in this request.
/// </summary>
[Serializable]
public class SetEntityProfilePolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The statements to include in the access policy.
/// </summary>
public List<EntityPermissionStatement> Statements;
}
[Serializable]
public class SetEntityProfilePolicyResponse : PlayFabResultCommon
{
/// <summary>
/// The permissions that govern access to this entity profile and its properties. Only includes permissions set on this
/// profile, not global statements from titles and namespaces.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
/// <summary>
/// Updates the title access policy that is used before the profile's policy is inspected during a request. Policies are
/// compiled and cached for several minutes so an update here may not be reflected in behavior for a short time.
/// </summary>
[Serializable]
public class SetGlobalPolicyRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The permissions that govern access to all entities under this title or namespace.
/// </summary>
public List<EntityPermissionStatement> Permissions;
}
[Serializable]
public class SetGlobalPolicyResponse : PlayFabResultCommon
{
}
/// <summary>
/// Given an entity profile, will update its language to the one passed in if the profile's version is equal to the one
/// passed in.
/// </summary>
[Serializable]
public class SetProfileLanguageRequest : PlayFabRequestCommon
{
/// <summary>
/// The optional custom tags associated with the request (e.g. build number, external trace identifiers, etc.).
/// </summary>
public Dictionary<string,string> CustomTags;
/// <summary>
/// The entity to perform this action on.
/// </summary>
public EntityKey Entity;
/// <summary>
/// The expected version of a profile to perform this update on
/// </summary>
public int? ExpectedVersion;
/// <summary>
/// The language to set on the given entity. Deletes the profile's language if passed in a null string.
/// </summary>
public string Language;
}
[Serializable]
public class SetProfileLanguageResponse : PlayFabResultCommon
{
/// <summary>
/// The type of operation that occured on the profile's language
/// </summary>
public OperationTypes? OperationResult;
/// <summary>
/// The updated version of the profile after the language update
/// </summary>
public int? VersionNumber;
}
}
#endif
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Banshee.Base;
using Banshee.MediaEngine;
using Banshee.Sources;
using Banshee.Configuration.Schema;
using Banshee.Plugins;
using Banshee.Winforms;
using Banshee.Base.Winforms.Widgets;
namespace Banshee
{
//Cornel 23-03-2007 - I will try and stay as close to the GTK# UI as i can
public partial class WindowPlayer : ComponentFactory.Krypton.Toolkit.KryptonForm
{
public static readonly uint SkipDelta = 10;
public static readonly int VolumeDelta = 10;
Hashtable playlistMenuMap = new Hashtable();
private PlaylistModel playlistModel;
Banshee.Base.Gui.SourceView sourceView;
private SeekSlider seek_slider;
private StreamPositionLabel stream_position_label;
Banshee.Base.Winforms.Controls.SearchEntry searchEntry;
public WindowPlayer()
{
InitializeComponent();
}
void InitSystem()
{
UpdateUI("Loading Banshee", 10);
LogCore.PrintEntries = true;
Globals.Initialize();
Globals.StartupInitializer.Run();
Globals.ShutdownRequested += new ShutdownRequestHandler(Globals_ShutdownRequested);
UpdateUI("Creating Components", 60);
BuildWindow();
}
private BackgroundWorker startupWorker = new BackgroundWorker();
bool Globals_ShutdownRequested()
{
Banshee.Winforms.Controls.ActiveUserEventsManager.Instance.CancelAll();
PlayerEngineCore.Dispose();
return true;
}
ToolTip toolTips = new ToolTip();
private void WindowPlayer_Load(object sender, EventArgs e)
{
InitSystem();
IconThemeUtils.SetWindowIcon(this, Properties.Resources.music_player_banshee_22);
this.Text = Banshee.Base.ConfigureDefines.PACKAGE + " " + Banshee.Base.ConfigureDefines.VERSION;
startupfinished();
Banshee.Controls.SplashScreen.CloseForm();
this.BringToFront();
}
void SetTip(Control ctrl, string caption)
{
toolTips.SetToolTip(ctrl, caption);
}
void BuildWindow()
{
//mainMenu.Renderer = new GlassControls.Controls.Office2007Renderer();
InterfaceElements.MainWindow = this;
InterfaceElements.MainContainer = LibraryContainer;
//SetTip(burn_button, "Write selection to CD");
//SetTip(rip_button, Catalog.GetString("Import CD into library"));
SetTip(previous_button, "Play previous song");
SetTip(playpause_button, "Play/pause current song");
SetTip(next_button, "Play next song");
SetTip(dapDiskUsageBar, "Device disk usage");
//SetTip(sync_dap_button, Catalog.GetString("Synchronize music library to device"));
SetTip(volumeButton, "Adjust volume");
SetTip(repeat_toggle_button, Catalog.GetString("Change repeat playback mode"));
SetTip(shuffle_toggle_button, Catalog.GetString("Toggle shuffle playback mode"));
SetTip(song_properties_button, Catalog.GetString("Edit and view metadata of selected songs"));
playlistModel = new PlaylistModel();
InterfaceElements.PlaylistView = playlistView;
//playlistGrid.DataSource = new BindingList<TrackInfo>(playlistModel.Tracks);
playlistView.LoadColumns();
InterfaceElements.PlaylistContainer = playlistContainer;
searchEntry = searchEntry1;
Banshee.Winforms.Controls.ActiveUserEventsManager event_manager = new Banshee.Winforms.Controls.ActiveUserEventsManager();
event_manager.Dock = DockStyle.Fill;
event_manager.ControlAdded += new ControlEventHandler(event_manager_ControlAdded);
event_manager.ControlRemoved += new ControlEventHandler(event_manager_ControlRemoved);
event_panel.Controls.Add(event_manager);
event_panel.Visible = false;
trackInfoHeader.Title = "Banshee";
trackInfoHeader.Dock = DockStyle.Fill;
SetRepeatMode((RepeatMode)PlayerWindowSchema.PlaybackRepeat.Get());
repeat_toggle_button.Values.Image = Properties.Resources.media_repeat_all;
playpause_button.Values.Image = Properties.Resources.media_playback_start;
sourceView = new Banshee.Base.Gui.SourceView();
sourceView.Dock = DockStyle.Fill;
sourceView.BringToFront();
playlistView.SourceView = sourceView;
SourceSplitter.Panel1.Controls.Add(sourceView);
seek_slider = new SeekSlider();
seek_slider.Dock = DockStyle.Fill;
seek_slider.SeekRequested += new EventHandler(seek_slider_SeekRequested);
seekpanel.Controls.Add(seek_slider);
seek_slider.SetIdle();
stream_position_label = new StreamPositionLabel(seek_slider);
stream_position_label.Dock = DockStyle.Bottom;
seekpanel.Controls.Add(stream_position_label);
playlistModel.Repeat = RepeatMode.All;
this.DoubleBuffered = true;
InterfaceElements.SearchEntry = this.searchEntry1;
InterfaceElements.ActionButtonBox = additional_action_buttons_box;
SetupEventHandlers();
Setrenderer(Properties.Settings.Default.style);
}
void UpdateUI(string status, int progress)
{
Banshee.Controls.SplashScreen.SetStatus(status, true,progress);
}
void playlist_grid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
{
// playlistView.PlayTrack();
}
void seek_slider_SeekRequested(object sender, EventArgs e)
{
PlayerEngineCore.Position = (uint)seek_slider.Value;
}
void SetupEventHandlers()
{
PlayerEngineCore.EventChanged += new PlayerEngineEventHandler(PlayerEngineCore_EventChanged);
PlayerEngineCore.StateChanged += new PlayerEngineStateHandler(PlayerEngineCore_StateChanged);
playlistModel.Updated += new EventHandler(playlistModel_Updated);
searchEntry.Changed += new EventHandler(playlistView_Changed);
SourceManager.ActiveSourceChanged += new SourceEventHandler(SourceManager_ActiveSourceChanged);
SourceManager.SourceUpdated += new SourceEventHandler(SourceManager_SourceUpdated);
SourceManager.SourceViewChanged += new SourceEventHandler(SourceManager_SourceViewChanged);
SourceManager.SourceTrackAdded += new TrackEventHandler(SourceManager_SourceTrackAdded);
SourceManager.SourceTrackRemoved += new TrackEventHandler(SourceManager_SourceTrackRemoved);
Dap.DapCore.DapAdded += new Banshee.Dap.DapEventHandler(DapCore_DapAdded);
}
void DapCore_DapAdded(object o, Banshee.Dap.DapEventArgs args)
{
args.Dap.PropertiesChanged += new EventHandler(Dap_PropertiesChanged);
args.Dap.SaveFinished += new EventHandler(Dap_SaveFinished);
}
void Dap_SaveFinished(object sender, EventArgs e)
{
if (SourceManager.ActiveSource is DapSource
&& !(SourceManager.ActiveSource as DapSource).IsSyncing)
{
playlistModel.ReloadSource();
UpdateDapDiskUsageBar(SourceManager.ActiveSource as DapSource);
}
}
void Dap_PropertiesChanged(object sender, EventArgs e)
{
}
void SourceManager_SourceTrackRemoved(object o, TrackEventArgs args)
{
playlistView.RefreshTracks();
sourceView.RefreshList();
}
void SourceManager_SourceTrackAdded(object o, TrackEventArgs args)
{
playlistView.RefreshTracks();
sourceView.RefreshList();
}
void SourceManager_SourceViewChanged(SourceEventArgs args)
{
if (args.Source == SourceManager.ActiveSource)
{
UpdateSourceView();
}
}
private void UpdateSourceView()
{
if (SourceManager.ActiveSource.ViewWidget != null)
{
ShowSourceWidget();
}
else
{
ShowPlaylistView();
}
}
private void ShowSourceWidget()
{
this.BeginInvoke((MethodInvoker)delegate()
{
playlist_header_event_box.Visible = SourceManager.ActiveSource.ShowPlaylistHeader;
if (LibraryContainer.Controls.Contains(SourceManager.ActiveSource.ViewWidget))
{
return;
}
if (SourceManager.ActiveSource.ViewWidget == null)
{
ShowPlaylistView();
return;
}
if (LibraryContainer.Controls.Count > 0)
{
LibraryContainer.Controls.Clear();
}
LibraryContainer.Controls.Add(SourceManager.ActiveSource.ViewWidget);
});
}
private void ShowPlaylistView()
{
if (LibraryContainer.Controls.Contains( playlistContainer))
{
return;
}
else if (LibraryContainer.Controls.Count >0 && LibraryContainer.Controls[0] != null)
{
LibraryContainer.Controls.Clear();
}
InterfaceElements.DetachPlaylistContainer();
LibraryContainer.Controls.Add(playlistContainer);
playlist_header_event_box.Visible = true;
}
void SourceManager_SourceUpdated(SourceEventArgs args)
{
if (args.Source == SourceManager.ActiveSource)
{
//UpdateViewName(args.Source);
if (playlistModel.Count() == 0 && args.Source.Count > 0
&& !searchEntry.IsQueryAvailable)
{
playlistModel.ReloadSource();
}
searchEntry.Enabled = args.Source.SearchEnabled;
}
}
void SourceManager_ActiveSourceChanged(SourceEventArgs args)
{
searchEntry.Ready = false;
ThreadAssist.ProxyToMain(HandleSourceChanged);
searchEntry.Ready = true;
}
Dap.DapDevice activedevice;
void SourceChanged()
{
BeginInvoke((MethodInvoker)delegate() {
Application.DoEvents();// I hate using this but the app stutters when the library is big
Source source = SourceManager.ActiveSource;
if (source == null)
{
return;
}
UpdateViewName(source, "Loading ...");
playlistModel.ReloadSource();
searchEntry.Ready = false;
if (source.FilterQuery != null && source.FilterField != null)
{
searchEntry.Query = source.FilterQuery;
searchEntry.Field = source.FilterField;
}
if (source is DapSource)
{
DapSource dap_source = source as DapSource;
UpdateDapDiskUsageBar(dap_source);
dapDiskUsageBar.Visible = true;
sync_dap_button.Visible = true;
activedevice = dap_source.Device;
activedevice.SaveFinished += new EventHandler(Device_SaveFinished);
}
else
{
dapDiskUsageBar.Visible = false;
sync_dap_button.Visible = false;
}
UpdateViewName(source, string.Empty);
// Bold label below track info
// SensitizeActions(source); // Right-click actions, buttons above search
// Make some choices for audio CDs, they can't be rated, nor have plays or
// last-played info. Only show the rip button for audio CDs
searchEntry.Enabled = source.SearchEnabled;
//playlistView.RipColumn.Visible = source is AudioCdSource;
UpdateSourceView();
//OnPlaylistViewSelectionChanged(playlistView.Selection, new EventArgs());
searchEntry.Ready = true;
});
}
void Device_SaveFinished(object sender, EventArgs e)
{
if (SourceManager.ActiveSource is DapSource
&& !(SourceManager.ActiveSource as DapSource).IsSyncing)
{
playlistModel.ReloadSource();
UpdateDapDiskUsageBar(SourceManager.ActiveSource as DapSource);
}
sourceView.RefreshList();
playlistView.RefreshTracks();
}
private void UpdateDapDiskUsageBar(DapSource dapSource)
{
this.Invoke((MethodInvoker)delegate()
{
{
dapDiskUsageBar.Maximum = (int)dapSource.Device.StorageCapacity;
dapDiskUsageBar.Value = (int)dapSource.Device.StorageUsed;
dapDiskUsageBar.Text = dapSource.DiskUsageString;
string tooltip = dapSource.DiskUsageString + " (" + dapSource.DiskAvailableString + ")";
SetTip(dapDiskUsageBar, tooltip);
}
});
}
private void HandleSourceChanged(object o, EventArgs args)
{
ThreadAssist.Spawn(new System.Threading.ThreadStart(SourceChanged), true);
}
private void UpdateViewName(Source source,string info)
{
ViewNameLabel.Text = string.Format("{0} {1}",source.Name,info);
}
void playlistView_Changed(object sender, EventArgs e)
{
OnSimpleSearch(sender, e);
}
void playlistModel_Updated(object sender, EventArgs e)
{
UpdateStatusBar();
sourceView.RefreshList();
}
private bool incrementedCurrentSongPlayCount;
void PlayerEngineCore_StateChanged(object o, PlayerEngineStateArgs args)
{
switch (args.State)
{
case PlayerEngineState.Contacting:
stream_position_label.IsContacting = true;
seek_slider.SetIdle();
SetPlayButton();
break;
case PlayerEngineState.Loaded:
incrementedCurrentSongPlayCount = false;
seek_slider.Duration = PlayerEngineCore.CurrentTrack.Duration.TotalSeconds;
UpdateMetaDisplay();
if (!PlayerEngineCore.CurrentTrack.CanPlay)
{
LogCore.Instance.PushWarning(
Catalog.GetString("Cannot Play Song"),
String.Format(Catalog.GetString("{0} cannot be played by Banshee. " +
"The most common reasons for this are:\n\n" +
" u2022 Song is protected (DRM)\n" +
" u2022 Song is on a DAP that does not support playback\n"),
PlayerEngineCore.CurrentTrack.Title));
}
break;
case PlayerEngineState.Idle:
posTimer.Stop();
playpause_button.Values.Image = Properties.Resources.media_playback_start;
seek_slider.SetIdle();
trackInfoHeader.SetIdle();
stream_position_label.IsContacting = false;
UpdateMetaDisplay();
break;
case PlayerEngineState.Paused:
posTimer.Stop();
playpause_button.Values.Image = Properties.Resources.media_playback_start;
break;
case PlayerEngineState.Playing:
// posTimer.Start();
playlistView.SelectPlaying();
SetPlayButton();
UpdateMetaDisplay();
break;
}
}
void PlayerEngineCore_EventChanged(object o, PlayerEngineEventArgs args)
{
switch (args.Event)
{
case PlayerEngineEvent.Iterate:
//Cornel - Although i have written the code ... the engine gets the event... but the event never fires here
OnPlayerEngineTick();
break;
case PlayerEngineEvent.EndOfStream:
//ToggleAction action = Globals.ActionManager["StopWhenFinishedAction"] as ToggleAction;
/* if (!action.Active)
{
playlistModel.Continue();
}
else
{
//OnPlaylistStopped(null, null);
}*/
LogCore.Instance.PushInformation("Player Engine","Player Reached End of Stream");
playlistView.UpdateView();
Next();
break;
case PlayerEngineEvent.StartOfStream:
UpdateMetaDisplay();
seek_slider.CanSeek = PlayerEngineCore.CanSeek;
break;
case PlayerEngineEvent.Volume:
// volumeButton.Volume = PlayerEngineCore.Volume;
break;
case PlayerEngineEvent.Buffering:
if (args.BufferingPercent >= 1.0)
{
stream_position_label.IsBuffering = false;
break;
}
stream_position_label.IsBuffering = true;
stream_position_label.BufferingProgress = args.BufferingPercent;
seek_slider.SetIdle();
break;
case PlayerEngineEvent.Error:
Console.WriteLine("Player error");
RepeatMode old_repeat_mode = playlistModel.Repeat;
bool old_shuffle_mode = playlistModel.Shuffle;
playlistModel.Repeat = RepeatMode.ErrorHalt;
playlistModel.Shuffle = false;
Next();
playlistModel.Repeat = old_repeat_mode;
playlistModel.Shuffle = old_shuffle_mode;
break;
case PlayerEngineEvent.TrackInfoUpdated:
UpdateMetaDisplay();
break;
}
}
private void OnJumpToPlayingAction(object o, EventArgs args)
{
playlistView.ScrollToPlaying();
}
private void OnPlayerEngineTick()
{
uint stream_length = PlayerEngineCore.Length;
uint stream_position = PlayerEngineCore.Position;
stream_position_label.IsContacting = false;
seek_slider.CanSeek = PlayerEngineCore.CanSeek;
seek_slider.Duration = stream_length;
seek_slider.SeekValue = stream_position;
Console.WriteLine("Player Ticking");
if (PlayerEngineCore.CurrentTrack == null)
{
return;
}
if (stream_length > 0 && PlayerEngineCore.CurrentTrack.Duration.TotalSeconds != (double)stream_length)
{
PlayerEngineCore.CurrentTrack.Duration = new TimeSpan(stream_length * TimeSpan.TicksPerSecond);
PlayerEngineCore.CurrentTrack.Save();
}
if (stream_length > 0 && stream_position > stream_length / 2 && !incrementedCurrentSongPlayCount)
{
PlayerEngineCore.CurrentTrack.IncrementPlayCount();
incrementedCurrentSongPlayCount = true;
}
}
public void Previous()
{
playlistModel.Regress();
playlistView.UpdateView();
}
public void Next()
{
playlistModel.Advance();
playlistView.UpdateView();
}
public string ApplicationLongName
{
get { return Catalog.GetString("Banshee Music Player"); }
}
public void UpdateMetaDisplay()
{
TrackInfo track = PlayerEngineCore.CurrentTrack;
if (track == null)
{
this.Text = ApplicationLongName;
trackInfoHeader.Visible = false;
cover_art_view.FileName = null;
cover_art_view.BorderStyle = BorderStyle.None;
//trackInfoHeader.Cover.Image = Properties.Resources.editor_cover_album;
return;
}
trackInfoHeader.Artist = track.DisplayArtist;
trackInfoHeader.Title = track.DisplayTitle;
trackInfoHeader.Album = track.Album;
trackInfoHeader.MoreInfoUri = track.MoreInfoUri != null ? track.MoreInfoUri.AbsoluteUri : null;
trackInfoHeader.Visible = true;
this.Text = track.DisplayTitle + ((track.Artist != null && track.Artist != String.Empty)
? (" (" + track.DisplayArtist + ")")
: "");
try
{
trackInfoHeader.FileName = track.CoverArtFileName;
cover_art_view.FileName = track.CoverArtFileName;
trackInfoHeader.Label = String.Format("{0} - {1}", track.DisplayArtist, track.DisplayAlbum);
cover_art_view.Enabled = false;
}
catch (Exception)
{
}
}
void event_manager_ControlRemoved(object sender, ControlEventArgs e)
{
event_panel.Visible = false;
}
void event_manager_ControlAdded(object sender, ControlEventArgs e)
{
event_panel.Visible = true;
}
void startupfinished()
{
UpdateUI("Checking Startup status", 80);
Application.DoEvents();
if (Globals.Library.IsLoaded)
{
Library_Reloaded(Globals.Library, new EventArgs());
}
else
{
Globals.Library.Reloaded += new EventHandler(Library_Reloaded);
}
SourceManager.SetActiveSource(LibrarySource.Instance);
Application.DoEvents();
//Cornel Not using args right now
/*if (LocalQueueSource.Instance.Count > 0)
{
SourceManager.SetActiveSource(LocalQueueSource.Instance);
}*/
/*foreach (Source source in SourceManager.Sources)
{
if (source is DapSource)
{
DapSource dsource = source as DapSource;
}
}*/
UpdateUI("Loading Playlists", 90);
Banshee.Base.HalCore.Control = this;
playlistView.Model = playlistModel;
Application.DoEvents();
}
protected override void WndProc(ref Message m)
{
base.WndProc(ref m);
Banshee.Base.HalCore.SendMessage(ref m);
}
void Library_Reloaded(object sender, EventArgs e)
{
BeginInvoke((MethodInvoker)delegate() {
if (Globals.Library.Tracks.Count <= 0)
{
PromptForImport();
}else
sourceView.RefreshList();
});
}
private void PromptForImport()
{
PromptForImport(true);
}
private void PromptForImport(bool startup)
{
bool show_dialog = System.Convert.ToBoolean(ImportSchema.ShowInitialImportDialog.Get());
if (startup && !show_dialog)
{
return;
}
Banshee.Winforms.ImportDialog dialog = new Banshee.Winforms.ImportDialog();
dialog.DoNotShowAgain = (bool)ImportSchema.ShowInitialImportDialog.Get();
DialogResult dr = dialog.ShowDialog(this);
if (dr != DialogResult.OK)
return;
else
{
IImportSource import_source = dialog.ActiveSource;
if (import_source != null)
{
import_source.Import();
}
}
if (startup)
{
ImportSchema.ShowInitialImportDialog.Set(!dialog.DoNotShowAgain);
}
}
void SetTitle(string text)
{
BeginInvoke((MethodInvoker)delegate() {
this.Text = text;});
}
string pluglist = string.Empty;
private void WindowPlayer_Shown(object sender, EventArgs e)
{
}
private void next_button_Click(object sender, EventArgs e)
{
Next();
}
private void SetPlayButton()
{
if (PlayerEngineCore.CanPause)
{
playpause_button.Values.Image = Properties.Resources.media_playback_pause;
}
else
{
playpause_button.Values.Image = Properties.Resources.media_playback_stop;
}
}
private void previous_button_Click(object sender, EventArgs e)
{
Previous();
}
public void TogglePlaying()
{
if (PlayerEngineCore.CurrentState == PlayerEngineState.Playing)
{
PlayerEngineCore.Pause();
}
else
{
PlayerEngineCore.Play();
}
}
public void PlayPause()
{
if (PlayerEngineCore.CurrentState != PlayerEngineState.Idle)
{
TogglePlaying();
}
else
{
if (SourceManager.ActiveSource.HandlesStartPlayback)
{
SourceManager.ActiveSource.StartPlayback();
return;
}
if (!playlistView.PlaySelected())
{
playlistModel.Advance();
playlistView.UpdateView();
}
}
}
private void playpause_button_Click(object sender, EventArgs e)
{
PlayPause();
}
private void WindowPlayer_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit();
}
private void UpdateStatusBar()
{
BeginInvoke((MethodInvoker)delegate() {
long count = playlistModel.Count();
if (count == 0 && SourceManager.ActiveSource == null)
{
LabelStatusBar.Text = ApplicationLongName;
return;
}
else if (count == 0)
{
LabelStatusBar.Text = String.Empty;
return;
}
TimeSpan span = playlistModel.TotalDuration;
StringBuilder builder = new StringBuilder();
builder.AppendFormat("{0} Items", count);
builder.Append(", ");
if (span.Days > 0)
{
builder.AppendFormat("{0} days", span.Days);
builder.Append(", ");
}
if (span.Hours > 0)
{
builder.AppendFormat("{0} hours", span.Hours);
builder.Append(", ");
}
builder.AppendFormat("{0} minutes", span.Minutes);
builder.Append(", ");
builder.AppendFormat("{0} seconds", span.Seconds);
LabelStatusBar.Text = builder.ToString();
});
}
private bool suspendSearch;
private void OnSimpleSearch(object o, EventArgs args)
{
//Cornel - I found the BackgroundWorker gives me the most responsive UI
UpdateViewName(SourceManager.ActiveSource, "Searching...");
SourceManager.ActiveSource.FilterField = searchEntry.Field;
SourceManager.ActiveSource.FilterQuery = searchEntry.Query;
Source source = SourceManager.ActiveSource;
if (SourceManager.ActiveSource.HandlesSearch)
{
return;
}
if (suspendSearch)
{
return;
}
playlistModel.ClearModel();
if (!searchEntry.IsQueryAvailable)
{
playlistModel.ReloadSource();
playlistView.UpdateView();
return;
}
this.backgroundWorker1.RunWorkerAsync();
playlistView.UpdateView();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
lock (SourceManager.ActiveSource.TracksMutex)
{
foreach (TrackInfo track in SourceManager.ActiveSource.Tracks)
{
try
{
if (DoesTrackMatchSearch(track))
{
playlistModel.AddTrack(track);
}
}
catch (Exception)
{
continue;
}
}
}
}
private bool DoesTrackMatchSearch(TrackInfo ti)
{
if (!searchEntry.IsQueryAvailable)
{
return false;
}
string query = searchEntry.Query;
string field = searchEntry.Field;
string[] matches;
if (field == Catalog.GetString("Artist Name"))
{
matches = new string[] { ti.Artist };
}
else if (field == Catalog.GetString("Song Name"))
{
matches = new string[] { ti.Title };
}
else if (field == Catalog.GetString("Album Title"))
{
matches = new string[] { ti.Album };
}
else if (field == Catalog.GetString("Genre"))
{
matches = new string[] { ti.Genre };
}
else if (field == Catalog.GetString("Year"))
{
matches = new string[] { ti.Year.ToString() };
}
else
{
matches = new string[] {
ti.Artist,
ti.Album,
ti.Title,
ti.Genre,
ti.Year.ToString()
};
}
List<string> words_include = new List<string>();
List<string> words_exclude = new List<string>();
Array.ForEach<string>(Regex.Split(query, @"\s+"), delegate(string word)
{
bool exclude = word.StartsWith("-");
if (exclude && word.Length > 1)
{
words_exclude.Add(word.Substring(1));
}
else if (!exclude)
{
words_include.Add(word);
}
});
foreach (string word in words_exclude)
{
foreach (string match in matches)
{
if (match == null || match == String.Empty)
{
continue;
}
if (StringUtil.RelaxedIndexOf(match, word) >= 0)
{
return false;
}
}
}
bool found;
foreach (string word in words_include)
{
found = false;
foreach (string match in matches)
{
if (match == null || match == string.Empty)
{
continue;
}
if (StringUtil.RelaxedIndexOf(match, word) >= 0)
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
return true;
}
private void SetRepeatMode(RepeatMode mode)
{
playlistModel.Repeat = mode;
PlayerWindowSchema.PlaybackRepeat.Set((int)mode);
allToolStripMenuItem.Checked = mode == RepeatMode.All ? true : false;
noneToolStripMenuItem.Checked = mode == RepeatMode.None ? true : false;
singleToolStripMenuItem.Checked = mode == RepeatMode.Single ? true : false;
}
//Menu Functions
private void importFolderToolStripMenuItem_Click(object sender, EventArgs e)
{
FolderImportSource.Instance.Import();
}
private void importFilesToolStripMenuItem_Click(object sender, EventArgs e)
{
FileImportSource.Instance.Import();
}
private void importMusicToolStripMenuItem_Click(object sender, EventArgs e)
{
PromptForImport(false);
}
private void quitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO
}
private void selectNoneToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO
}
private void pluginsToolStripMenuItem_Click(object sender, EventArgs e)
{
//TODO
}
private void preferencesToolStripMenuItem_Click(object sender, EventArgs e)
{
Banshee.Base.Winforms.Gui.PreferencesDialog prdlg = new Banshee.Base.Winforms.Gui.PreferencesDialog();
prdlg.ShowDialog(this);
}
private void playToolStripMenuItem_Click(object sender, EventArgs e)
{
PlayPause();
}
private void previousToolStripMenuItem_Click(object sender, EventArgs e)
{
if (PlayerEngineCore.Position < 3)
{
Previous();
}
else
{
PlayerEngineCore.Position = 0;
}
}
private void nextToolStripMenuItem_Click(object sender, EventArgs e)
{
Next();
}
private void seekForwardToolStripMenuItem_Click(object sender, EventArgs e)
{
PlayerEngineCore.Position += SkipDelta;
}
private void seekBackwardToolStripMenuItem_Click(object sender, EventArgs e)
{
PlayerEngineCore.Position -= SkipDelta;
}
private void shuffleToolStripMenuItem_Click(object sender, EventArgs e)
{
//ToggleAction action = o as ToggleAction;
//playlistModel.Shuffle = action.Active;
//PlayerWindowSchema.PlaybackShuffle.Set(action.Active);
}
private void allToolStripMenuItem_Click(object sender, EventArgs e)
{
SetRepeatMode(RepeatMode.All);
}
private void noneToolStripMenuItem_Click(object sender, EventArgs e)
{
SetRepeatMode(RepeatMode.None);
}
private void singleToolStripMenuItem_Click(object sender, EventArgs e)
{
SetRepeatMode(RepeatMode.Single);
}
private void showCoverartToolStripMenuItem_Click(object sender, EventArgs e)
{
if (cover_art_view.Enabled)
{
cover_art_view.Enabled = false;
}
else
{
cover_art_view.Enabled = true;
}
showCoverartToolStripMenuItem.Checked = cover_art_view.Enabled;
}
private void showFullScreenToolStripMenuItem_Click(object sender, EventArgs e)
{
//Fullscreen
}
private void showEqualiserToolStripMenuItem_Click(object sender, EventArgs e)
{
//Equaliser
}
private void columnsToolStripMenuItem_Click(object sender, EventArgs e)
{
playlistView.ColumnChooser();
}
//private Banshee.Gui.Dialogs.LogCoreDialog log_viewer = null;
private void showLogToolStripMenuItem_Click(object sender, EventArgs e)
{
// playlistView.ShowPlugArea = true;
//Show Logview
/*
if(log_viewer == null) {
log_viewer = new Banshee.Gui.Dialogs.LogCoreDialog(LogCore.Instance, WindowPlayer);
log_viewer.Response += delegate {
log_viewer.Hide();
};
log_viewer.DeleteEvent += delegate {
log_viewer.Destroy();
log_viewer = null;
};
}
log_viewer.Show();
*/
}
private enum SearchTrackCriteria
{
Artist,
Album,
Genre
}
private void jumpToPlayingToolStripMenuItem_Click(object sender, EventArgs e)
{
playlistView.ScrollToPlaying();
playlistView.SelectPlaying();
}
private void byAlbumToolStripMenuItem_Click(object sender, EventArgs e)
{
SearchBySelectedTrack(SearchTrackCriteria.Artist);
}
private void byArtistToolStripMenuItem_Click(object sender, EventArgs e)
{
SearchBySelectedTrack(SearchTrackCriteria.Artist);
}
private void byGenreToolStripMenuItem_Click(object sender, EventArgs e)
{
SearchBySelectedTrack(SearchTrackCriteria.Artist);
}
private void SearchBySelectedTrack(SearchTrackCriteria criteria)
{
//TODO Cornel fix this in the morning
/*if (playlistView.Selection.CountSelectedRows() <= 0)
{
return;
}
*/
TrackInfo track = playlistModel.SelectedTrack;
if (track == null)
{
return;
}
// suspend the search functionality (for performance reasons)
suspendSearch = true;
switch (criteria)
{
case SearchTrackCriteria.Album:
this.searchEntry.Field = Catalog.GetString("Album Title");
searchEntry.Query = track.Album;
break;
case SearchTrackCriteria.Artist:
searchEntry.Field = Catalog.GetString("Artist Name");
searchEntry.Query = track.Artist;
break;
case SearchTrackCriteria.Genre:
searchEntry.Field = Catalog.GetString("Genre");
searchEntry.Query = track.Genre;
break;
} suspendSearch = false;
OnSimpleSearch(this, null);
playlistView.Select();
}
private void versionInfoToolStripMenuItem_Click(object sender, EventArgs e)
{
//Banshee.Gui.Dialogs.VersionInformationDialog dialog = new Banshee.Gui.Dialogs.VersionInformationDialog();
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
//Banshee.Gui.Dialogs.AboutDialog about = new Banshee.Gui.Dialogs.AboutDialog();
}
private void event_panel_VisibleChanged(object sender, EventArgs e)
{
if(sourceView != null)
sourceView.BringToFront();
}
private void propertiesToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Banshee.Base.Gui.Dialogs.TrackEditor propEdit = new Banshee.Base.Gui.Dialogs.TrackEditor(playlistView.SelectedTrackInfoMultiple);
propEdit.ShowDialog(this);
playlistView.Refresh();
}
private void shuffle_toggle_button_Click(object sender, EventArgs e)
{
if (playlistModel.Shuffle)
{
playlistModel.Shuffle = false;
shuffle_toggle_button.Values.Image = Properties.Resources.media_playlist_continuous;
}
else
{
playlistModel.Shuffle = true;
shuffle_toggle_button.Values.Image = Properties.Resources.media_playlist_shuffle;
}
}
private void repeat_toggle_button_Click(object sender, EventArgs e)
{
if (playlistModel.Repeat == RepeatMode.All)
{
SetRepeatMode(RepeatMode.Single);
repeat_toggle_button.Values.Image = Properties.Resources.media_repeat_single;
}
else if (playlistModel.Repeat == RepeatMode.Single)
{
SetRepeatMode(RepeatMode.None);
repeat_toggle_button.Values.Image = Properties.Resources.media_repeat_none;
}
else if(playlistModel.Repeat == RepeatMode.None)
{
SetRepeatMode(RepeatMode.All);
repeat_toggle_button.Values.Image = Properties.Resources.media_repeat_all;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
UpdateViewName(SourceManager.ActiveSource, string.Format("{0} out of {1} results for '{2}'", playlistModel.Count(), SourceManager.ActiveSource.Count, SourceManager.ActiveSource.FilterQuery));
}
private void SourceSplitter_Panel1_Resize(object sender, EventArgs e)
{
cover_art_view.Height = cover_art_view.Width;
}
private void sync_dap_button_Click(object sender, EventArgs e)
{
if (SourceManager.ActiveSource is DapSource)
{
DapSource source = (DapSource)SourceManager.ActiveSource;
source.Device.Save();
}
}
private void blueToolStripMenuItem_Click(object sender, EventArgs e)
{
Setrenderer(((ToolStripMenuItem)sender).Text);
}
void Setrenderer(string style)
{
switch (style)
{
case "Blue":
Manager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Blue;
blueToolStripMenuItem.Checked = true;
silverToolStripMenuItem.Checked = false;
blackToolStripMenuItem.Checked = false;
break;
case "Silver":
Manager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Silver;
blueToolStripMenuItem.Checked = false;
silverToolStripMenuItem.Checked = true;
blackToolStripMenuItem.Checked = false;
break;
case "Black":
Manager.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Black;
blueToolStripMenuItem.Checked = false;
silverToolStripMenuItem.Checked = false;
blackToolStripMenuItem.Checked = true;
break;
}
Color back = Manager.GlobalPalette.GetBackColor1(ComponentFactory.Krypton.Toolkit.PaletteBackStyle.PanelClient, ComponentFactory.Krypton.Toolkit.PaletteState.Normal);
Color fore = Manager.GlobalPalette.ColorTable.MenuItemText;
playlist_header_event_box.BackColor = back;
playlist_header_event_box.ForeColor = fore;
seek_slider.ViewColor = back;
Properties.Settings.Default.style = style;
Properties.Settings.Default.Save();
}
private void kryptonPalette1_PalettePaint(object sender, ComponentFactory.Krypton.Toolkit.PaletteLayoutEventArgs e)
{
playlistView.Invalidate();
}
private void posTimer_Tick(object sender, EventArgs e)
{
Application.DoEvents();
OnPlayerEngineTick();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Impl.Binary
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using Apache.Ignite.Core.Binary;
using Apache.Ignite.Core.Impl.Binary.IO;
using Apache.Ignite.Core.Impl.Binary.Structure;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Binary reader implementation.
/// </summary>
internal class BinaryReader : IBinaryReader, IBinaryRawReader
{
/** Marshaller. */
private readonly Marshaller _marsh;
/** Parent builder. */
private readonly BinaryObjectBuilder _builder;
/** Handles. */
private BinaryReaderHandleDictionary _hnds;
/** Detach flag. */
private bool _detach;
/** Binary read mode. */
private BinaryMode _mode;
/** Current frame. */
private Frame _frame;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="marsh">Marshaller.</param>
/// <param name="stream">Input stream.</param>
/// <param name="mode">The mode.</param>
/// <param name="builder">Builder.</param>
public BinaryReader
(Marshaller marsh,
IBinaryStream stream,
BinaryMode mode,
BinaryObjectBuilder builder)
{
_marsh = marsh;
_mode = mode;
_builder = builder;
_frame.Pos = stream.Position;
Stream = stream;
}
/// <summary>
/// Gets the marshaller.
/// </summary>
public Marshaller Marshaller
{
get { return _marsh; }
}
/// <summary>
/// Gets the mode.
/// </summary>
public BinaryMode Mode
{
get { return _mode; }
}
/** <inheritdoc /> */
public IBinaryRawReader GetRawReader()
{
MarkRaw();
return this;
}
/** <inheritdoc /> */
public bool ReadBoolean(string fieldName)
{
return ReadField(fieldName, r => r.ReadBoolean(), BinaryUtils.TypeBool);
}
/** <inheritdoc /> */
public bool ReadBoolean()
{
return Stream.ReadBool();
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public bool[] ReadBooleanArray()
{
return Read(BinaryUtils.ReadBooleanArray, BinaryUtils.TypeArrayBool);
}
/** <inheritdoc /> */
public byte ReadByte(string fieldName)
{
return ReadField(fieldName, ReadByte, BinaryUtils.TypeByte);
}
/** <inheritdoc /> */
public byte ReadByte()
{
return Stream.ReadByte();
}
/** <inheritdoc /> */
public byte[] ReadByteArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public byte[] ReadByteArray()
{
return Read(BinaryUtils.ReadByteArray, BinaryUtils.TypeArrayByte);
}
/** <inheritdoc /> */
public short ReadShort(string fieldName)
{
return ReadField(fieldName, ReadShort, BinaryUtils.TypeShort);
}
/** <inheritdoc /> */
public short ReadShort()
{
return Stream.ReadShort();
}
/** <inheritdoc /> */
public short[] ReadShortArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public short[] ReadShortArray()
{
return Read(BinaryUtils.ReadShortArray, BinaryUtils.TypeArrayShort);
}
/** <inheritdoc /> */
public char ReadChar(string fieldName)
{
return ReadField(fieldName, ReadChar, BinaryUtils.TypeChar);
}
/** <inheritdoc /> */
public char ReadChar()
{
return Stream.ReadChar();
}
/** <inheritdoc /> */
public char[] ReadCharArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public char[] ReadCharArray()
{
return Read(BinaryUtils.ReadCharArray, BinaryUtils.TypeArrayChar);
}
/** <inheritdoc /> */
public int ReadInt(string fieldName)
{
return ReadField(fieldName, ReadInt, BinaryUtils.TypeInt);
}
/** <inheritdoc /> */
public int ReadInt()
{
return Stream.ReadInt();
}
/** <inheritdoc /> */
public int[] ReadIntArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public int[] ReadIntArray()
{
return Read(BinaryUtils.ReadIntArray, BinaryUtils.TypeArrayInt);
}
/** <inheritdoc /> */
public long ReadLong(string fieldName)
{
return ReadField(fieldName, ReadLong, BinaryUtils.TypeLong);
}
/** <inheritdoc /> */
public long ReadLong()
{
return Stream.ReadLong();
}
/** <inheritdoc /> */
public long[] ReadLongArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public long[] ReadLongArray()
{
return Read(BinaryUtils.ReadLongArray, BinaryUtils.TypeArrayLong);
}
/** <inheritdoc /> */
public float ReadFloat(string fieldName)
{
return ReadField(fieldName, ReadFloat, BinaryUtils.TypeFloat);
}
/** <inheritdoc /> */
public float ReadFloat()
{
return Stream.ReadFloat();
}
/** <inheritdoc /> */
public float[] ReadFloatArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public float[] ReadFloatArray()
{
return Read(BinaryUtils.ReadFloatArray, BinaryUtils.TypeArrayFloat);
}
/** <inheritdoc /> */
public double ReadDouble(string fieldName)
{
return ReadField(fieldName, ReadDouble, BinaryUtils.TypeDouble);
}
/** <inheritdoc /> */
public double ReadDouble()
{
return Stream.ReadDouble();
}
/** <inheritdoc /> */
public double[] ReadDoubleArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public double[] ReadDoubleArray()
{
return Read(BinaryUtils.ReadDoubleArray, BinaryUtils.TypeArrayDouble);
}
/** <inheritdoc /> */
public decimal? ReadDecimal(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal? ReadDecimal()
{
return Read(BinaryUtils.ReadDecimal, BinaryUtils.TypeDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public decimal?[] ReadDecimalArray()
{
return Read(BinaryUtils.ReadDecimalArray, BinaryUtils.TypeArrayDecimal);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime? ReadTimestamp()
{
return Read(BinaryUtils.ReadTimestamp, BinaryUtils.TypeTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public DateTime?[] ReadTimestampArray()
{
return Read(BinaryUtils.ReadTimestampArray, BinaryUtils.TypeArrayTimestamp);
}
/** <inheritdoc /> */
public string ReadString(string fieldName)
{
return ReadField(fieldName, BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string ReadString()
{
return Read(BinaryUtils.ReadString, BinaryUtils.TypeString);
}
/** <inheritdoc /> */
public string[] ReadStringArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public string[] ReadStringArray()
{
return Read(r => BinaryUtils.ReadArray<string>(r, false), BinaryUtils.TypeArrayString);
}
/** <inheritdoc /> */
public Guid? ReadGuid(string fieldName)
{
return ReadField<Guid?>(fieldName, r => BinaryUtils.ReadGuid(r), BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid? ReadGuid()
{
return Read<Guid?>(r => BinaryUtils.ReadGuid(r), BinaryUtils.TypeGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public Guid?[] ReadGuidArray()
{
return Read(r => BinaryUtils.ReadArray<Guid?>(r, false), BinaryUtils.TypeArrayGuid);
}
/** <inheritdoc /> */
public T ReadEnum<T>(string fieldName)
{
return SeekField(fieldName) ? ReadEnum<T>() : default(T);
}
/** <inheritdoc /> */
public T ReadEnum<T>()
{
var hdr = ReadByte();
switch (hdr)
{
case BinaryUtils.HdrNull:
return default(T);
case BinaryUtils.TypeEnum:
return ReadEnum0<T>(this, _mode == BinaryMode.ForceBinary);
case BinaryUtils.TypeBinaryEnum:
return ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
case BinaryUtils.HdrFull:
// Unregistered enum written as serializable
Stream.Seek(-1, SeekOrigin.Current);
return ReadObject<T>();
default:
throw new BinaryObjectException(string.Format(
"Invalid header on enum deserialization. Expected: {0} or {1} or {2} but was: {3}",
BinaryUtils.TypeEnum, BinaryUtils.TypeBinaryEnum, BinaryUtils.HdrFull, hdr));
}
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T[] ReadEnumArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArrayEnum);
}
/** <inheritdoc /> */
public T ReadObject<T>(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (SeekField(fieldName))
return Deserialize<T>();
return default(T);
}
/** <inheritdoc /> */
public T ReadObject<T>()
{
return Deserialize<T>();
}
/** <inheritdoc /> */
public T[] ReadArray<T>(string fieldName)
{
return ReadField(fieldName, r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public T[] ReadArray<T>()
{
return Read(r => BinaryUtils.ReadArray<T>(r, true), BinaryUtils.TypeArray);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName)
{
return ReadCollection(fieldName, null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection()
{
return ReadCollection(null, null);
}
/** <inheritdoc /> */
public ICollection ReadCollection(string fieldName, Func<int, ICollection> factory,
Action<ICollection, object> adder)
{
return ReadField(fieldName, r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public ICollection ReadCollection(Func<int, ICollection> factory, Action<ICollection, object> adder)
{
return Read(r => BinaryUtils.ReadCollection(r, factory, adder), BinaryUtils.TypeCollection);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName)
{
return ReadDictionary(fieldName, null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary()
{
return ReadDictionary((Func<int, IDictionary>) null);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(string fieldName, Func<int, IDictionary> factory)
{
return ReadField(fieldName, r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/** <inheritdoc /> */
public IDictionary ReadDictionary(Func<int, IDictionary> factory)
{
return Read(r => BinaryUtils.ReadDictionary(r, factory), BinaryUtils.TypeDictionary);
}
/// <summary>
/// Enable detach mode for the next object read.
/// </summary>
public BinaryReader DetachNext()
{
_detach = true;
return this;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>Deserialized object.</returns>
public T Deserialize<T>(Type typeOverride = null)
{
T res;
// ReSharper disable once CompareNonConstrainedGenericWithNull
if (!TryDeserialize(out res, typeOverride) && default(T) != null)
throw new BinaryObjectException(string.Format("Invalid data on deserialization. " +
"Expected: '{0}' But was: null", typeof (T)));
return res;
}
/// <summary>
/// Deserialize object.
/// </summary>
/// <param name="res">Deserialized object.</param>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>
/// Deserialized object.
/// </returns>
public bool TryDeserialize<T>(out T res, Type typeOverride = null)
{
int pos = Stream.Position;
byte hdr = Stream.ReadByte();
var doDetach = _detach; // save detach flag into a var and reset so it does not go deeper
_detach = false;
switch (hdr)
{
case BinaryUtils.HdrNull:
res = default(T);
return false;
case BinaryUtils.HdrHnd:
res = ReadHandleObject<T>(pos, typeOverride);
return true;
case BinaryUtils.HdrFull:
res = ReadFullObject<T>(pos, typeOverride);
return true;
case BinaryUtils.TypeBinary:
res = ReadBinaryObject<T>(doDetach);
return true;
case BinaryUtils.TypeEnum:
res = ReadEnum0<T>(this, _mode == BinaryMode.ForceBinary);
return true;
case BinaryUtils.TypeBinaryEnum:
res = ReadEnum0<T>(this, _mode != BinaryMode.Deserialize);
return true;
}
if (BinarySystemHandlers.TryReadSystemType(hdr, this, out res))
return true;
throw new BinaryObjectException("Invalid header on deserialization [pos=" + pos + ", hdr=" + hdr + ']');
}
/// <summary>
/// Gets the flag indicating that there is custom type information in raw region.
/// </summary>
public bool GetCustomTypeDataFlag()
{
return _frame.Hdr.IsCustomDotNetType;
}
/// <summary>
/// Reads the binary object.
/// </summary>
private T ReadBinaryObject<T>(bool doDetach)
{
var len = Stream.ReadInt();
var binaryBytesPos = Stream.Position;
if (_mode != BinaryMode.Deserialize)
return TypeCaster<T>.Cast(ReadAsBinary(binaryBytesPos, len, doDetach));
Stream.Seek(len, SeekOrigin.Current);
var offset = Stream.ReadInt();
var retPos = Stream.Position;
Stream.Seek(binaryBytesPos + offset, SeekOrigin.Begin);
_mode = BinaryMode.KeepBinary;
try
{
return Deserialize<T>();
}
finally
{
_mode = BinaryMode.Deserialize;
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the binary object in binary form.
/// </summary>
private BinaryObject ReadAsBinary(int binaryBytesPos, int dataLen, bool doDetach)
{
try
{
Stream.Seek(dataLen + binaryBytesPos, SeekOrigin.Begin);
var offs = Stream.ReadInt(); // offset inside data
var pos = binaryBytesPos + offs;
var hdr = BinaryObjectHeader.Read(Stream, pos);
if (!doDetach)
return new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
Stream.Seek(pos, SeekOrigin.Begin);
return new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
finally
{
Stream.Seek(binaryBytesPos + dataLen + 4, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the full object.
/// </summary>
/// <param name="pos">The position.</param>
/// <param name="typeOverride">The type override.
/// There can be multiple versions of the same type when peer assembly loading is enabled.
/// Only first one is registered in Marshaller.
/// This parameter specifies exact type to be instantiated.</param>
/// <returns>Resulting object</returns>
[SuppressMessage("Microsoft.Performance", "CA1804:RemoveUnusedLocals", MessageId = "hashCode")]
private T ReadFullObject<T>(int pos, Type typeOverride)
{
var hdr = BinaryObjectHeader.Read(Stream, pos);
// Validate protocol version.
BinaryUtils.ValidateProtocolVersion(hdr.Version);
try
{
// Already read this object?
object hndObj;
if (_hnds != null && _hnds.TryGetValue(pos, out hndObj))
return (T) hndObj;
if (hdr.IsUserType && _mode == BinaryMode.ForceBinary)
{
BinaryObject portObj;
if (_detach)
{
Stream.Seek(pos, SeekOrigin.Begin);
portObj = new BinaryObject(_marsh, Stream.ReadByteArray(hdr.Length), 0, hdr);
}
else
portObj = new BinaryObject(_marsh, Stream.GetArray(), pos, hdr);
T obj = _builder == null ? TypeCaster<T>.Cast(portObj) : TypeCaster<T>.Cast(_builder.Child(portObj));
AddHandle(pos, obj);
return obj;
}
else
{
// Find descriptor.
var desc = hdr.TypeId == BinaryUtils.TypeUnregistered
? _marsh.GetDescriptor(ReadUnregisteredType(typeOverride))
: _marsh.GetDescriptor(hdr.IsUserType, hdr.TypeId, true, null, typeOverride);
// Instantiate object.
if (desc.Type == null)
{
throw new BinaryObjectException(string.Format(
"No matching type found for object [typeId={0}, typeName={1}]. " +
"This usually indicates that assembly with specified type is not loaded on a node. " +
"When using Apache.Ignite.exe, make sure to load assemblies with -assembly parameter. " +
"Alternatively, set IgniteConfiguration.PeerAssemblyLoadingEnabled to true.",
desc.TypeId, desc.TypeName));
}
// Preserve old frame.
var oldFrame = _frame;
// Set new frame.
_frame.Hdr = hdr;
_frame.Pos = pos;
SetCurSchema(desc);
_frame.Struct = new BinaryStructureTracker(desc, desc.ReaderTypeStructure);
_frame.Raw = false;
// Read object.
var obj = desc.Serializer.ReadBinary<T>(this, desc, pos, typeOverride);
_frame.Struct.UpdateReaderStructure();
// Restore old frame.
_frame = oldFrame;
return obj;
}
}
finally
{
// Advance stream pointer.
Stream.Seek(pos + hdr.Length, SeekOrigin.Begin);
}
}
/// <summary>
/// Reads the unregistered type.
/// </summary>
private Type ReadUnregisteredType(Type knownType)
{
var typeName = ReadString(); // Must read always.
return knownType ?? Type.GetType(typeName, true);
}
/// <summary>
/// Sets the current schema.
/// </summary>
private void SetCurSchema(IBinaryTypeDescriptor desc)
{
_frame.SchemaMap = null;
if (_frame.Hdr.HasSchema)
{
_frame.Schema = desc.Schema.Get(_frame.Hdr.SchemaId);
if (_frame.Schema == null)
{
_frame.Schema = ReadSchema(desc.TypeId);
desc.Schema.Add(_frame.Hdr.SchemaId, _frame.Schema);
}
}
else
{
_frame.Schema = null;
}
}
/// <summary>
/// Reads the schema.
/// </summary>
private int[] ReadSchema(int typeId)
{
if (_frame.Hdr.IsCompactFooter)
{
// Get schema from Java
var ignite = Marshaller.Ignite;
Debug.Assert(typeId != BinaryUtils.TypeUnregistered);
var schema = ignite == null
? null
: ignite.BinaryProcessor.GetSchema(_frame.Hdr.TypeId, _frame.Hdr.SchemaId);
if (schema == null)
throw new BinaryObjectException("Cannot find schema for object with compact footer [" +
"typeId=" + typeId + ", schemaId=" + _frame.Hdr.SchemaId + ']');
return schema;
}
var pos = Stream.Position;
Stream.Seek(_frame.Pos + _frame.Hdr.SchemaOffset, SeekOrigin.Begin);
var count = _frame.Hdr.SchemaFieldCount;
var offsetSize = _frame.Hdr.SchemaFieldOffsetSize;
var res = new int[count];
for (int i = 0; i < count; i++)
{
res[i] = Stream.ReadInt();
Stream.Seek(offsetSize, SeekOrigin.Current);
}
Stream.Seek(pos, SeekOrigin.Begin);
return res;
}
/// <summary>
/// Reads the handle object.
/// </summary>
private T ReadHandleObject<T>(int pos, Type typeOverride)
{
// Get handle position.
int hndPos = pos - Stream.ReadInt();
int retPos = Stream.Position;
try
{
object hndObj;
if (_builder == null || !_builder.TryGetCachedField(hndPos, out hndObj))
{
if (_hnds == null || !_hnds.TryGetValue(hndPos, out hndObj))
{
// No such handler, i.e. we trying to deserialize inner object before deserializing outer.
Stream.Seek(hndPos, SeekOrigin.Begin);
hndObj = Deserialize<T>(typeOverride);
}
// Notify builder that we deserialized object on other location.
if (_builder != null)
_builder.CacheField(hndPos, hndObj);
}
return (T) hndObj;
}
finally
{
// Position stream to correct place.
Stream.Seek(retPos, SeekOrigin.Begin);
}
}
/// <summary>
/// Adds a handle to the dictionary.
/// </summary>
/// <param name="pos">Position.</param>
/// <param name="obj">Object.</param>
internal void AddHandle(int pos, object obj)
{
if (_hnds == null)
_hnds = new BinaryReaderHandleDictionary(pos, obj);
else
_hnds.Add(pos, obj);
}
/// <summary>
/// Underlying stream.
/// </summary>
public IBinaryStream Stream
{
get;
private set;
}
/// <summary>
/// Seeks to raw data.
/// </summary>
internal void SeekToRaw()
{
Stream.Seek(_frame.Pos + _frame.Hdr.GetRawOffset(Stream, _frame.Pos), SeekOrigin.Begin);
}
/// <summary>
/// Mark current output as raw.
/// </summary>
private void MarkRaw()
{
if (!_frame.Raw)
{
_frame.Raw = true;
SeekToRaw();
}
}
/// <summary>
/// Seeks the field by name.
/// </summary>
private bool SeekField(string fieldName)
{
if (_frame.Raw)
throw new BinaryObjectException("Cannot read named fields after raw data is read.");
if (!_frame.Hdr.HasSchema)
return false;
var actionId = _frame.Struct.CurStructAction;
var fieldId = _frame.Struct.GetFieldId(fieldName);
if (_frame.Schema == null || actionId >= _frame.Schema.Length || fieldId != _frame.Schema[actionId])
{
_frame.SchemaMap = _frame.SchemaMap ?? BinaryObjectSchemaSerializer.ReadSchema(Stream, _frame.Pos,
_frame.Hdr, () => _frame.Schema).ToDictionary();
_frame.Schema = null; // read order is different, ignore schema for future reads
int pos;
if (!_frame.SchemaMap.TryGetValue(fieldId, out pos))
return false;
Stream.Seek(pos + _frame.Pos, SeekOrigin.Begin);
}
return true;
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<IBinaryStream, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<BinaryReader, T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Seeks specified field and invokes provided func.
/// </summary>
private T ReadField<T>(string fieldName, Func<T> readFunc, byte expHdr)
{
return SeekField(fieldName) ? Read(readFunc, expHdr) : default(T);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<BinaryReader, T> readFunc, byte expHdr)
{
return Read(() => readFunc(this), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<IBinaryStream, T> readFunc, byte expHdr)
{
return Read(() => readFunc(Stream), expHdr);
}
/// <summary>
/// Reads header and invokes specified func if the header is not null.
/// </summary>
private T Read<T>(Func<T> readFunc, byte expHdr)
{
var hdr = ReadByte();
if (hdr == BinaryUtils.HdrNull)
return default(T);
if (hdr == BinaryUtils.HdrHnd)
return ReadHandleObject<T>(Stream.Position - 1, null);
if (expHdr != hdr)
throw new BinaryObjectException(string.Format("Invalid header on deserialization. " +
"Expected: {0} but was: {1}", expHdr, hdr));
return readFunc();
}
/// <summary>
/// Reads the enum.
/// </summary>
private static T ReadEnum0<T>(BinaryReader reader, bool keepBinary)
{
var enumType = reader.ReadInt();
var enumValue = reader.ReadInt();
if (!keepBinary)
{
return BinaryUtils.GetEnumValue<T>(enumValue, enumType, reader.Marshaller);
}
return TypeCaster<T>.Cast(new BinaryEnum(enumType, enumValue, reader.Marshaller));
}
/// <summary>
/// Stores current reader stack frame.
/// </summary>
private struct Frame
{
/** Current position. */
public int Pos;
/** Current raw flag. */
public bool Raw;
/** Current type structure tracker. */
public BinaryStructureTracker Struct;
/** Current schema. */
public int[] Schema;
/** Current schema with positions. */
public Dictionary<int, int> SchemaMap;
/** Current header. */
public BinaryObjectHeader Hdr;
}
}
}
| |
#region copyright
// VZF
// Copyright (C) 2014-2016 Vladimir Zakharov
//
// http://www.code.coolhobby.ru/
// File DB.cs created on 2.6.2015 in 6:31 AM.
// Last changed on 5.21.2016 in 1:13 PM.
// 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
namespace YAF.Providers.Membership
{
using System;
using System.Data;
using System.Web.Security;
using YAF.Classes;
using YAF.Core;
using VZF.Data.DAL;
/// <summary>
/// The db.
/// </summary>
public static class Db
{
public static void __ChangePassword(string connectionStringName, string appName, string userName, string newPassword, string newSalt, int passwordFormat, string newPasswordAnswer)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_password", newPassword));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordsalt", newSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordformat", passwordFormat));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordanswer", newPasswordAnswer));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_changepassword", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public static void __ChangePasswordQuestionAndAnswer(string connectionStringName, string appName, string userName, string passwordQuestion, string passwordAnswer)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordquestion", passwordQuestion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordanswer", passwordAnswer));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_changepasswordquestionandanswer", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public static void __CreateUser(string connectionStringName, string appName, string userName, string password, string passwordSalt, int passwordFormat, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_password", password));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordsalt", passwordSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordformat", passwordFormat.ToString()));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_email", email));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordquestion", passwordQuestion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordanswer", passwordAnswer));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_isapproved", isApproved));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newuserkey", Guid.NewGuid()));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_utctimestamp", DateTime.UtcNow));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_userkey", providerUserKey, ParameterDirection.InputOutput));
sc.CommandText.AppendObjectQuery("prov_createuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure, true);
providerUserKey = sc.Parameters["i_userkey"].Value;
}
}
public static void __DeleteUser(string connectionStringName, string appName, string userName, bool deleteAllRelatedData)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_deleteallrelated", deleteAllRelatedData));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_deleteuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public static DataTable __FindUsersByEmail(string connectionStringName, string appName, string emailToMatch, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_emailaddress", emailToMatch));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_findusersbyemail", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public static DataTable __FindUsersByName(string connectionStringName, string appName, string usernameToMatch, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", usernameToMatch));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_findusersbyname", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public static DataTable __GetAllUsers(string connectionStringName, string appName, int pageIndex, int pageSize)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pageindex", pageIndex));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_pagesize", pageSize));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_getallusers", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public static int __GetNumberOfUsersOnline(string connectionStringName, string appName, int TimeWindow)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_timewindow", TimeWindow));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_currenttimeutc", DateTime.UtcNow));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_returnvalue", null, ParameterDirection.ReturnValue));
sc.CommandText.AppendObjectQuery("prov_getnumberofusersonline", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
return Convert.ToInt32(sc.Parameters["i_returnvalue"].Value);
}
}
public static DataRow __GetUser(string connectionStringName, string appName, object providerUserKey, string userName, bool userIsOnline)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_userkey", providerUserKey));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_userisonline", userIsOnline));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_utctimestamp", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_getuser", connectionStringName);
using (var dt = sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, true))
{
return dt.Rows.Count > 0 ? dt.Rows[0] : null;
}
}
}
public static DataTable __GetUserPasswordInfo(string connectionStringName, string appName, string userName, bool updateUser)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_userkey", DBNull.Value));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_userisonline", updateUser));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_utctimestamp", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_getuser", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public static DataTable __GetUserNameByEmail(string connectionStringName, string appName, string email)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_email", email));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_getusernamebyemail", connectionStringName);
return sc.ExecuteDataTableFromReader(CommandBehavior.Default, CommandType.StoredProcedure, false);
}
}
public static void __ResetPassword(string connectionStringName, string appName, string userName, string password, string passwordSalt, int passwordFormat, int maxInvalidPasswordAttempts, int passwordAttemptWindow)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_password", password));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordsalt", passwordSalt));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_passwordformat", passwordFormat));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_maxinvalidattempts", maxInvalidPasswordAttempts));
sc.Parameters.Add(sc.CreateParameter(DbType.Int32, "i_passwordattemptwindow", passwordAttemptWindow));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_currenttimeutc", DateTime.UtcNow));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_resetpassword", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public static void __UnlockUser(string connectionStringName, string appName, string userName)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", userName));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_unlockuser", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
public static int __UpdateUser(string connectionStringName, object appName, MembershipUser user, bool requiresUniqueEmail)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_applicationname", appName));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_userkey", user.ProviderUserKey));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_username", user.UserName));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_email", user.Email));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_comment", user.Comment));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_isapproved", user.IsApproved));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_lastlogin", user.LastLoginDate));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_lastactivity", user.LastActivityDate));
sc.Parameters.Add(sc.CreateParameter(DbType.Boolean, "i_uniqueemail", requiresUniqueEmail));
sc.Parameters.Add(sc.CreateParameter(DbType.Guid, "i_newguid", Guid.NewGuid()));
sc.CommandText.AppendObjectQuery("prov_updateuser", connectionStringName);
return Convert.ToInt32(sc.ExecuteScalar(CommandType.StoredProcedure));
}
}
public static void UpgradeMembership(string connectionStringName, int previousVersion, int newVersion)
{
using (var sc = new VzfSqlCommand(connectionStringName))
{
// sc.DataSource.ProviderName
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_PreviousVersion", previousVersion));
sc.Parameters.Add(sc.CreateParameter(DbType.String, "i_NewVersion", newVersion));
sc.Parameters.Add(sc.CreateParameter(DbType.DateTime, "i_UTCTIMESTAMP", DateTime.UtcNow));
sc.CommandText.AppendObjectQuery("prov_upgrade", connectionStringName);
sc.ExecuteNonQuery(CommandType.StoredProcedure);
}
}
}
}
| |
using System;
using System.Data.SQLite;
using System.Windows.Forms;
using System.Drawing;
using Simban;
using System.Collections.Generic;
using Model;
namespace PhoneNetwork
{
public enum MapMode : byte {
None = 0,
NewNode = 1,
EditNode = 2,
DeleteNode = 3,
NewEdge = 4,
EditEdge = 5,
DeleteEdge = 6,
EditMovingNode = 21,
NewEdgeSecondNode = 41,
};
public class Map: System.Windows.Forms.PictureBox
{
public static string[] MapModeTitles = new String[7] {"None", "New Node", "Edit Node", "Delete Node", "New Edge", "Edit Edge", "Delete Edge"};
public MapModel mapModel;
public MapMode mapMode;
Database database;
public Nodes nodes;
Edges edges;
MapData mapData ;
PointD mouseDelta;
public Map (Database database, Nodes nodes, Edges edges)
{
this.database = database;
this.mapModel = new MapModel(this.database, true);
this.nodes = nodes;
this.edges = edges;
this.mapMode = MapMode.None;
this.MouseClick += new MouseEventHandler(onClick);
this.MouseDoubleClick += HandleMouseDoubleClick;
this.MouseDown += new MouseEventHandler(onMouseDown);
this.MouseMove += new MouseEventHandler(onMouseMove);
this.MouseUp += new MouseEventHandler(onMouseUp);
}
void ShowNodeProperties (Node node)
{
NodeForm nodeForm = new NodeForm(node);
if (nodeForm.ShowDialog() == DialogResult.OK)
this.nodes.UpdateFirstSelected(nodeForm.node);
}
void ShowEdgeProperties (Edge edge)
{
EdgeForm edgeForm = new EdgeForm(edge);
if (edgeForm.ShowDialog() == DialogResult.OK)
this.edges.Update(edgeForm.edge);
}
void HandleMouseDoubleClick (object sender, MouseEventArgs e)
{
PointD location = this.MapToPoint (e.Location);
if (this.mapMode == MapMode.EditNode && this.nodes.SelectAtPoisition(location, true))
this.ShowNodeProperties(this.nodes.FirstSelected());
if (this.mapMode == MapMode.EditEdge && this.edges.SelectAtPoisition(location, true))
this.ShowEdgeProperties(this.edges.FirstSelected());
}
public void LoadMap (long id)
{
this.mapData = this.mapModel.LoadData(id);
}
PointD MapToPoint (Point point)
{
PointD result = new PointD((double)point.X * 100 / this.Image.Width,
(double)point.Y * 100 / this.Image.Height);
return result;
}
Point PointToMap (Point point)
{
Point result = new Point(point.X * this.Image.Width / 100,
point.Y * this.Image.Height / 100);
return result;
}
void onClick (object sender, MouseEventArgs e)
{
PointD location = this.MapToPoint (e.Location);
switch (this.mapMode) {
case MapMode.NewNode:
this.NewNode (location);
break;
case MapMode.DeleteNode:
this.DeleteNode (location);
break;
case MapMode.NewEdge:
this.NewEdge(location);
break;
case MapMode.NewEdgeSecondNode:
this.NewEdgeSecondNode(location);
break;
case MapMode.EditEdge:
this.EditEdge(location);
break;
case MapMode.DeleteEdge:
this.DeleteEdge(location);
break;
}
Invalidate ();
}
public void NewNode (PointD location)
{
string nodeName = "New node";
if (Dialog.InputBox("New Node", "Enter name of new node", ref nodeName) == DialogResult.OK) {
this.nodes.CreateNew (nodeName, location.X, location.Y);
}
}
void DeleteNode (PointD location)
{
if (this.nodes.SelectAtPoisition(location, true))
{
Invalidate();
DialogResult confirm = MessageBox.Show ("Delete the selected node " + this.nodes.FirstSelected().name, "Confrim delete", MessageBoxButtons.YesNo);
if (confirm == DialogResult.Yes){
this.nodes.DeleteSelected();
this.nodes.LoadAll();
this.edges.LoadAll();
Invalidate();
}
}
}
public bool MoveNodeStart (PointD location)
{
if (!this.nodes.SelectAtPoisition(location, true))
return false;
this.mouseDelta = new PointD(this.nodes.FirstSelected().left - location.X,
this.nodes.FirstSelected().top - location.Y);
this.mapMode = MapMode.EditMovingNode;
return true;
}
public Point NodePointOnMap(double left, double top)
{
Point result = new Point(Convert.ToInt32(left * this.Image.Width / 100 + this.mapData.left),
Convert.ToInt32(top * this.Image.Height / 100 + this.mapData.top));
return result;
}
void DrawNode (PaintEventArgs pe, Node node)
{
Color[] colors = new Color[2] {
Color.FromArgb (50, 50, 255),
Color.FromArgb (150, 155, 255)};
if (this.nodes.IsSelected(node))
colors = new Color[3] {
Color.FromArgb (255, 200, 200),
Color.FromArgb (200, 150, 150),
Color.FromArgb (150, 50, 50)
};
System.Drawing.Pen pen;
var point = this.NodePointOnMap (node.left, node.top);
Rectangle rect = new Rectangle (point, new Size (2, 2));
foreach (Color color in colors) {
pen = new System.Drawing.Pen (color);
pe.Graphics.DrawEllipse (pen, rect);
rect = new Rectangle(rect.Left - 1, rect.Top - 1, rect.Width + 2, rect.Height + 2);
}
}
void NewEdge (PointD location)
{
if (this.nodes.SelectAtPoisition (location, true))
this.mapMode = MapMode.NewEdgeSecondNode;
}
void NewEdgeSecondNode (PointD location)
{
if (this.nodes.SelectAtPoisition (location, false)) {
this.edges.CreateNew (this.nodes.FirstSelected (), this.nodes.SecondSelected ());
this.nodes.ClearSelection ();
this.mapMode = MapMode.NewEdge;
}
}
void EditEdge (PointD location)
{
this.edges.SelectAtPoisition(location, true);
}
void DeleteEdge (PointD location)
{
if (this.edges.SelectAtPoisition(location, true))
{
Invalidate();
Edge edge = this.edges.FirstSelected();
DialogResult confirm = MessageBox.Show ("Delete the edge between " + edge.node1.name + " and " + edge.node2.name + "?", "Confrim delete", MessageBoxButtons.YesNo);
if (confirm == DialogResult.Yes){
this.edges.DeleteSelected();
this.edges.LoadAll();
Invalidate();
}
}
}
void DrawEdge (Edge edge, ref PaintEventArgs pe)
{
System.Drawing.Pen pen = new System.Drawing.Pen (Color.Blue);
if (this.edges.IsSelected(edge))
pen.Color = Color.Red;
pe.Graphics.DrawLine (pen, this.NodePointOnMap (edge.node1.left, edge.node1.top), this.NodePointOnMap (edge.node2.left, edge.node2.top));
}
protected override void OnPaint (PaintEventArgs pe)
{
base.OnPaint (pe);
if (this.Image == null)
return;
foreach (Node node in nodes.nodes.Values) {
this.DrawNode(pe, node);
}
foreach (Edge edge in edges.edges.Values) {
DrawEdge (edge, ref pe);
}
}
void onMouseDown (object sedner, MouseEventArgs e)
{
PointD location = this.MapToPoint (e.Location);
if (this.mapMode == MapMode.EditNode) {
this.MoveNodeStart(location);
}
}
public void MoveNodeContinue (PointD location)
{
this.nodes.MoveFirstSelectedNode (location.X + this.mouseDelta.X,
location.Y + this.mouseDelta.Y);
}
void onMouseMove (object sender, MouseEventArgs e)
{
PointD location = this.MapToPoint (e.Location);
if (this.mapMode == MapMode.EditMovingNode && e.Button == System.Windows.Forms.MouseButtons.Left) {
MoveNodeContinue (location);
this.Invalidate();
}
}
public void MoveNodeFinish ()
{
this.mapMode = MapMode.EditNode;
this.nodes.UpdateFirstSelected ();
}
void onMouseUp (object sender, MouseEventArgs e)
{
if (this.mapMode == MapMode.EditMovingNode && e.Button == System.Windows.Forms.MouseButtons.Left) {
// if (this.nodes.FirstSelected().left != this.
MoveNodeFinish ();
}
}
}
}
| |
//=============================================================================
// System : EWSoftware Design Time Attributes and Editors
// File : PlugInConfigurationEditorDlg.cs
// Author : Eric Woodruff (Eric@EWoodruff.us)
// Updated : 12/06/2009
// Note : Copyright 2007-2009, Eric Woodruff, All rights reserved
// Compiler: Microsoft Visual C#
//
// This file contains the form used to select and edit the plug-in
// configurations.
//
// This code is published under the Microsoft Public License (Ms-PL). A copy
// of the license should be distributed with the code. It can also be found
// at the project website: http://SHFB.CodePlex.com. This notice, the
// author's name, and all copyright notices must remain intact in all
// applications, documentation, and source files.
//
// Version Date Who Comments
// ============================================================================
// 1.5.2.0 09/10/2007 EFW Created the code
//=============================================================================
using System;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.Xml;
using SandcastleBuilder.Utils;
using SandcastleBuilder.Utils.PlugIn;
namespace SandcastleBuilder.Utils.Design
{
/// <summary>
/// This is used to select and edit the plug-in configurations.
/// </summary>
/// <remarks>To be editable, the plug-in assembly must be present in
/// the <b>.\Plug-Ins</b> folder or a subfolder beneath it. The plug-ins
/// folder is found under the common application data folder.</remarks>
internal partial class PlugInConfigurationEditorDlg : Form
{
#region Private data members
// The current configurations
private PlugInConfigurationDictionary currentConfigs;
#endregion
//=====================================================================
// Methods, etc.
/// <summary>
/// Constructor
/// </summary>
/// <param name="configs">The current configurations</param>
internal PlugInConfigurationEditorDlg(
PlugInConfigurationDictionary configs)
{
int idx;
InitializeComponent();
currentConfigs = configs;
try
{
foreach(string key in PlugInManager.PlugIns.Keys)
lbAvailablePlugIns.Items.Add(key);
}
catch(ReflectionTypeLoadException loadEx)
{
System.Diagnostics.Debug.WriteLine(loadEx.ToString());
System.Diagnostics.Debug.WriteLine(
loadEx.LoaderExceptions[0].ToString());
MessageBox.Show("Unexpected error loading plug-ins: " +
loadEx.LoaderExceptions[0].Message,
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show("Unexpected error loading plug-ins: " +
ex.Message, Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
if(lbAvailablePlugIns.Items.Count != 0)
lbAvailablePlugIns.SelectedIndex = 0;
else
{
MessageBox.Show("No valid plug-ins found",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Information);
gbAvailablePlugIns.Enabled = gbProjectAddIns.Enabled = false;
}
foreach(string key in currentConfigs.Keys)
{
idx = lbProjectPlugIns.Items.Add(key);
lbProjectPlugIns.SetItemChecked(idx,
currentConfigs[key].Enabled);
}
if(lbProjectPlugIns.Items.Count != 0)
lbProjectPlugIns.SelectedIndex = 0;
else
btnConfigure.Enabled = btnDelete.Enabled = false;
}
/// <summary>
/// Close this form
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
/// <summary>
/// Update the plug-in details when the selected index changes
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void lbAvailablePlugIns_SelectedIndexChanged(object sender,
EventArgs e)
{
string key = (string)lbAvailablePlugIns.SelectedItem;
PlugInInfo info = PlugInManager.PlugIns[key];
txtPlugInCopyright.Text = info.Copyright;
txtPlugInVersion.Text = String.Format(CultureInfo.CurrentCulture,
"Version {0}", info.Version);
txtPlugInDescription.Text = info.Description;
}
/// <summary>
/// Update the enabled state of the plug-in based on its checked state
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void lbProjectPlugIns_ItemCheck(object sender,
ItemCheckEventArgs e)
{
string key = (string)lbProjectPlugIns.Items[e.Index];
bool newState = (e.NewValue == CheckState.Checked);
if(currentConfigs[key].Enabled != newState)
currentConfigs[key].Enabled = newState;
}
/// <summary>
/// Add the selected plug-in to the project with a default
/// configuration.
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnAddPlugIn_Click(object sender, EventArgs e)
{
string key = (string)lbAvailablePlugIns.SelectedItem;
int idx = lbProjectPlugIns.FindStringExact(key);
// Currently, no duplicates are allowed
if(idx != -1)
{
lbProjectPlugIns.SelectedIndex = idx;
return;
}
if(PlugInManager.IsSupported(key))
{
idx = lbProjectPlugIns.Items.Add(key);
if(idx != -1)
{
currentConfigs.Add(key, true, null);
lbProjectPlugIns.SelectedIndex = idx;
lbProjectPlugIns.SetItemChecked(idx, true);
btnConfigure.Enabled = btnDelete.Enabled = true;
currentConfigs.OnDictionaryChanged(new ListChangedEventArgs(
ListChangedType.ItemAdded, -1));
}
}
else
MessageBox.Show("The selected plug-in's version is not " +
"compatible with this version of the help file builder " +
"and cannot be used.", Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
/// <summary>
/// Edit the selected plug-in's project configuration
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnConfigure_Click(object sender, EventArgs e)
{
PlugInConfiguration plugInConfig;
string newConfig, currentConfig,
key = (string)lbProjectPlugIns.SelectedItem;
if(PlugInManager.IsSupported(key))
{
PlugInInfo info = PlugInManager.PlugIns[key];
using(IPlugIn plugIn = info.NewInstance())
{
plugInConfig = currentConfigs[key];
currentConfig = plugInConfig.Configuration;
newConfig = plugIn.ConfigurePlugIn(currentConfigs.ProjectFile,
currentConfig);
}
// Only store it if new or if it changed
if(currentConfig != newConfig)
plugInConfig.Configuration = newConfig;
}
else
MessageBox.Show("The selected plug-in either does not exist " +
"or is of a version that is not compatible with this " +
"version of the help file builder and cannot be used.",
Constants.AppName, MessageBoxButtons.OK,
MessageBoxIcon.Error);
}
/// <summary>
/// Delete the selected plug-in from the project
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnDelete_Click(object sender, EventArgs e)
{
string key = (string)lbProjectPlugIns.SelectedItem;
int idx = lbProjectPlugIns.SelectedIndex;
if(currentConfigs.ContainsKey(key))
{
currentConfigs.Remove(key);
currentConfigs.OnDictionaryChanged(new ListChangedEventArgs(
ListChangedType.ItemDeleted, -1));
lbProjectPlugIns.Items.RemoveAt(idx);
if(lbProjectPlugIns.Items.Count == 0)
btnConfigure.Enabled = btnDelete.Enabled = false;
else
if(idx < lbProjectPlugIns.Items.Count)
lbProjectPlugIns.SelectedIndex = idx;
else
lbProjectPlugIns.SelectedIndex = idx - 1;
}
}
/// <summary>
/// View help for this form
/// </summary>
/// <param name="sender">The sender of the event</param>
/// <param name="e">The event arguments</param>
private void btnHelp_Click(object sender, EventArgs e)
{
string path = Path.GetDirectoryName(
Assembly.GetExecutingAssembly().Location);
try
{
#if DEBUG
path += @"\..\..\..\Doc\Help\SandcastleBuilder.chm";
#else
path += @"\SandcastleBuilder.chm";
#endif
Form form = new Form();
form.CreateControl();
Help.ShowHelp(form, path, HelpNavigator.Topic,
"html/e031b14e-42f0-47e1-af4c-9fed2b88cbc7.htm");
}
catch(Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
MessageBox.Show(String.Format(CultureInfo.CurrentCulture,
"Unable to open help file '{0}'. Reason: {1}",
path, ex.Message), Constants.AppName,
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
}
| |
using UnityEngine;
using System;
using System.Collections;
using System.Runtime.InteropServices;
namespace ChartboostSDK {
public class CBExternal {
private static bool initialized = false;
private static string _logTag = "ChartboostSDK";
public static void Log (string message) {
if(CBSettings.isLogging() && Debug.isDebugBuild)
Debug.Log(_logTag + "/" + message);
}
public static bool isInitialized() {
return initialized;
}
private static bool checkInitialized() {
if (initialized) {
return true;
} else {
Debug.LogError("The Chartboost SDK needs to be initialized before we can show any ads");
return false;
}
}
#if UNITY_EDITOR || (!UNITY_ANDROID && !UNITY_IPHONE)
/// Initializes the Chartboost plugin.
/// This must be called before using any other Chartboost features.
public static void init() {
Log("Unity : init with version " + Application.unityVersion);
// Will verify all the id and signatures against example ones.
CBSettings.getIOSAppId ();
CBSettings.getIOSAppSecret ();
CBSettings.getAndroidAppId ();
CBSettings.getAndroidAppSecret ();
CBSettings.getAmazonAppId ();
CBSettings.getAmazonAppSecret ();
}
/// Initialize the Chartboost plugin with a specific appId and signature
/// Either one of the init() methods must be called before using any other Chartboost feature
public static void initWithAppId(string appId, string appSignature) {
Log("Unity : initWithAppId " + appId + " and version " + Application.unityVersion);
}
/// Caches an interstitial.
public static void cacheInterstitial(CBLocation location) {
Log("Unity : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial.
public static bool hasInterstitial(CBLocation location) {
Log("Unity : hasInterstitial at location = " + location.ToString());
return false;
}
/// Loads an interstitial.
public static void showInterstitial(CBLocation location) {
Log("Unity : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen.
public static void cacheMoreApps(CBLocation location) {
Log("Unity : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached.
public static bool hasMoreApps(CBLocation location) {
Log("Unity : hasMoreApps at location = " + location.ToString());
return false;
}
/// Shows the more apps screen.
public static void showMoreApps(CBLocation location) {
Log("Unity : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
Log("Unity : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
Log("Unity : hasInPlay at location = " + location.ToString());
return false;
}
public static CBInPlay getInPlay(CBLocation location) {
Log("Unity : getInPlay at location = " + location.ToString());
return null;
}
/// Caches a rewarded video.
public static void cacheRewardedVideo(CBLocation location) {
Log("Unity : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video.
public static bool hasRewardedVideo(CBLocation location) {
Log("Unity : hasRewardedVideo at location = " + location.ToString());
return false;
}
/// Loads a rewarded video.
public static void showRewardedVideo(CBLocation location) {
Log("Unity : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
Log("Unity : chartBoostShouldDisplayMoreAppsCallbackResult");
}
/// Sets the name of the game object to be used by the Chartboost iOS SDK
public static void setGameObjectName(string name) {
Log("Unity : Set Game object name for callbacks to = " + name);
}
/// Set the custom id used for rewarded video call
public static void setCustomId(string id) {
Log("Unity : setCustomId to = " + id);
}
/// Get the custom id used for rewarded video call
public static string getCustomId() {
Log("Unity : getCustomId");
return "";
}
/// Confirm if an age gate passed or failed. When specified
/// Chartboost will wait for this call before showing the ios app store
public static void didPassAgeGate(bool pass) {
Log("Unity : didPassAgeGate with value = " + pass);
}
/// Open a URL using a Chartboost Custom Scheme
public static void handleOpenURL(string url, string sourceApp) {
Log("Unity : handleOpenURL at url = " + url + " for app = " + sourceApp);
}
/// Set to true if you would like to implement confirmation for ad clicks, such as an age gate.
/// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial.
public static void setShouldPauseClickForConfirmation(bool pause) {
Log("Unity : setShouldPauseClickForConfirmation with value = " + pause);
}
/// Set to false if you want interstitials to be disabled in the first user session
public static void setShouldRequestInterstitialsInFirstSession(bool request) {
Log("Unity : setShouldRequestInterstitialsInFirstSession with value = " + request);
}
public static bool getAutoCacheAds() {
Log("Unity : getAutoCacheAds");
return false;
}
public static void setAutoCacheAds(bool autoCacheAds) {
Log("Unity : setAutoCacheAds with value = " + autoCacheAds);
}
public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) {
Log("Unity : setStatusBarBehavior with value = " + statusBarBehavior);
}
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
Log("Unity : setShouldDisplayLoadingViewForMoreApps with value = " + shouldDisplay);
}
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
Log("Unity : setShouldPrefetchVideoContent with value = " + shouldPrefetch);
}
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) {
int levelType = (int)type;
Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description));
}
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) {
int levelType = (int)type;
Log(String.Format("Unity : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description));
}
public static void pause(bool paused) {
Log("Unity : pause");
}
/// Shuts down the Chartboost plugin
public static void destroy() {
Log("Unity : destroy");
}
/// Used to notify Chartboost that the Android back button has been pressed
/// Returns true to indicate that Chartboost has handled the event and it should not be further processed
public static bool onBackPressed() {
Log("Unity : onBackPressed");
return true;
}
public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) {
Log("Unity: trackInAppGooglePlayPurchaseEvent");
}
public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) {
Log("Unity: trackInAppAmazonStorePurchaseEvent");
}
public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) {
Log("Unity : trackInAppAppleStorePurchaseEvent");
}
public static bool isAnyViewVisible() {
Log("Unity : isAnyViewVisible");
return false;
}
public static void setMediation(CBMediation mediator, string version) {
Log("Unity : setMediation to = " + mediator.ToString() + " " + version);
}
public static Boolean isWebViewEnabled() {
Log("Unity : isWebViewEnabled");
return false;
}
#elif UNITY_IPHONE
[DllImport("__Internal")]
private static extern void _chartBoostInit(string appId, string appSignature, string unityVersion);
[DllImport("__Internal")]
private static extern bool _chartBoostIsAnyViewVisible();
[DllImport("__Internal")]
private static extern void _chartBoostCacheInterstitial(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasInterstitial(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowInterstitial(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheRewardedVideo(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasRewardedVideo(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowRewardedVideo(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheMoreApps(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasMoreApps(string location);
[DllImport("__Internal")]
private static extern void _chartBoostShowMoreApps(string location);
[DllImport("__Internal")]
private static extern void _chartBoostCacheInPlay(string location);
[DllImport("__Internal")]
private static extern bool _chartBoostHasInPlay(string location);
[DllImport("__Internal")]
private static extern IntPtr _chartBoostGetInPlay(string location);
[DllImport("__Internal")]
private static extern void _chartBoostSetCustomId(string id);
[DllImport("__Internal")]
private static extern void _chartBoostDidPassAgeGate(bool pass);
[DllImport("__Internal")]
private static extern string _chartBoostGetCustomId();
[DllImport("__Internal")]
private static extern void _chartBoostHandleOpenURL(string url, string sourceApp);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldPauseClickForConfirmation(bool pause);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldRequestInterstitialsInFirstSession(bool request);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayInterstitialCallbackResult(bool result);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayRewardedVideoCallbackResult(bool result);
[DllImport("__Internal")]
private static extern void _chartBoostShouldDisplayMoreAppsCallbackResult(bool result);
[DllImport("__Internal")]
private static extern bool _chartBoostGetAutoCacheAds();
[DllImport("__Internal")]
private static extern void _chartBoostSetAutoCacheAds(bool autoCacheAds);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldDisplayLoadingViewForMoreApps(bool shouldDisplay);
[DllImport("__Internal")]
private static extern void _chartBoostSetShouldPrefetchVideoContent(bool shouldDisplay);
[DllImport("__Internal")]
private static extern void _chartBoostTrackInAppPurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier);
[DllImport("__Internal")]
private static extern void _chartBoostSetGameObjectName(string name);
[DllImport("__Internal")]
private static extern void _chartBoostSetStatusBarBehavior(CBStatusBarBehavior statusBarBehavior);
[DllImport("__Internal")]
private static extern void _chartBoostTrackLevelInfo(String eventLabel, int levelType, int mainLevel, int subLevel, String description);
[DllImport("__Internal")]
private static extern void _chartBoostSetMediation(int mediator, string version);
/// Initializes the Chartboost plugin.
/// This must be called before using any other Chartboost features.
public static void init() {
// get the AppID and AppSecret from CBSettings
string appID = CBSettings.getIOSAppId ();
string appSecret = CBSettings.getIOSAppSecret ();
initWithAppId(appID, appSecret);
}
/// Initialize the Chartboost plugin with a specific appId and signature
/// Either one of the init() methods must be called before using any other Chartboost feature
public static void initWithAppId(string appId, string appSignature) {
Log("Unity : initWithAppId " + appId + " and version " + Application.unityVersion);
if (Application.platform == RuntimePlatform.IPhonePlayer)
_chartBoostInit(appId, appSignature, Application.unityVersion);
initialized = true;
}
/// Shuts down the Chartboost plugin
public static void destroy() {
Log("Unity : destroy");
}
/// Check to see if any chartboost ad or view is visible
public static bool isAnyViewVisible() {
bool handled = false;
if (!checkInitialized())
return handled;
handled = _chartBoostIsAnyViewVisible();
Log("iOS : isAnyViewVisible = " + handled );
return handled;
}
/// Caches an interstitial.
public static void cacheInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheInterstitial(location.ToString());
Log("iOS : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial.
public static bool hasInterstitial(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasInterstitial at location = " + location.ToString());
return _chartBoostHasInterstitial(location.ToString());
}
/// Loads an interstitial.
public static void showInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowInterstitial(location.ToString());
Log("iOS : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen.
public static void cacheMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheMoreApps(location.ToString());
Log("iOS : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached.
public static bool hasMoreApps(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasMoreApps at location = " + location.ToString());
return _chartBoostHasMoreApps(location.ToString());
}
/// Shows the more apps screen.
public static void showMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowMoreApps(location.ToString());
Log("iOS : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheInPlay(location.ToString());
Log("iOS : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasInPlay at location = " + location.ToString());
return _chartBoostHasInPlay(location.ToString());
}
public static CBInPlay getInPlay(CBLocation location) {
if (!checkInitialized())
return null;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return null;
}
IntPtr inPlayId = _chartBoostGetInPlay(location.ToString());
// No Inplay was available right now
if(inPlayId == IntPtr.Zero) {
return null;
}
CBInPlay inPlayAd = new CBInPlay(inPlayId);
Log("iOS : getInPlay at location = " + location.ToString());
return inPlayAd;
}
/// Caches a rewarded video.
public static void cacheRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostCacheRewardedVideo(location.ToString());
Log("iOS : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video.
public static bool hasRewardedVideo(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("iOS : hasRewardedVideo at location = " + location.ToString());
return _chartBoostHasRewardedVideo(location.ToString());
}
/// Loads a rewarded video.
public static void showRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_chartBoostShowRewardedVideo(location.ToString());
Log("iOS : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayInterstitialCallbackResult(result);
Log("iOS : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayRewardedVideoCallbackResult(result);
Log("iOS : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
if (!checkInitialized())
return;
_chartBoostShouldDisplayMoreAppsCallbackResult(result);
Log("iOS : chartBoostShouldDisplayMoreAppsCallbackResult");
}
/// Set the custom id used for rewarded video call
public static void setCustomId(string id) {
if (!checkInitialized())
return;
_chartBoostSetCustomId(id);
Log("iOS : setCustomId to = " + id);
}
/// Get the custom id used for rewarded video call
public static string getCustomId() {
if (!checkInitialized())
return null;
Log("iOS : getCustomId");
return _chartBoostGetCustomId();
}
/// Confirm if an age gate passed or failed. When specified
/// Chartboost will wait for this call before showing the ios app store
public static void didPassAgeGate(bool pass) {
if (!checkInitialized())
return;
_chartBoostDidPassAgeGate(pass);
Log("iOS : didPassAgeGate with value = " + pass);
}
/// Open a URL using a Chartboost Custom Scheme
public static void handleOpenURL(string url, string sourceApp) {
if (!checkInitialized())
return;
_chartBoostHandleOpenURL(url, sourceApp);
Log("iOS : handleOpenURL at url = " + url + " for app = " + sourceApp);
}
/// Set to true if you would like to implement confirmation for ad clicks, such as an age gate.
/// If using this feature, you should call CBBinding.didPassAgeGate() in your didClickInterstitial.
public static void setShouldPauseClickForConfirmation(bool pause) {
if (!checkInitialized())
return;
_chartBoostSetShouldPauseClickForConfirmation(pause);
Log("iOS : setShouldPauseClickForConfirmation with value = " + pause);
}
/// Set to false if you want interstitials to be disabled in the first user session
public static void setShouldRequestInterstitialsInFirstSession(bool request) {
if (!checkInitialized())
return;
_chartBoostSetShouldRequestInterstitialsInFirstSession(request);
Log("iOS : setShouldRequestInterstitialsInFirstSession with value = " + request);
}
/// Sets the name of the game object to be used by the Chartboost iOS SDK
public static void setGameObjectName(string name) {
_chartBoostSetGameObjectName(name);
Log("iOS : Set Game object name for callbacks to = " + name);
}
/// Check if we are autocaching ads after every show call
public static bool getAutoCacheAds() {
Log("iOS : getAutoCacheAds");
return _chartBoostGetAutoCacheAds();
}
/// Sets whether to autocache after every show call
public static void setAutoCacheAds(bool autoCacheAds) {
_chartBoostSetAutoCacheAds(autoCacheAds);
Log("iOS : Set AutoCacheAds to = " + autoCacheAds);
}
/// Sets whether to autocache after every show call
public static void setStatusBarBehavior(CBStatusBarBehavior statusBarBehavior) {
_chartBoostSetStatusBarBehavior(statusBarBehavior);
Log("iOS : Set StatusBarBehavior to = " + statusBarBehavior);
}
/// Sets whether to display loading view for moreapps
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
_chartBoostSetShouldDisplayLoadingViewForMoreApps(shouldDisplay);
Log("iOS : Set Should Display Loading View for More Apps to = " + shouldDisplay);
}
/// Sets whether to prefetch videos or not
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
_chartBoostSetShouldPrefetchVideoContent(shouldPrefetch);
Log("iOS : Set setShouldPrefetchVideoContent to = " + shouldPrefetch);
}
/// PIA Level Tracking info call
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) {
int levelType = (int)type;
_chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, subLevel, description);
Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description));
}
/// PIA Level Tracking info call
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) {
int levelType = (int)type;
_chartBoostTrackLevelInfo(eventLabel, levelType, mainLevel, 0, description);
Log(String.Format("iOS : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description));
}
/// IAP Tracking call
public static void trackInAppAppleStorePurchaseEvent(string receipt, string productTitle, string productDescription, string productPrice, string productCurrency, string productIdentifier) {
_chartBoostTrackInAppPurchaseEvent(receipt, productTitle, productDescription, productPrice, productCurrency, productIdentifier);
Log("iOS : trackInAppAppleStorePurchaseEvent");
}
public static void setMediation(CBMediation mediator, string version) {
// map string mediation to int for ios
int library = 0; // CBMediationOther
switch(mediator.ToString()) {
case "AdMarvel":
library = 1;
break;
case "Fuse":
library = 2;
break;
case "Fyber":
library = 3;
break;
case "HeyZap":
library = 4;
break;
case "MoPub":
library = 5;
break;
case "Supersonic":
library = 6;
break;
case "AdMob":
library = 7;
break;
case "HyprMX":
library = 8;
break;
}
_chartBoostSetMediation(library, version);
Log("iOS : setMediation to = " + mediator.ToString() + " " + version);
}
#elif UNITY_ANDROID
private static AndroidJavaObject _plugin;
/// Initialize the android sdk
public static void init() {
// get the AppID and AppSecret from CBSettings
string appID = CBSettings.getSelectAndroidAppId ();
string appSecret = CBSettings.getSelectAndroidAppSecret ();
initWithAppId(appID, appSecret);
}
/// Initialize the Chartboost plugin with a specific appId and signature
/// Either one of the init() methods must be called before using any other Chartboost feature
public static void initWithAppId(string appId, string appSignature) {
string unityVersion = Application.unityVersion;
Log("Unity : initWithAppId " + appId + " and version " + unityVersion);
// find the plugin instance
using (var pluginClass = new AndroidJavaClass("com.chartboost.sdk.unity.CBPlugin"))
_plugin = pluginClass.CallStatic<AndroidJavaObject>("instance");
_plugin.Call("init", appId, appSignature, unityVersion);
initialized = true;
}
/// Check to see if any chartboost ad or view is visible
public static bool isAnyViewVisible() {
bool handled = false;
if (!checkInitialized())
return handled;
handled = _plugin.Call<bool>("isAnyViewVisible");
Log("Android : isAnyViewVisible = " + handled );
return handled;
}
/// Caches an interstitial.
public static void cacheInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheInterstitial", location.ToString());
Log("Android : cacheInterstitial at location = " + location.ToString());
}
/// Checks for a cached an interstitial.
public static bool hasInterstitial(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasInterstitial at location = " + location.ToString());
return _plugin.Call<bool>("hasInterstitial", location.ToString());
}
/// Loads an interstitial.
public static void showInterstitial(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showInterstitial", location.ToString());
Log("Android : showInterstitial at location = " + location.ToString());
}
/// Caches the more apps screen.
public static void cacheMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
};
_plugin.Call("cacheMoreApps", location.ToString());
Log("Android : cacheMoreApps at location = " + location.ToString());
}
/// Checks to see if the more apps screen is cached.
public static bool hasMoreApps(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasMoreApps at location = " + location.ToString());
return _plugin.Call<bool>("hasMoreApps", location.ToString());
}
/// Shows the more apps screen.
public static void showMoreApps(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showMoreApps", location.ToString());
Log("Android : showMoreApps at location = " + location.ToString());
}
public static void cacheInPlay(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheInPlay", location.ToString());
Log("Android : cacheInPlay at location = " + location.ToString());
}
public static bool hasInPlay(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasInPlay at location = " + location.ToString());
return _plugin.Call<bool>("hasCachedInPlay", location.ToString());
}
public static CBInPlay getInPlay(CBLocation location) {
Log("Android : getInPlay at location = " + location.ToString());
if (!checkInitialized())
return null;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return null;
}
try
{
AndroidJavaObject androidInPlayAd = _plugin.Call<AndroidJavaObject>("getInPlay", location.ToString());
CBInPlay inPlayAd = new CBInPlay(androidInPlayAd, _plugin);
return inPlayAd;
}
catch
{
return null;
}
}
/// Caches a rewarded video.
public static void cacheRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("cacheRewardedVideo", location.ToString());
Log("Android : cacheRewardedVideo at location = " + location.ToString());
}
/// Checks for a cached a rewarded video.
public static bool hasRewardedVideo(CBLocation location) {
if (!checkInitialized())
return false;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return false;
}
Log("Android : hasRewardedVideo at location = " + location.ToString());
return _plugin.Call<bool>("hasRewardedVideo", location.ToString());
}
/// Loads a rewarded video.
public static void showRewardedVideo(CBLocation location) {
if (!checkInitialized())
return;
else if(location == null) {
Debug.LogError("Chartboost SDK: location passed is null cannot perform the operation requested");
return;
}
_plugin.Call("showRewardedVideo", location.ToString());
Log("Android : showRewardedVideo at location = " + location.ToString());
}
// Sends back the reponse by the delegate call for ShouldDisplayInterstitial
public static void chartBoostShouldDisplayInterstitialCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayInterstitialCallbackResult", result);
Log("Android : chartBoostShouldDisplayInterstitialCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayRewardedVideo
public static void chartBoostShouldDisplayRewardedVideoCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayRewardedVideoCallbackResult", result);
Log("Android : chartBoostShouldDisplayRewardedVideoCallbackResult");
}
// Sends back the reponse by the delegate call for ShouldDisplayMoreApps
public static void chartBoostShouldDisplayMoreAppsCallbackResult(bool result) {
if (!checkInitialized())
return;
_plugin.Call("chartBoostShouldDisplayMoreAppsCallbackResult", result);
Log("Android : chartBoostShouldDisplayMoreAppsCallbackResult");
}
public static void didPassAgeGate(bool pass) {
_plugin.Call ("didPassAgeGate",pass);
}
public static void setShouldPauseClickForConfirmation(bool shouldPause) {
_plugin.Call ("setShouldPauseClickForConfirmation",shouldPause);
}
public static String getCustomId() {
return _plugin.Call<String>("getCustomId");
}
public static void setCustomId(String customId) {
_plugin.Call("setCustomId", customId);
}
public static bool getAutoCacheAds() {
return _plugin.Call<bool>("getAutoCacheAds");
}
public static void setAutoCacheAds(bool autoCacheAds) {
_plugin.Call ("setAutoCacheAds", autoCacheAds);
}
public static void setShouldRequestInterstitialsInFirstSession(bool shouldRequest) {
_plugin.Call ("setShouldRequestInterstitialsInFirstSession", shouldRequest);
}
public static void setShouldDisplayLoadingViewForMoreApps(bool shouldDisplay) {
_plugin.Call ("setShouldDisplayLoadingViewForMoreApps", shouldDisplay);
}
public static void setShouldPrefetchVideoContent(bool shouldPrefetch) {
_plugin.Call ("setShouldPrefetchVideoContent", shouldPrefetch);
}
/// PIA Level Tracking info call
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, int subLevel, String description) {;
int levelType = (int)type;
_plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, subLevel, description);
Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tsubLevel = {3}\n\tdescription = {4}", eventLabel, levelType, mainLevel, subLevel, description));
}
/// PIA Level Tracking info call
public static void trackLevelInfo(String eventLabel, CBLevelType type, int mainLevel, String description) {;
int levelType = (int)type;
_plugin.Call ("trackLevelInfo", eventLabel, levelType, mainLevel, description);
Log(String.Format("Android : PIA Level Tracking:\n\teventLabel = {0}\n\ttype = {1}\n\tmainLevel = {2}\n\tdescription = {3}", eventLabel, levelType, mainLevel, description));
}
/// Sets the name of the game object to be used by the Chartboost Android SDK
public static void setGameObjectName(string name) {
_plugin.Call("setGameObjectName", name);
}
/// Informs the Chartboost SDK about the lifecycle of your app
public static void pause(bool paused) {
if (!checkInitialized())
return;
_plugin.Call("pause", paused);
Log("Android : pause");
}
/// Shuts down the Chartboost plugin
public static void destroy() {
if (!checkInitialized())
return;
_plugin.Call("destroy");
initialized = false;
Log("Android : destroy");
}
/// Used to notify Chartboost that the Android back button has been pressed
/// Returns true to indicate that Chartboost has handled the event and it should not be further processed
public static bool onBackPressed() {
bool handled = false;
if (!checkInitialized())
return false;
handled = _plugin.Call<bool>("onBackPressed");
Log("Android : onBackPressed");
return handled;
}
public static void trackInAppGooglePlayPurchaseEvent(string title, string description, string price, string currency, string productID, string purchaseData, string purchaseSignature) {
Log("Android: trackInAppGooglePlayPurchaseEvent");
_plugin.Call("trackInAppGooglePlayPurchaseEvent", title,description,price,currency,productID,purchaseData,purchaseSignature);
}
public static void trackInAppAmazonStorePurchaseEvent(string title, string description, string price, string currency, string productID, string userID, string purchaseToken) {
Log("Android: trackInAppAmazonStorePurchaseEvent");
_plugin.Call("trackInAppAmazonStorePurchaseEvent", title,description,price,currency,productID,userID,purchaseToken);
}
public static void setMediation(CBMediation mediator, string version) {
_plugin.Call("setMediation", mediator.ToString(), version);
Log("Android : setMediation to = " + mediator.ToString() + " " + version);
}
public static Boolean isWebViewEnabled() {
return _plugin.Call<bool>("isWebViewEnabled");
}
#endif
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Mono.Addins;
using Nini.Config;
using System;
using System.Collections.Generic;
using System.Reflection;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenSim.Services.Connectors;
using OpenSim.Services.Connectors.SimianGrid;
using OpenMetaverse;
namespace OpenSim.Region.CoreModules.ServiceConnectorsOut.Inventory
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "HGInventoryBroker")]
public class HGInventoryBroker : ISharedRegionModule, IInventoryService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private static bool m_Enabled = false;
private static IInventoryService m_LocalGridInventoryService;
private Dictionary<string, IInventoryService> m_connectors = new Dictionary<string, IInventoryService>();
// A cache of userIDs --> ServiceURLs, for HGBroker only
protected Dictionary<UUID, string> m_InventoryURLs = new Dictionary<UUID,string>();
private List<Scene> m_Scenes = new List<Scene>();
private InventoryCache m_Cache = new InventoryCache();
protected IUserManagement m_UserManagement;
protected IUserManagement UserManagementModule
{
get
{
if (m_UserManagement == null)
{
m_UserManagement = m_Scenes[0].RequestModuleInterface<IUserManagement>();
if (m_UserManagement == null)
m_log.ErrorFormat(
"[HG INVENTORY CONNECTOR]: Could not retrieve IUserManagement module from {0}",
m_Scenes[0].RegionInfo.RegionName);
}
return m_UserManagement;
}
}
public Type ReplaceableInterface
{
get { return null; }
}
public string Name
{
get { return "HGInventoryBroker"; }
}
public void Initialise(IConfigSource source)
{
IConfig moduleConfig = source.Configs["Modules"];
if (moduleConfig != null)
{
string name = moduleConfig.GetString("InventoryServices", "");
if (name == Name)
{
IConfig inventoryConfig = source.Configs["InventoryService"];
if (inventoryConfig == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: InventoryService missing from OpenSim.ini");
return;
}
string localDll = inventoryConfig.GetString("LocalGridInventoryService",
String.Empty);
//string HGDll = inventoryConfig.GetString("HypergridInventoryService",
// String.Empty);
if (localDll == String.Empty)
{
m_log.Error("[HG INVENTORY CONNECTOR]: No LocalGridInventoryService named in section InventoryService");
//return;
throw new Exception("Unable to proceed. Please make sure your ini files in config-include are updated according to .example's");
}
Object[] args = new Object[] { source };
m_LocalGridInventoryService =
ServerUtils.LoadPlugin<IInventoryService>(localDll,
args);
if (m_LocalGridInventoryService == null)
{
m_log.Error("[HG INVENTORY CONNECTOR]: Can't load local inventory service");
return;
}
m_Enabled = true;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: HG inventory broker enabled with inner connector of type {0}", m_LocalGridInventoryService.GetType());
}
}
}
public void PostInitialise()
{
}
public void Close()
{
}
public void AddRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Add(scene);
scene.RegisterModuleInterface<IInventoryService>(this);
if (m_Scenes.Count == 1)
{
// FIXME: The local connector needs the scene to extract the UserManager. However, it's not enabled so
// we can't just add the region. But this approach is super-messy.
if (m_LocalGridInventoryService is RemoteXInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in RemoteXInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((RemoteXInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
else if (m_LocalGridInventoryService is LocalInventoryServicesConnector)
{
m_log.DebugFormat(
"[HG INVENTORY BROKER]: Manually setting scene in LocalInventoryServicesConnector to {0}",
scene.RegionInfo.RegionName);
((LocalInventoryServicesConnector)m_LocalGridInventoryService).Scene = scene;
}
scene.EventManager.OnClientClosed += OnClientClosed;
}
}
public void RemoveRegion(Scene scene)
{
if (!m_Enabled)
return;
m_Scenes.Remove(scene);
}
public void RegionLoaded(Scene scene)
{
if (!m_Enabled)
return;
m_log.InfoFormat("[HG INVENTORY CONNECTOR]: Enabled HG inventory for region {0}", scene.RegionInfo.RegionName);
}
#region URL Cache
void OnClientClosed(UUID clientID, Scene scene)
{
if (m_InventoryURLs.ContainsKey(clientID)) // if it's in cache
{
ScenePresence sp = null;
foreach (Scene s in m_Scenes)
{
s.TryGetScenePresence(clientID, out sp);
if ((sp != null) && !sp.IsChildAgent && (s != scene))
{
m_log.DebugFormat("[INVENTORY CACHE]: OnClientClosed in {0}, but user {1} still in sim. Keeping inventoryURL in cache",
scene.RegionInfo.RegionName, clientID);
return;
}
}
DropInventoryServiceURL(clientID);
}
}
/// <summary>
/// Gets the user's inventory URL from its serviceURLs, if the user is foreign,
/// and sticks it in the cache
/// </summary>
/// <param name="userID"></param>
private void CacheInventoryServiceURL(UUID userID)
{
if (UserManagementModule != null && !UserManagementModule.IsLocalGridUser(userID))
{
// The user is not local; let's cache its service URL
string inventoryURL = string.Empty;
ScenePresence sp = null;
foreach (Scene scene in m_Scenes)
{
scene.TryGetScenePresence(userID, out sp);
if (sp != null)
{
AgentCircuitData aCircuit = scene.AuthenticateHandler.GetAgentCircuitData(sp.ControllingClient.CircuitCode);
if (aCircuit == null)
return;
if (aCircuit.ServiceURLs == null)
return;
if (aCircuit.ServiceURLs.ContainsKey("InventoryServerURI"))
{
inventoryURL = aCircuit.ServiceURLs["InventoryServerURI"].ToString();
if (inventoryURL != null && inventoryURL != string.Empty)
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs[userID] = inventoryURL;
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
return;
}
}
// else
// {
// m_log.DebugFormat("[HG INVENTORY CONNECTOR]: User {0} does not have InventoryServerURI. OH NOES!", userID);
// return;
// }
}
}
if (sp == null)
{
inventoryURL = UserManagementModule.GetUserServerURL(userID, "InventoryServerURI");
if (!string.IsNullOrEmpty(inventoryURL))
{
inventoryURL = inventoryURL.Trim(new char[] { '/' });
m_InventoryURLs.Add(userID, inventoryURL);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Added {0} to the cache of inventory URLs", inventoryURL);
}
}
}
}
private void DropInventoryServiceURL(UUID userID)
{
lock (m_InventoryURLs)
if (m_InventoryURLs.ContainsKey(userID))
{
string url = m_InventoryURLs[userID];
m_InventoryURLs.Remove(userID);
m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Removed {0} from the cache of inventory URLs", url);
}
}
public string GetInventoryServiceURL(UUID userID)
{
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
CacheInventoryServiceURL(userID);
if (m_InventoryURLs.ContainsKey(userID))
return m_InventoryURLs[userID];
return null; //it means that the methods should forward to local grid's inventory
}
#endregion
#region IInventoryService
public bool CreateUserInventory(UUID userID)
{
return m_LocalGridInventoryService.CreateUserInventory(userID);
}
public List<InventoryFolderBase> GetInventorySkeleton(UUID userID)
{
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetInventorySkeleton(userID);
IInventoryService connector = GetConnector(invURL);
return connector.GetInventorySkeleton(userID);
}
public InventoryFolderBase GetRootFolder(UUID userID)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetRootFolder for {0}", userID);
InventoryFolderBase root = m_Cache.GetRootFolder(userID);
if (root != null)
return root;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetRootFolder(userID);
IInventoryService connector = GetConnector(invURL);
root = connector.GetRootFolder(userID);
m_Cache.Cache(userID, root);
return root;
}
public InventoryFolderBase GetFolderForType(UUID userID, AssetType type)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: GetFolderForType {0} type {1}", userID, type);
InventoryFolderBase f = m_Cache.GetFolderForType(userID, type);
if (f != null)
return f;
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderForType(userID, type);
IInventoryService connector = GetConnector(invURL);
f = connector.GetFolderForType(userID, type);
m_Cache.Cache(userID, type, f);
return f;
}
public InventoryCollection GetFolderContent(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderContent(userID, folderID);
InventoryCollection c = m_Cache.GetFolderContent(userID, folderID);
if (c != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderContent found content in cache " + folderID);
return c;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderContent(userID, folderID);
}
public List<InventoryItemBase> GetFolderItems(UUID userID, UUID folderID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems " + folderID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolderItems(userID, folderID);
List<InventoryItemBase> items = m_Cache.GetFolderItems(userID, folderID);
if (items != null)
{
m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolderItems found items in cache " + folderID);
return items;
}
IInventoryService connector = GetConnector(invURL);
return connector.GetFolderItems(userID, folderID);
}
public bool AddFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.AddFolder(folder);
}
public bool UpdateFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateFolder(folder);
}
public bool DeleteFolders(UUID ownerID, List<UUID> folderIDs)
{
if (folderIDs == null)
return false;
if (folderIDs.Count == 0)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: DeleteFolders for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteFolders(ownerID, folderIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteFolders(ownerID, folderIDs);
}
public bool MoveFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.MoveFolder(folder);
}
public bool PurgeFolder(InventoryFolderBase folder)
{
if (folder == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: PurgeFolder for " + folder.Owner);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.PurgeFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.PurgeFolder(folder);
}
public bool AddItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: AddItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.AddItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.AddItem(item);
}
public bool UpdateItem(InventoryItemBase item)
{
if (item == null)
return false;
//m_log.Debug("[HG INVENTORY CONNECTOR]: UpdateItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.UpdateItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.UpdateItem(item);
}
public bool MoveItems(UUID ownerID, List<InventoryItemBase> items)
{
if (items == null)
return false;
if (items.Count == 0)
return true;
//m_log.Debug("[HG INVENTORY CONNECTOR]: MoveItems for " + ownerID);
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.MoveItems(ownerID, items);
IInventoryService connector = GetConnector(invURL);
return connector.MoveItems(ownerID, items);
}
public bool DeleteItems(UUID ownerID, List<UUID> itemIDs)
{
//m_log.DebugFormat("[HG INVENTORY CONNECTOR]: Delete {0} items for user {1}", itemIDs.Count, ownerID);
if (itemIDs == null)
return false;
if (itemIDs.Count == 0)
return true;
string invURL = GetInventoryServiceURL(ownerID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.DeleteItems(ownerID, itemIDs);
IInventoryService connector = GetConnector(invURL);
return connector.DeleteItems(ownerID, itemIDs);
}
public InventoryItemBase GetItem(InventoryItemBase item)
{
if (item == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetItem " + item.ID);
string invURL = GetInventoryServiceURL(item.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetItem(item);
IInventoryService connector = GetConnector(invURL);
return connector.GetItem(item);
}
public InventoryFolderBase GetFolder(InventoryFolderBase folder)
{
if (folder == null)
return null;
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetFolder " + folder.ID);
string invURL = GetInventoryServiceURL(folder.Owner);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetFolder(folder);
IInventoryService connector = GetConnector(invURL);
return connector.GetFolder(folder);
}
public bool HasInventoryForUser(UUID userID)
{
return false;
}
public List<InventoryItemBase> GetActiveGestures(UUID userId)
{
return new List<InventoryItemBase>();
}
public int GetAssetPermissions(UUID userID, UUID assetID)
{
//m_log.Debug("[HG INVENTORY CONNECTOR]: GetAssetPermissions " + assetID);
string invURL = GetInventoryServiceURL(userID);
if (invURL == null) // not there, forward to local inventory connector to resolve
return m_LocalGridInventoryService.GetAssetPermissions(userID, assetID);
IInventoryService connector = GetConnector(invURL);
return connector.GetAssetPermissions(userID, assetID);
}
#endregion
private IInventoryService GetConnector(string url)
{
IInventoryService connector = null;
lock (m_connectors)
{
if (m_connectors.ContainsKey(url))
{
connector = m_connectors[url];
}
else
{
// Still not as flexible as I would like this to be,
// but good enough for now
string connectorType = new HeloServicesConnector(url).Helo();
m_log.DebugFormat("[HG INVENTORY SERVICE]: HELO returned {0}", connectorType);
if (connectorType == "opensim-simian")
{
connector = new SimianInventoryServiceConnector(url);
}
else
{
RemoteXInventoryServicesConnector rxisc = new RemoteXInventoryServicesConnector(url);
rxisc.Scene = m_Scenes[0];
connector = rxisc;
}
m_connectors.Add(url, connector);
}
}
return connector;
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CompilerServer;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.Win32;
using Moq;
using Roslyn.Test.Utilities;
using Xunit;
using System.IO.Pipes;
namespace Microsoft.CodeAnalysis.BuildTasks.UnitTests
{
public class CompilerServerApiTest : TestBase
{
private sealed class TestableClientConnection : IClientConnection
{
internal string LoggingIdentifier = string.Empty;
internal Task<BuildRequest> ReadBuildRequestTask = TaskFromException<BuildRequest>(new Exception());
internal Task WriteBuildResponseTask = TaskFromException(new Exception());
internal Task MonitorTask = TaskFromException(new Exception());
internal Action CloseAction = delegate { };
/// <summary>
/// Ensure server respects keep alive and shuts down after processing a single connection.
/// </summary>
[Fact]
public async Task KeepAliveAfterSingleConnection()
{
var keepAlive = TimeSpan.FromSeconds(1);
var listener = new TestableDiagnosticListener();
var pipeName = Guid.NewGuid().ToString();
var dispatcherTask = Task.Run(() =>
{
var dispatcher = new ServerDispatcher(CreateNopRequestHandler().Object, listener);
dispatcher.ListenAndDispatchConnections(pipeName, keepAlive, watchAnalyzerFiles: false);
});
await RunCSharpCompile(pipeName, HelloWorldSourceText).ConfigureAwait(false);
await dispatcherTask.ConfigureAwait(false);
Assert.Equal(1, listener.ProcessedCount);
Assert.True(listener.LastProcessedTime.HasValue);
Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
}
/// <summary>
/// Ensure server respects keep alive and shuts down after processing multiple connections.
/// </summary>
[Fact]
public async Task KeepAliveAfterMultipleConnection()
{
var keepAlive = TimeSpan.FromSeconds(1);
var listener = new TestableDiagnosticListener();
var pipeName = Guid.NewGuid().ToString();
var dispatcherTask = Task.Run(() =>
{
var dispatcher = new ServerDispatcher(new CompilerRequestHandler(Temp.CreateDirectory().Path), listener);
dispatcher.ListenAndDispatchConnections(pipeName, keepAlive, watchAnalyzerFiles: false);
});
for (int i = 0; i < 5; i++)
{
await RunCSharpCompile(pipeName, HelloWorldSourceText).ConfigureAwait(false);
}
await dispatcherTask.ConfigureAwait(false);
Assert.Equal(5, listener.ProcessedCount);
Assert.True(listener.LastProcessedTime.HasValue);
Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
}
/// <summary>
/// Ensure server respects keep alive and shuts down after processing simultaneous connections.
/// </summary>
[Fact(Skip = "DevDiv 1095079")]
public async Task KeepAliveAfterSimultaneousConnection()
{
var keepAlive = TimeSpan.FromSeconds(1);
var listener = new TestableDiagnosticListener();
var pipeName = Guid.NewGuid().ToString();
var dispatcherTask = Task.Run(() =>
{
var dispatcher = new ServerDispatcher(new CompilerRequestHandler(Temp.CreateDirectory().Path), listener);
dispatcher.ListenAndDispatchConnections(pipeName, keepAlive, watchAnalyzerFiles: false);
});
var list = new List<Task>();
for (int i = 0; i < 5; i++)
{
var task = Task.Run(() => RunCSharpCompile(pipeName, HelloWorldSourceText));
list.Add(task);
}
foreach (var current in list)
{
await current.ConfigureAwait(false);
}
await dispatcherTask.ConfigureAwait(false);
Assert.Equal(5, listener.ProcessedCount);
Assert.True(listener.LastProcessedTime.HasValue);
Assert.True((DateTime.Now - listener.LastProcessedTime.Value) > keepAlive);
}
[Fact(Skip = "DevDiv 1095079"), WorkItem(1095079)]
public async Task FirstClientCanOverrideDefaultTimeout()
{
var cts = new CancellationTokenSource();
var listener = new TestableDiagnosticListener();
TimeSpan? newTimeSpan = null;
var connectionSource = new TaskCompletionSource<int>();
var diagnosticListener = new Mock<IDiagnosticListener>();
diagnosticListener
.Setup(x => x.UpdateKeepAlive(It.IsAny<TimeSpan>()))
.Callback<TimeSpan>(ts => { newTimeSpan = ts; });
diagnosticListener
.Setup(x => x.ConnectionProcessed(It.IsAny<int>()))
.Callback<int>(count => connectionSource.SetResult(count));
var pipeName = Guid.NewGuid().ToString();
var dispatcherTask = Task.Run(() =>
{
var dispatcher = new ServerDispatcher(CreateNopRequestHandler().Object, diagnosticListener.Object);
dispatcher.ListenAndDispatchConnections(pipeName, TimeSpan.FromSeconds(1), watchAnalyzerFiles: false, cancellationToken: cts.Token);
});
var seconds = 10;
var response = await RunCSharpCompile(pipeName, HelloWorldSourceText, TimeSpan.FromSeconds(seconds)).ConfigureAwait(false);
Assert.Equal(BuildResponse.ResponseType.Completed, response.Type);
Assert.Equal(1, await connectionSource.Task.ConfigureAwait(false));
Assert.True(newTimeSpan.HasValue);
Assert.Equal(seconds, newTimeSpan.Value.TotalSeconds);
cts.Cancel();
await dispatcherTask.ConfigureAwait(false);
}
string IClientConnection.LoggingIdentifier
{
get { return LoggingIdentifier; }
}
Task<BuildRequest> IClientConnection.ReadBuildRequest(CancellationToken cancellationToken)
{
return ReadBuildRequestTask;
}
Task IClientConnection.WriteBuildResponse(BuildResponse response, CancellationToken cancellationToken)
{
return WriteBuildResponseTask;
}
Task IClientConnection.CreateMonitorDisconnectTask(CancellationToken cancellationToken)
{
return MonitorTask;
}
void IClientConnection.Close()
{
CloseAction();
}
}
private sealed class TestableDiagnosticListener : IDiagnosticListener
{
public int ProcessedCount = 0;
public DateTime? LastProcessedTime;
public TimeSpan? KeepAlive;
public void ConnectionProcessed(int count)
{
ProcessedCount += count;
LastProcessedTime = DateTime.Now;
}
public void UpdateKeepAlive(TimeSpan timeSpan)
{
KeepAlive = timeSpan;
}
}
private static readonly BuildRequest EmptyCSharpBuildRequest = new BuildRequest(
1,
BuildProtocolConstants.RequestLanguage.CSharpCompile,
ImmutableArray<BuildRequest.Argument>.Empty);
private static readonly BuildResponse EmptyBuildResponse = new CompletedBuildResponse(
returnCode: 0,
utf8output: false,
output: string.Empty,
errorOutput: string.Empty);
private const string HelloWorldSourceText = @"
using System;
class Hello
{
static void Main()
{
Console.WriteLine(""Hello, world."");
}
}";
private static Task TaskFromException(Exception e)
{
return TaskFromException<bool>(e);
}
private static Task<T> TaskFromException<T>(Exception e)
{
var source = new TaskCompletionSource<T>();
source.SetException(e);
return source.Task;
}
private async Task<BuildRequest> CreateBuildRequest(string sourceText, TimeSpan? keepAlive = null)
{
var directory = Temp.CreateDirectory();
var file = directory.CreateFile("temp.cs");
await file.WriteAllTextAsync(sourceText).ConfigureAwait(false);
var builder = ImmutableArray.CreateBuilder<BuildRequest.Argument>();
if (keepAlive.HasValue)
{
builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.KeepAlive, argumentIndex: 0, value: keepAlive.Value.TotalSeconds.ToString()));
}
builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CurrentDirectory, argumentIndex: 0, value: directory.Path));
builder.Add(new BuildRequest.Argument(BuildProtocolConstants.ArgumentId.CommandLineArgument, argumentIndex: 0, value: file.Path));
return new BuildRequest(
BuildProtocolConstants.ProtocolVersion,
BuildProtocolConstants.RequestLanguage.CSharpCompile,
builder.ToImmutable());
}
/// <summary>
/// Run a C# compilation against the given source text using the provided named pipe name.
/// </summary>
private async Task<BuildResponse> RunCSharpCompile(string pipeName, string sourceText, TimeSpan? keepAlive = null)
{
using (var namedPipe = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut))
{
var buildRequest = await CreateBuildRequest(sourceText, keepAlive).ConfigureAwait(false);
namedPipe.Connect((int)TimeSpan.FromSeconds(5).TotalMilliseconds);
await buildRequest.WriteAsync(namedPipe, default(CancellationToken)).ConfigureAwait(false);
return await BuildResponse.ReadAsync(namedPipe, default(CancellationToken)).ConfigureAwait(false);
}
}
/// <summary>
/// This returns an <see cref="IRequestHandler"/> that always returns <see cref="CompletedBuildResponse"/> without
/// doing any work.
/// </summary>
private static Mock<IRequestHandler> CreateNopRequestHandler()
{
var requestHandler = new Mock<IRequestHandler>();
requestHandler
.Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
.Returns(new CompletedBuildResponse(0, utf8output: false, output: string.Empty, errorOutput: string.Empty));
return requestHandler;
}
[Fact]
public void NotifyCallBackOnRequestHandlerException()
{
var clientConnection = new TestableClientConnection();
clientConnection.MonitorTask = Task.Delay(-1);
clientConnection.ReadBuildRequestTask = Task.FromResult(EmptyCSharpBuildRequest);
var ex = new Exception();
var handler = new Mock<IRequestHandler>();
handler
.Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
.Throws(ex);
var invoked = false;
FatalError.OverwriteHandler((providedEx) =>
{
Assert.Same(ex, providedEx);
invoked = true;
});
var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
Assert.Throws(typeof(AggregateException), () => client.ServeConnection().Wait());
Assert.True(invoked);
}
[Fact]
public void ClientDisconnectCancelBuildAndReturnsFailure()
{
var clientConnection = new TestableClientConnection();
clientConnection.ReadBuildRequestTask = Task.FromResult(EmptyCSharpBuildRequest);
var monitorTaskSource = new TaskCompletionSource<bool>();
clientConnection.MonitorTask = monitorTaskSource.Task;
var handler = new Mock<IRequestHandler>();
var handlerTaskSource = new TaskCompletionSource<CancellationToken>();
var releaseHandlerSource = new TaskCompletionSource<bool>();
handler
.Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
.Callback<BuildRequest, CancellationToken>((_, t) =>
{
handlerTaskSource.SetResult(t);
releaseHandlerSource.Task.Wait();
})
.Returns(EmptyBuildResponse);
var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
var serveTask = client.ServeConnection(new TaskCompletionSource<TimeSpan?>());
// Once this returns we know the Connection object has kicked off a compilation and
// started monitoring the disconnect task. Can now initiate a disconnect in a known
// state.
var cancellationToken = handlerTaskSource.Task.Result;
monitorTaskSource.SetResult(true);
Assert.Equal(ServerDispatcher.CompletionReason.ClientDisconnect, serveTask.Result);
Assert.True(cancellationToken.IsCancellationRequested);
// Now that the asserts are done unblock the "build" long running task. Have to do this
// last to simulate a build which is still running when the client disconnects.
releaseHandlerSource.SetResult(true);
}
[Fact]
public void ReadError()
{
var handler = new Mock<IRequestHandler>(MockBehavior.Strict);
var ex = new Exception("Simulated read error.");
var clientConnection = new TestableClientConnection();
var calledClose = false;
clientConnection.ReadBuildRequestTask = TaskFromException<BuildRequest>(ex);
clientConnection.CloseAction = delegate { calledClose = true; };
var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
Assert.Equal(ServerDispatcher.CompletionReason.CompilationNotStarted, client.ServeConnection().Result);
Assert.True(calledClose);
}
/// <summary>
/// A failure to write the results to the client is considered a client disconnection. Any error
/// from when the build starts to when the write completes should be handled this way.
/// </summary>
[Fact]
public void WriteError()
{
var clientConnection = new TestableClientConnection();
clientConnection.MonitorTask = Task.Delay(-1);
clientConnection.ReadBuildRequestTask = Task.FromResult(EmptyCSharpBuildRequest);
clientConnection.WriteBuildResponseTask = TaskFromException(new Exception());
var handler = new Mock<IRequestHandler>();
handler
.Setup(x => x.HandleRequest(It.IsAny<BuildRequest>(), It.IsAny<CancellationToken>()))
.Returns(EmptyBuildResponse);
var client = new ServerDispatcher.Connection(clientConnection, handler.Object);
Assert.Equal(ServerDispatcher.CompletionReason.ClientDisconnect, client.ServeConnection().Result);
}
[Fact]
public void KeepAliveNoConnections()
{
var keepAlive = TimeSpan.FromSeconds(3);
var pipeName = Guid.NewGuid().ToString();
var requestHandler = new Mock<IRequestHandler>(MockBehavior.Strict);
var dispatcher = new ServerDispatcher(requestHandler.Object, new EmptyDiagnosticListener());
var startTime = DateTime.Now;
dispatcher.ListenAndDispatchConnections(pipeName, keepAlive, watchAnalyzerFiles: false);
Assert.True((DateTime.Now - startTime) > keepAlive);
}
}
}
| |
// 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 Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Roslyn.Test.Utilities;
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using Xunit;
using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class WinMdTests : ExpressionCompilerTestBase
{
/// <summary>
/// Handle runtime assemblies rather than Windows.winmd
/// (compile-time assembly) since those are the assemblies
/// loaded in the debuggee.
/// </summary>
[WorkItem(981104)]
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs);
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections");
Assert.True(runtimeAssemblies.Length >= 2);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
context.CompileExpression("(p == null) ? f : null", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldarg.1
IL_0001: brfalse.s IL_0005
IL_0003: ldnull
IL_0004: ret
IL_0005: ldarg.0
IL_0006: ret
}");
}
[ConditionalFact(typeof(OSVersionWin8))]
public void Win8RuntimeAssemblies_ExternAlias()
{
var source =
@"extern alias X;
class C
{
static void M(X::Windows.Storage.StorageFolder f)
{
}
}";
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r));
var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage");
Assert.True(runtimeAssemblies.Length >= 1);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
var runtime = CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd
exeBytes,
new SymReader(pdbBytes));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldc.i4.0
IL_0001: ret
}");
}
[Fact]
public void Win8OnWin8()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[Fact]
public void Win8OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows.Storage");
}
[WorkItem(1108135)]
[Fact]
public void Win10OnWin10()
{
CompileTimeAndRuntimeAssemblies(
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
ImmutableArray.Create(
MscorlibRef,
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(),
AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(),
AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()),
"Windows");
}
private void CompileTimeAndRuntimeAssemblies(
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences,
string storageAssemblyName)
{
var source =
@"class C
{
static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f)
{
}
}";
var runtime = CreateRuntime(source, compileReferences, runtimeReferences);
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out resultProperties, out error, testData);
Assert.Null(error);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 17 (0x11)
.maxstack 2
IL_0000: ldarg.0
IL_0001: dup
IL_0002: brtrue.s IL_0010
IL_0004: pop
IL_0005: ldarg.1
IL_0006: dup
IL_0007: brtrue.s IL_0010
IL_0009: pop
IL_000a: ldarg.2
IL_000b: dup
IL_000c: brtrue.s IL_0010
IL_000e: pop
IL_000f: ldarg.3
IL_0010: ret
}");
testData = new CompilationTestData();
var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out resultProperties, out error, testData);
Assert.Null(error);
var methodData = testData.GetMethodData("<>x.<>m0");
methodData.VerifyIL(
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
// Check return type is from runtime assembly.
var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference();
var compilation = CSharpCompilation.Create(
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference)));
var assembly = ImmutableArray.CreateRange(result.Assembly);
using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly)))
{
var reader = metadata.MetadataReader;
var typeDef = reader.GetTypeDef("<>x");
var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0");
var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule;
var metadataDecoder = new MetadataDecoder(module);
SignatureHeader signatureHeader;
BadImageFormatException metadataException;
var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException);
Assert.Equal(parameters.Length, 5);
var actualReturnType = parameters[0].Type;
Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error
var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder");
Assert.Equal(expectedReturnType, actualReturnType);
Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name);
}
}
/// <summary>
/// Assembly-qualified name containing "ContentType=WindowsRuntime",
/// and referencing runtime assembly.
/// </summary>
[WorkItem(1116143)]
[ConditionalFact(typeof(OSVersionWin8))]
public void AssemblyQualifiedName()
{
var source =
@"class C
{
static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections")));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
InspectionContextFactory.Empty.
Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime").
Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"),
"(object)s.Attributes ?? d.UniversalTime",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object <>x.<>GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object <>x.<>GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
[WorkItem(1117084)]
[Fact(Skip = "1114866")]
public void OtherFrameworkAssembly()
{
var source =
@"class C
{
static void M(Windows.UI.Xaml.FrameworkElement f)
{
}
}";
var runtime = CreateRuntime(
source,
ImmutableArray.CreateRange(WinRtRefs),
ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml")));
var context = CreateMethodContext(runtime, "C.M");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
InspectionContextFactory.Empty,
"f.RenderSize",
DkmEvaluationFlags.TreatAsExpression,
DiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Empty(missingAssemblyIdentities);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 55 (0x37)
.maxstack 2
IL_0000: ldstr ""s""
IL_0005: call ""object <>x.<>GetObjectByAlias(string)""
IL_000a: castclass ""Windows.Storage.StorageFolder""
IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get""
IL_0014: box ""Windows.Storage.FileAttributes""
IL_0019: dup
IL_001a: brtrue.s IL_0036
IL_001c: pop
IL_001d: ldstr ""d""
IL_0022: call ""object <>x.<>GetObjectByAlias(string)""
IL_0027: unbox.any ""Windows.Foundation.DateTime""
IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime""
IL_0031: box ""long""
IL_0036: ret
}");
}
private RuntimeInstance CreateRuntime(
string source,
ImmutableArray<MetadataReference> compileReferences,
ImmutableArray<MetadataReference> runtimeReferences)
{
var compilation0 = CreateCompilationWithMscorlib(
source,
options: TestOptions.DebugDll,
assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(),
references: compileReferences);
byte[] exeBytes;
byte[] pdbBytes;
ImmutableArray<MetadataReference> references;
compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references);
return CreateRuntimeInstance(
ExpressionCompilerUtilities.GenerateUniqueName(),
runtimeReferences,
exeBytes,
new SymReader(pdbBytes));
}
private static byte[] ToVersion1_3(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_3(bytes);
}
private static byte[] ToVersion1_4(byte[] bytes)
{
return ExpressionCompilerTestHelpers.ToVersion1_4(bytes);
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace PixelCrushers.DialogueSystem {
/// <summary>
/// Player setup wizard.
/// </summary>
public class PlayerSetupWizard : EditorWindow {
[MenuItem("Window/Dialogue System/Wizards/Player Setup", false, 1)]
public static void Init() {
(EditorWindow.GetWindow(typeof(PlayerSetupWizard), false, "Player Setup") as PlayerSetupWizard).minSize = new Vector2(700, 500);
}
// Private fields for the window:
private enum Stage {
SelectPC,
Control,
Camera,
Targeting,
Transition,
Persistence,
Review
};
private Stage stage = Stage.SelectPC;
private string[] stageLabels = new string[] { "Player", "Control", "Camera", "Targeting", "Transition", "Persistence", "Review" };
private const float ToggleWidth = 16;
private GameObject pcObject = null;
private bool setEnabledFlag = false;
/// <summary>
/// Draws the window.
/// </summary>
void OnGUI() {
DrawProgressIndicator();
DrawCurrentStage();
}
private void DrawProgressIndicator() {
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.Toolbar((int) stage, stageLabels, GUILayout.Width(700));
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
EditorGUI.EndDisabledGroup();
EditorWindowTools.DrawHorizontalLine();
}
private void DrawNavigationButtons(bool backEnabled, bool nextEnabled, bool nextCloses) {
GUILayout.FlexibleSpace();
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button("Cancel", GUILayout.Width(100))) {
this.Close();
} else if (backEnabled && GUILayout.Button("Back", GUILayout.Width(100))) {
stage--;
} else {
EditorGUI.BeginDisabledGroup(!nextEnabled);
if (GUILayout.Button(nextCloses ? "Finish" : "Next", GUILayout.Width(100))) {
if (nextCloses) {
Close();
} else {
stage++;
}
}
EditorGUI.EndDisabledGroup();
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.LabelField(string.Empty, GUILayout.Height(2));
}
private void DrawCurrentStage() {
if (pcObject == null) stage = Stage.SelectPC;
switch (stage) {
case Stage.SelectPC: DrawSelectPCStage(); break;
case Stage.Control: DrawControlStage(); break;
case Stage.Camera: DrawCameraStage(); break;
case Stage.Targeting: DrawTargetingStage(); break;
case Stage.Transition: DrawTransitionStage(); break;
case Stage.Persistence: DrawPersistenceStage(); break;
case Stage.Review: DrawReviewStage(); break;
}
}
private void DrawSelectPCStage() {
EditorGUILayout.LabelField("Select Player Object", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("This wizard will help you configure a Player object to work with the Dialogue System. First, assign the Player's GameObject below.", MessageType.Info);
pcObject = EditorGUILayout.ObjectField("Player Object", pcObject, typeof(GameObject), true) as GameObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(false, (pcObject != null), false);
}
private enum ControlStyle {
ThirdPersonShooter,
FollowMouseClicks,
Custom
};
private void DrawControlStage() {
EditorGUILayout.LabelField("Control", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
PixelCrushers.DialogueSystem.SimpleController simpleController = pcObject.GetComponent<PixelCrushers.DialogueSystem.SimpleController>();
NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>();
ControlStyle controlStyle = (simpleController != null)
? ControlStyle.ThirdPersonShooter
: (navigateOnMouseClick != null)
? ControlStyle.FollowMouseClicks
: ControlStyle.Custom;
EditorGUILayout.HelpBox("How will the player control movement? (Select Custom to provide your own control components instead of using the Dialogue System's.)", MessageType.Info);
controlStyle = (ControlStyle) EditorGUILayout.EnumPopup("Control", controlStyle);
switch (controlStyle) {
case ControlStyle.ThirdPersonShooter:
DestroyImmediate(navigateOnMouseClick);
DrawSimpleControllerSection(simpleController ?? pcObject.AddComponent<PixelCrushers.DialogueSystem.SimpleController>());
break;
case ControlStyle.FollowMouseClicks:
DestroyImmediate(simpleController);
DrawNavigateOnMouseClickSection(navigateOnMouseClick ?? pcObject.AddComponent<NavigateOnMouseClick>());
break;
default:
DestroyImmediate(simpleController);
DestroyImmediate(navigateOnMouseClick);
break;
}
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawSimpleControllerSection(PixelCrushers.DialogueSystem.SimpleController simpleController) {
EditorWindowTools.StartIndentedSection();
if ((simpleController.idle == null) || (simpleController.runForward == null)) {
EditorGUILayout.HelpBox("The player uses third-person shooter style controls. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info);
}
simpleController.idle = EditorGUILayout.ObjectField("Idle Animation", simpleController.idle, typeof(AnimationClip), false) as AnimationClip;
simpleController.runForward = EditorGUILayout.ObjectField("Run Animation", simpleController.runForward, typeof(AnimationClip), false) as AnimationClip;
EditorWindowTools.StartIndentedSection();
EditorGUILayout.LabelField("Optional", EditorStyles.boldLabel);
simpleController.runSpeed = EditorGUILayout.FloatField("Run Speed", simpleController.runSpeed);
simpleController.runBack = EditorGUILayout.ObjectField("Run Back", simpleController.runBack, typeof(AnimationClip), false) as AnimationClip;
simpleController.aim = EditorGUILayout.ObjectField("Aim", simpleController.aim, typeof(AnimationClip), false) as AnimationClip;
simpleController.fire = EditorGUILayout.ObjectField("Fire", simpleController.fire, typeof(AnimationClip), false) as AnimationClip;
if (simpleController.fire != null) {
if (simpleController.upperBodyMixingTransform == null) EditorGUILayout.HelpBox("Specify the upper body mixing transform for the fire animation.", MessageType.Info);
simpleController.upperBodyMixingTransform = EditorGUILayout.ObjectField("Upper Body Transform", simpleController.upperBodyMixingTransform, typeof(Transform), true) as Transform;
simpleController.fireLayerMask = EditorGUILayout.LayerField("Fire Layer", simpleController.fireLayerMask);
simpleController.fireSound = EditorGUILayout.ObjectField("Fire Sound", simpleController.fireSound, typeof(AudioClip), false) as AudioClip;
AudioSource audioSource = pcObject.GetComponent<AudioSource>();
if (audioSource == null) {
audioSource = pcObject.AddComponent<AudioSource>();
audioSource.playOnAwake = false;
audioSource.loop = false;
}
}
EditorWindowTools.EndIndentedSection();
EditorWindowTools.EndIndentedSection();
}
private void DrawNavigateOnMouseClickSection(NavigateOnMouseClick navigateOnMouseClick) {
EditorWindowTools.StartIndentedSection();
if ((navigateOnMouseClick.idle == null) || (navigateOnMouseClick.run == null)) {
EditorGUILayout.HelpBox("The player clicks on the map to move. At a minimum, Idle and Run animations are required. Click Select Player to customize further.", MessageType.Info);
}
navigateOnMouseClick.idle = EditorGUILayout.ObjectField("Idle Animation", navigateOnMouseClick.idle, typeof(AnimationClip), false) as AnimationClip;
navigateOnMouseClick.run = EditorGUILayout.ObjectField("Run Animation", navigateOnMouseClick.run, typeof(AnimationClip), false) as AnimationClip;
navigateOnMouseClick.mouseButton = (NavigateOnMouseClick.MouseButtonType) EditorGUILayout.EnumPopup("Mouse Button", navigateOnMouseClick.mouseButton);
EditorWindowTools.EndIndentedSection();
}
private void DrawCameraStage() {
EditorGUILayout.LabelField("Camera", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
Camera playerCamera = pcObject.GetComponentInChildren<Camera>() ?? Camera.main;
SmoothCameraWithBumper smoothCamera = (playerCamera != null) ? playerCamera.GetComponent<SmoothCameraWithBumper>() : null;
EditorGUILayout.BeginHorizontal();
bool useSmoothCamera = EditorGUILayout.Toggle((smoothCamera != null) , GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Use Smooth Follow Camera", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (useSmoothCamera) {
if (playerCamera == null) {
GameObject playerCameraObject = new GameObject("Player Camera");
playerCameraObject.transform.parent = pcObject.transform;
playerCamera = playerCameraObject.AddComponent<Camera>();
playerCamera.tag = "MainCamera";
}
smoothCamera = playerCamera.GetComponentInChildren<SmoothCameraWithBumper>() ?? playerCamera.gameObject.AddComponent<SmoothCameraWithBumper>();
EditorWindowTools.StartIndentedSection();
if (smoothCamera.target == null) {
EditorGUILayout.HelpBox("Specify the transform (usually the head) that the camera should follow.", MessageType.Info);
}
smoothCamera.target = EditorGUILayout.ObjectField("Target", smoothCamera.target, typeof(Transform), true) as Transform;
EditorWindowTools.EndIndentedSection();
} else {
DestroyImmediate(smoothCamera);
}
if (GUILayout.Button("Select Camera", GUILayout.Width(100))) Selection.activeObject = playerCamera;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawTargetingStage() {
EditorGUILayout.LabelField("Targeting", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
SelectorType selectorType = GetSelectorType();
if (selectorType == SelectorType.None) EditorGUILayout.HelpBox("Specify how the player will target NPCs to trigger conversations and barks.", MessageType.Info);
selectorType = (SelectorType) EditorGUILayout.EnumPopup("Target NPCs By", selectorType);
switch (selectorType) {
case SelectorType.Proximity:
DrawProximitySelector();
break;
case SelectorType.CenterOfScreen:
case SelectorType.MousePosition:
case SelectorType.CustomPosition:
DrawSelector(selectorType);
break;
default:
DrawNoSelector();
break;
}
EditorWindowTools.EndIndentedSection();
EditorWindowTools.DrawHorizontalLine();
DrawOverrideNameSubsection();
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
DrawNavigationButtons(true, true, false);
}
private enum SelectorType {
CenterOfScreen,
MousePosition,
Proximity,
CustomPosition,
None,
};
private enum MouseButtonChoice {
LeftMouseButton,
RightMouseButton
}
private SelectorType GetSelectorType() {
if (pcObject.GetComponent<ProximitySelector>() != null) {
return SelectorType.Proximity;
} else {
Selector selector = pcObject.GetComponent<Selector>();
if (selector != null) {
switch (selector.selectAt) {
case Selector.SelectAt.CenterOfScreen:
return SelectorType.CenterOfScreen;
case Selector.SelectAt.MousePosition:
return SelectorType.MousePosition;
default:
return SelectorType.CustomPosition;
}
} else {
return SelectorType.None;
}
}
}
private void DrawNoSelector() {
DestroyImmediate(pcObject.GetComponent<Selector>());
DestroyImmediate(pcObject.GetComponent<ProximitySelector>());
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("The player will not use a Dialogue System-provided targeting component.", MessageType.None);
EditorWindowTools.EndIndentedSection();
}
private void DrawProximitySelector() {
DestroyImmediate(pcObject.GetComponent<Selector>());
ProximitySelector proximitySelector = pcObject.GetComponent<ProximitySelector>() ?? pcObject.AddComponent<ProximitySelector>();
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("The player can target usable objects (e.g., conversations on NPCs) when inside their trigger areas. Click Select Player to customize the Proximity Selector.", MessageType.None);
DrawSelectorUIPosition();
proximitySelector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", proximitySelector.useKey);
proximitySelector.useButton = EditorGUILayout.TextField("'Use' Button", proximitySelector.useButton);
EditorWindowTools.EndIndentedSection();
}
private void DrawSelector(SelectorType selectorType) {
DestroyImmediate(pcObject.GetComponent<ProximitySelector>());
Selector selector = pcObject.GetComponent<Selector>() ?? pcObject.AddComponent<Selector>();
EditorWindowTools.StartIndentedSection();
switch (selectorType) {
case SelectorType.CenterOfScreen:
EditorGUILayout.HelpBox("Usable objects in the center of the screen will be targeted.", MessageType.None);
selector.selectAt = Selector.SelectAt.CenterOfScreen;
break;
case SelectorType.MousePosition:
EditorGUILayout.HelpBox("Usable objects under the mouse cursor will be targeted. Specify which mouse button activates the targeted object.", MessageType.None);
selector.selectAt = Selector.SelectAt.MousePosition;
MouseButtonChoice mouseButtonChoice = string.Equals(selector.useButton, "Fire2") ? MouseButtonChoice.RightMouseButton : MouseButtonChoice.LeftMouseButton;
mouseButtonChoice = (MouseButtonChoice) EditorGUILayout.EnumPopup("Select With", mouseButtonChoice);
selector.useButton = (mouseButtonChoice == MouseButtonChoice.RightMouseButton) ? "Fire2" : "Fire1";
break;
default:
case SelectorType.CustomPosition:
EditorGUILayout.HelpBox("Usable objects will be targeted at a custom screen position. You are responsible for setting the Selector component's CustomPosition property.", MessageType.None);
selector.selectAt = Selector.SelectAt.CustomPosition;
break;
}
if (selector.reticle != null) {
selector.reticle.inRange = EditorGUILayout.ObjectField("In-Range Reticle", selector.reticle.inRange, typeof(Texture2D), false) as Texture2D;
selector.reticle.outOfRange = EditorGUILayout.ObjectField("Out-of-Range Reticle", selector.reticle.outOfRange, typeof(Texture2D), false) as Texture2D;
}
DrawSelectorUIPosition();
selector.useKey = (KeyCode) EditorGUILayout.EnumPopup("'Use' Key", selector.useKey);
selector.useButton = EditorGUILayout.TextField("'Use' Button", selector.useButton);
EditorGUILayout.HelpBox("Click Select Player to customize the Selector.", MessageType.None);
EditorWindowTools.EndIndentedSection();
}
private enum SelectorUIPositionType {
TopOfScreen,
OnSelectionTarget
}
private void DrawSelectorUIPosition() {
SelectorFollowTarget selectorFollowTarget = pcObject.GetComponent<SelectorFollowTarget>();
SelectorUIPositionType position = (selectorFollowTarget != null) ? SelectorUIPositionType.OnSelectionTarget : SelectorUIPositionType.TopOfScreen;
EditorGUILayout.HelpBox("Specify where the current selection message will be displayed.", MessageType.None);
position = (SelectorUIPositionType) EditorGUILayout.EnumPopup("Message Position", position);
if (position == SelectorUIPositionType.TopOfScreen) {
DestroyImmediate(selectorFollowTarget);
} else {
if (selectorFollowTarget == null) pcObject.AddComponent<SelectorFollowTarget>();
}
}
private void DrawOverrideNameSubsection() {
NPCSetupWizard.DrawOverrideNameSubsection(pcObject);
}
private void DrawTransitionStage() {
EditorGUILayout.LabelField("Gameplay/Conversation Transition", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
SetEnabledOnDialogueEvent setEnabled = pcObject.GetComponent<SetEnabledOnDialogueEvent>();
setEnabledFlag = setEnabledFlag || (setEnabled != null);
if (!setEnabledFlag) EditorGUILayout.HelpBox("Gameplay components, such as movement and camera control, will interfere with conversations. If you want to disable gameplay components during conversations, tick the checkbox below.", MessageType.None);
EditorGUILayout.BeginHorizontal();
setEnabledFlag = EditorGUILayout.Toggle(setEnabledFlag, GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Disable gameplay components during conversations", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
DrawDisableControlsSection();
DrawShowCursorSection();
if (GUILayout.Button("Select Player", GUILayout.Width(100))) Selection.activeGameObject = pcObject;
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawDisableControlsSection() {
EditorWindowTools.StartIndentedSection();
SetEnabledOnDialogueEvent enabler = FindConversationEnabler();
if (setEnabledFlag) {
if (enabler == null) enabler = pcObject.AddComponent<SetEnabledOnDialogueEvent>();
enabler.trigger = DialogueEvent.OnConversation;
enabler.onStart = GetPlayerControls(enabler.onStart, Toggle.False);
enabler.onEnd = GetPlayerControls(enabler.onEnd, Toggle.True);
ShowDisabledComponents(enabler.onStart);
} else {
DestroyImmediate(enabler);
}
EditorWindowTools.EndIndentedSection();
}
private SetEnabledOnDialogueEvent FindConversationEnabler() {
foreach (var component in pcObject.GetComponents<SetEnabledOnDialogueEvent>()) {
if (component.trigger == DialogueEvent.OnConversation) return component;
}
return null;
}
private void ShowDisabledComponents(SetEnabledOnDialogueEvent.SetEnabledAction[] actionList) {
EditorGUILayout.LabelField("The following components will be disabled during conversations:");
EditorWindowTools.StartIndentedSection();
foreach (SetEnabledOnDialogueEvent.SetEnabledAction action in actionList) {
if (action.target != null) {
EditorGUILayout.LabelField(action.target.GetType().Name);
}
}
EditorWindowTools.EndIndentedSection();
}
private SetEnabledOnDialogueEvent.SetEnabledAction[] GetPlayerControls(SetEnabledOnDialogueEvent.SetEnabledAction[] oldList, Toggle state) {
List<SetEnabledOnDialogueEvent.SetEnabledAction> actions = new List<SetEnabledOnDialogueEvent.SetEnabledAction>();
if (oldList != null) {
actions.AddRange(oldList);
}
foreach (var component in pcObject.GetComponents<MonoBehaviour>()) {
if (IsPlayerControlComponent(component) && !IsInActionList(actions, component)) {
AddToActionList(actions, component, state);
}
}
SmoothCameraWithBumper smoothCamera = pcObject.GetComponentInChildren<SmoothCameraWithBumper>();
if (smoothCamera == null) smoothCamera = Camera.main.GetComponent<SmoothCameraWithBumper>();
if ((smoothCamera != null) && !IsInActionList(actions, smoothCamera)) {
AddToActionList(actions, smoothCamera, state);
}
actions.RemoveAll(a => ((a == null) || (a.target == null)));
return actions.ToArray();
}
private bool IsPlayerControlComponent(MonoBehaviour component) {
return (component is Selector) ||
(component is ProximitySelector) ||
(component is SimpleController) ||
(component is NavigateOnMouseClick);
}
private bool IsInActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component) {
return (actions.Find(a => (a.target == component)) != null);
}
private void AddToActionList(List<SetEnabledOnDialogueEvent.SetEnabledAction> actions, MonoBehaviour component, Toggle state) {
SetEnabledOnDialogueEvent.SetEnabledAction newAction = new SetEnabledOnDialogueEvent.SetEnabledAction();
newAction.state = state;
newAction.target = component;
actions.Add(newAction);
}
private void DrawShowCursorSection() {
EditorWindowTools.DrawHorizontalLine();
ShowCursorOnConversation showCursor = pcObject.GetComponent<ShowCursorOnConversation>();
bool showCursorFlag = (showCursor != null);
if (!showCursorFlag) EditorGUILayout.HelpBox("If regular gameplay hides the mouse cursor, tick Show Mouse Cursor to enable it during conversations.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
showCursorFlag = EditorGUILayout.Toggle(showCursorFlag, GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Show mouse cursor during conversations", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (showCursorFlag) {
if (showCursor == null) showCursor = pcObject.AddComponent<ShowCursorOnConversation>();
} else {
DestroyImmediate(showCursor);
}
}
private void DrawPersistenceStage() {
EditorGUILayout.LabelField("Persistence", EditorStyles.boldLabel);
PersistentPositionData persistentPositionData = pcObject.GetComponent<PersistentPositionData>();
EditorWindowTools.StartIndentedSection();
if (persistentPositionData == null) EditorGUILayout.HelpBox("The player can be configured to record its position in the Dialogue System's Lua environment so it will be preserved when saving and loading games.", MessageType.Info);
EditorGUILayout.BeginHorizontal();
bool hasPersistentPosition = EditorGUILayout.Toggle((persistentPositionData != null), GUILayout.Width(ToggleWidth));
EditorGUILayout.LabelField("Player records position for saved games", EditorStyles.boldLabel);
EditorGUILayout.EndHorizontal();
if (hasPersistentPosition) {
if (persistentPositionData == null) {
persistentPositionData = pcObject.AddComponent<PersistentPositionData>();
persistentPositionData.overrideActorName = "Player";
}
if (string.IsNullOrEmpty(persistentPositionData.overrideActorName)) {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}'] (the name of the GameObject) or the Override Actor Name if defined. You can override the name below.", pcObject.name), MessageType.None);
} else {
EditorGUILayout.HelpBox(string.Format("Position data will be saved to the Actor['{0}']. To use the name of the GameObject instead, clear the field below.", persistentPositionData.overrideActorName), MessageType.None);
}
persistentPositionData.overrideActorName = EditorGUILayout.TextField("Actor Name", persistentPositionData.overrideActorName);
} else {
DestroyImmediate(persistentPositionData);
}
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, false);
}
private void DrawReviewStage() {
EditorGUILayout.LabelField("Review", EditorStyles.boldLabel);
EditorWindowTools.StartIndentedSection();
EditorGUILayout.HelpBox("Your Player is ready! Below is a summary of the configuration.", MessageType.Info);
SimpleController simpleController = pcObject.GetComponent<SimpleController>();
NavigateOnMouseClick navigateOnMouseClick = pcObject.GetComponent<NavigateOnMouseClick>();
if (simpleController != null) {
EditorGUILayout.LabelField("Control: Third-Person Shooter Style");
} else if (navigateOnMouseClick != null) {
EditorGUILayout.LabelField("Control: Follow Mouse Clicks");
} else {
EditorGUILayout.LabelField("Control: Custom");
}
switch (GetSelectorType()) {
case SelectorType.CenterOfScreen: EditorGUILayout.LabelField("Targeting: Center of Screen"); break;
case SelectorType.CustomPosition: EditorGUILayout.LabelField("Targeting: Custom Position (you must set Selector.CustomPosition)"); break;
case SelectorType.MousePosition: EditorGUILayout.LabelField("Targeting: Mouse Position"); break;
case SelectorType.Proximity: EditorGUILayout.LabelField("Targeting: Proximity"); break;
default: EditorGUILayout.LabelField("Targeting: None"); break;
}
SetEnabledOnDialogueEvent enabler = FindConversationEnabler();
if (enabler != null) ShowDisabledComponents(enabler.onStart);
ShowCursorOnConversation showCursor = pcObject.GetComponentInChildren<ShowCursorOnConversation>();
if (showCursor != null) EditorGUILayout.LabelField("Show Cursor During Conversations: Yes");
PersistentPositionData persistentPositionData = pcObject.GetComponentInChildren<PersistentPositionData>();
EditorGUILayout.LabelField(string.Format("Save Position: {0}", (persistentPositionData != null) ? "Yes" : "No"));
EditorWindowTools.EndIndentedSection();
DrawNavigationButtons(true, true, true);
}
}
}
| |
/*
* 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-2014-10-01.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>
/// Container for the parameters to the RegisterImage operation.
/// Registers an AMI. When you're creating an AMI, this is the final step you must complete
/// before you can launch an instance from the AMI. For more information about creating
/// AMIs, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami.html">Creating
/// Your Own AMIs</a> in the <i>Amazon Elastic Compute Cloud User Guide for Linux</i>.
///
/// <note>
/// <para>
/// For Amazon EBS-backed instances, <a>CreateImage</a> creates and registers the AMI
/// in a single request, so you don't have to register the AMI yourself.
/// </para>
/// </note>
/// <para>
/// You can also use <code>RegisterImage</code> to create an Amazon EBS-backed AMI from
/// a snapshot of a root device volume. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/Using_LaunchingInstanceFromSnapshot.html">Launching
/// an Instance from a Snapshot</a> in the <i>Amazon Elastic Compute Cloud User Guide
/// for Linux</i>.
/// </para>
///
/// <para>
/// If needed, you can deregister an AMI at any time. Any modifications you make to an
/// AMI backed by an instance store volume invalidates its registration. If you make changes
/// to an image, deregister the previous image and register the new image.
/// </para>
/// <note>
/// <para>
/// You can't register an image where a secondary (non-root) snapshot has AWS Marketplace
/// product codes.
/// </para>
/// </note>
/// </summary>
public partial class RegisterImageRequest : AmazonEC2Request
{
private ArchitectureValues _architecture;
private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>();
private string _description;
private string _imageLocation;
private string _kernelId;
private string _name;
private string _ramdiskId;
private string _rootDeviceName;
private string _sriovNetSupport;
private string _virtualizationType;
/// <summary>
/// Empty constructor used to set properties independently even when a simple constructor is available
/// </summary>
public RegisterImageRequest() { }
/// <summary>
/// Instantiates RegisterImageRequest with the parameterized properties
/// </summary>
/// <param name="imageLocation">The full path to your AMI manifest in Amazon S3 storage.</param>
public RegisterImageRequest(string imageLocation)
{
_imageLocation = imageLocation;
}
/// <summary>
/// Gets and sets the property Architecture.
/// <para>
/// The architecture of the AMI.
/// </para>
///
/// <para>
/// Default: For Amazon EBS-backed AMIs, <code>i386</code>. For instance store-backed
/// AMIs, the architecture specified in the manifest file.
/// </para>
/// </summary>
public ArchitectureValues Architecture
{
get { return this._architecture; }
set { this._architecture = value; }
}
// Check to see if Architecture property is set
internal bool IsSetArchitecture()
{
return this._architecture != null;
}
/// <summary>
/// Gets and sets the property BlockDeviceMappings.
/// <para>
/// One or more block device mapping entries.
/// </para>
/// </summary>
public List<BlockDeviceMapping> BlockDeviceMappings
{
get { return this._blockDeviceMappings; }
set { this._blockDeviceMappings = value; }
}
// Check to see if BlockDeviceMappings property is set
internal bool IsSetBlockDeviceMappings()
{
return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// A description for your AMI.
/// </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 ImageLocation.
/// <para>
/// The full path to your AMI manifest in Amazon S3 storage.
/// </para>
/// </summary>
public string ImageLocation
{
get { return this._imageLocation; }
set { this._imageLocation = value; }
}
// Check to see if ImageLocation property is set
internal bool IsSetImageLocation()
{
return this._imageLocation != null;
}
/// <summary>
/// Gets and sets the property KernelId.
/// <para>
/// The ID of the kernel.
/// </para>
/// </summary>
public string KernelId
{
get { return this._kernelId; }
set { this._kernelId = value; }
}
// Check to see if KernelId property is set
internal bool IsSetKernelId()
{
return this._kernelId != null;
}
/// <summary>
/// Gets and sets the property Name.
/// <para>
/// A name for your AMI.
/// </para>
///
/// <para>
/// Constraints: 3-128 alphanumeric characters, parentheses (()), square brackets ([]),
/// spaces ( ), periods (.), slashes (/), dashes (-), single quotes ('), at-signs (@),
/// or underscores(_)
/// </para>
/// </summary>
public string Name
{
get { return this._name; }
set { this._name = value; }
}
// Check to see if Name property is set
internal bool IsSetName()
{
return this._name != null;
}
/// <summary>
/// Gets and sets the property RamdiskId.
/// <para>
/// The ID of the RAM disk.
/// </para>
/// </summary>
public string RamdiskId
{
get { return this._ramdiskId; }
set { this._ramdiskId = value; }
}
// Check to see if RamdiskId property is set
internal bool IsSetRamdiskId()
{
return this._ramdiskId != null;
}
/// <summary>
/// Gets and sets the property RootDeviceName.
/// <para>
/// The name of the root device (for example, <code>/dev/sda1</code>, or <code>xvda</code>).
/// </para>
/// </summary>
public string RootDeviceName
{
get { return this._rootDeviceName; }
set { this._rootDeviceName = value; }
}
// Check to see if RootDeviceName property is set
internal bool IsSetRootDeviceName()
{
return this._rootDeviceName != null;
}
/// <summary>
/// Gets and sets the property SriovNetSupport.
/// <para>
/// Set to <code>simple</code> to enable enhanced networking for the AMI and any instances
/// that you launch from the AMI.
/// </para>
///
/// <para>
/// There is no way to disable enhanced networking at this time.
/// </para>
///
/// <para>
/// This option is supported only for HVM AMIs. Specifying this option with a PV AMI can
/// make instances launched from the AMI unreachable.
/// </para>
/// </summary>
public string SriovNetSupport
{
get { return this._sriovNetSupport; }
set { this._sriovNetSupport = value; }
}
// Check to see if SriovNetSupport property is set
internal bool IsSetSriovNetSupport()
{
return this._sriovNetSupport != null;
}
/// <summary>
/// Gets and sets the property VirtualizationType.
/// <para>
/// The type of virtualization.
/// </para>
///
/// <para>
/// Default: <code>paravirtual</code>
/// </para>
/// </summary>
public string VirtualizationType
{
get { return this._virtualizationType; }
set { this._virtualizationType = value; }
}
// Check to see if VirtualizationType property is set
internal bool IsSetVirtualizationType()
{
return this._virtualizationType != null;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Security;
using Newtonsoft.Json;
using Umbraco.Core.Configuration;
using Umbraco.Core.Logging;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.DatabaseModelDefinitions;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Relators;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Security;
namespace Umbraco.Core.Persistence.Repositories
{
/// <summary>
/// Represents the UserRepository for doing CRUD operations for <see cref="IUser"/>
/// </summary>
internal class UserRepository : PetaPocoRepositoryBase<int, IUser>, IUserRepository
{
private readonly IDictionary<string, string> _passwordConfiguration;
/// <summary>
/// Constructor
/// </summary>
/// <param name="work"></param>
/// <param name="cacheHelper"></param>
/// <param name="logger"></param>
/// <param name="sqlSyntax"></param>
/// <param name="passwordConfiguration">
/// A dictionary specifying the configuration for user passwords. If this is null then no password configuration will be persisted or read.
/// </param>
public UserRepository(IScopeUnitOfWork work, CacheHelper cacheHelper, ILogger logger, ISqlSyntaxProvider sqlSyntax,
IDictionary<string, string> passwordConfiguration = null)
: base(work, cacheHelper, logger, sqlSyntax)
{
_passwordConfiguration = passwordConfiguration;
}
#region Overrides of RepositoryBase<int,IUser>
protected override IUser PerformGet(int id)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dto = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.FirstOrDefault();
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by username
/// </summary>
/// <param name="username"></param>
/// <param name="includeSecurityData">
/// Can be used for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes).
/// This is really only used for a shim in order to upgrade to 7.6.
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser GetByUsername(string username, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
/// <summary>
/// Returns a user by id
/// </summary>
/// <param name="id"></param>
/// <param name="includeSecurityData">
/// This is really only used for a shim in order to upgrade to 7.6 but could be used
/// for slightly faster user lookups if the result doesn't require security data (i.e. groups, apps & start nodes)
/// </param>
/// <returns>
/// A non cached <see cref="IUser"/> instance
/// </returns>
public IUser Get(int id, bool includeSecurityData)
{
UserDto dto;
if (includeSecurityData)
{
var sql = GetQueryWithGroups();
sql.Where(GetBaseWhereClause(), new { Id = id });
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
dto = Database
.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(
new UserGroupRelator().Map, sql)
.FirstOrDefault();
}
else
{
var sql = GetBaseQuery("umbracoUser.*");
sql.Where(GetBaseWhereClause(), new { Id = id });
dto = Database.FirstOrDefault<UserDto>(sql);
}
if (dto == null)
return null;
var user = UserFactory.BuildEntity(dto);
return user;
}
public IProfile GetProfile(string username)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Login == username, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IProfile GetProfile(int id)
{
var sql = GetBaseQuery(false).Where<UserDto>(userDto => userDto.Id == id, SqlSyntax);
var dto = Database.Fetch<UserDto>(sql)
.FirstOrDefault();
if (dto == null)
return null;
return new UserProfile(dto.Id, dto.UserName);
}
public IDictionary<UserState, int> GetUserStates()
{
var sql = @"SELECT '1CountOfAll' AS colName, COUNT(id) AS num FROM umbracoUser
UNION
SELECT '2CountOfActive' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL
UNION
SELECT '3CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 1
UNION
SELECT '4CountOfLockedOut' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userNoConsole = 1
UNION
SELECT '5CountOfInvited' AS colName, COUNT(id) AS num FROM umbracoUser WHERE lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL
UNION
SELECT '6CountOfDisabled' AS colName, COUNT(id) AS num FROM umbracoUser WHERE userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NULL
ORDER BY colName";
var result = Database.Fetch<dynamic>(sql);
return new Dictionary<UserState, int>
{
{UserState.All, (int)result[0].num},
{UserState.Active, (int)result[1].num},
{UserState.Disabled, (int)result[2].num},
{UserState.LockedOut, (int)result[3].num},
{UserState.Invited, (int)result[4].num},
{UserState.Inactive, (int) result[5].num}
};
}
public Guid CreateLoginSession(int userId, string requestingIpAddress, bool cleanStaleSessions = true)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var now = DateTime.UtcNow;
var dto = new UserLoginDto
{
UserId = userId,
IpAddress = requestingIpAddress,
LoggedInUtc = now,
LastValidatedUtc = now,
LoggedOutUtc = null,
SessionId = Guid.NewGuid()
};
Database.Insert(dto);
if (cleanStaleSessions)
{
ClearLoginSessions(TimeSpan.FromDays(15));
}
return dto.SessionId;
}
public bool ValidateLoginSession(int userId, Guid sessionId)
{
var found = Database.FirstOrDefault<UserLoginDto>("WHERE sessionId=@sessionId", new {sessionId = sessionId});
if (found == null || found.UserId != userId || found.LoggedOutUtc.HasValue)
return false;
//now detect if there's been a timeout
if (DateTime.UtcNow - found.LastValidatedUtc > TimeSpan.FromMinutes(GlobalSettings.TimeOutInMinutes))
{
//timeout detected, update the record
ClearLoginSession(sessionId);
return false;
}
//update the validate date
found.LastValidatedUtc = DateTime.UtcNow;
Database.Update(found);
return true;
}
public int ClearLoginSessions(int userId)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE userId=@userId", new { userId = userId });
Database.Execute("DELETE FROM umbracoUserLogin WHERE userId=@userId", new {userId = userId});
return count;
}
public int ClearLoginSessions(TimeSpan timespan)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
var fromDate = DateTime.UtcNow - timespan;
var count = Database.ExecuteScalar<int>("SELECT COUNT(*) FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate });
Database.Execute("DELETE FROM umbracoUserLogin WHERE lastValidatedUtc=@fromDate", new { fromDate = fromDate });
return count;
}
public void ClearLoginSession(Guid sessionId)
{
//TODO: I know this doesn't follow the normal repository conventions which would require us to crete a UserSessionRepository
//and also business logic models for these objects but that's just so overkill for what we are doing
//and now that everything is properly in a transaction (Scope) there doesn't seem to be much reason for using that anymore
Database.Execute("UPDATE umbracoUserLogin SET loggedOutUtc=@now WHERE sessionId=@sessionId",
new { now = DateTime.UtcNow, sessionId = sessionId });
}
protected override IEnumerable<IUser> PerformGetAll(params int[] ids)
{
var sql = GetQueryWithGroups();
if (ids.Any())
{
sql.Where("umbracoUser.id in (@ids)", new { ids = ids });
}
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
protected override IEnumerable<IUser> PerformGetByQuery(IQuery<IUser> query)
{
var sqlClause = GetQueryWithGroups();
var translator = new SqlTranslator<IUser>(sqlClause, query);
var sql = translator.Translate();
sql //must be included for relator to work
.OrderBy<UserDto>(d => d.Id, SqlSyntax)
.OrderBy<UserGroupDto>(d => d.Id, SqlSyntax)
.OrderBy<UserStartNodeDto>(d => d.Id, SqlSyntax);
var dtos = Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, sql)
.DistinctBy(x => x.Id);
var users = ConvertFromDtos(dtos)
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
#endregion
#region Overrides of PetaPocoRepositoryBase<int,IUser>
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<UserDto>();
}
else
{
return GetBaseQuery("*");
}
return sql;
}
/// <summary>
/// A query to return a user with it's groups and with it's groups sections
/// </summary>
/// <returns></returns>
private Sql GetQueryWithGroups()
{
//base query includes user groups
var sql = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
AddGroupLeftJoin(sql);
return sql;
}
private void AddGroupLeftJoin(Sql sql)
{
sql.LeftJoin<User2UserGroupDto>(SqlSyntax)
.On<User2UserGroupDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id)
.LeftJoin<UserGroupDto>(SqlSyntax)
.On<UserGroupDto, User2UserGroupDto>(SqlSyntax, dto => dto.Id, dto => dto.UserGroupId)
.LeftJoin<UserGroup2AppDto>(SqlSyntax)
.On<UserGroup2AppDto, UserGroupDto>(SqlSyntax, dto => dto.UserGroupId, dto => dto.Id)
.LeftJoin<UserStartNodeDto>(SqlSyntax)
.On<UserStartNodeDto, UserDto>(SqlSyntax, dto => dto.UserId, dto => dto.Id);
}
private Sql GetBaseQuery(string columns)
{
var sql = new Sql();
sql.Select(columns)
.From<UserDto>();
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoUser.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM cmsTask WHERE userId = @Id",
"DELETE FROM cmsTask WHERE parentUserId = @Id",
"DELETE FROM umbracoUser2UserGroup WHERE userId = @Id",
"DELETE FROM umbracoUser2NodeNotify WHERE userId = @Id",
"DELETE FROM umbracoUserStartNode WHERE userId = @Id",
"DELETE FROM umbracoUser WHERE id = @Id",
"DELETE FROM umbracoExternalLogin WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IUser entity)
{
((User)entity).AddingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
}
var id = Convert.ToInt32(Database.Insert(userDto));
entity.Id = id;
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, Enumerable.Empty<UserStartNodeDto>(), UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IUser entity)
{
//Updates Modified date
((User)entity).UpdatingEntity();
//ensure security stamp if non
if (entity.SecurityStamp.IsNullOrWhiteSpace())
{
entity.SecurityStamp = Guid.NewGuid().ToString();
}
var userDto = UserFactory.BuildDto(entity);
//build list of columns to check for saving - we don't want to save the password if it hasn't changed!
//List the columns to save, NOTE: would be nice to not have hard coded strings here but no real good way around that
var colsToSave = new Dictionary<string, string>()
{
{"userDisabled", "IsApproved"},
{"userNoConsole", "IsLockedOut"},
{"startStructureID", "StartContentId"},
{"startMediaID", "StartMediaId"},
{"userName", "Name"},
{"userLogin", "Username"},
{"userEmail", "Email"},
{"userLanguage", "Language"},
{"securityStampToken", "SecurityStamp"},
{"lastLockoutDate", "LastLockoutDate"},
{"lastPasswordChangeDate", "LastPasswordChangeDate"},
{"lastLoginDate", "LastLoginDate"},
{"failedLoginAttempts", "FailedPasswordAttempts"},
{"createDate", "CreateDate"},
{"updateDate", "UpdateDate"},
{"avatar", "Avatar"},
{"emailConfirmedDate", "EmailConfirmedDate"},
{"invitedDate", "InvitedDate"},
{"tourData", "TourData"}
};
//create list of properties that have changed
var changedCols = colsToSave
.Where(col => entity.IsPropertyDirty(col.Value))
.Select(col => col.Key)
.ToList();
// DO NOT update the password if it has not changed or if it is null or empty
if (entity.IsPropertyDirty("RawPasswordValue") && entity.RawPasswordValue.IsNullOrWhiteSpace() == false)
{
changedCols.Add("userPassword");
//special case - when using ASP.Net identity the user manager will take care of updating the security stamp, however
// when not using ASP.Net identity (i.e. old membership providers), we'll need to take care of updating this manually
// so we can just detect if that property is dirty, if it's not we'll set it manually
if (entity.IsPropertyDirty("SecurityStamp") == false)
{
userDto.SecurityStampToken = entity.SecurityStamp = Guid.NewGuid().ToString();
changedCols.Add("securityStampToken");
}
//Check if we have a known config, we only want to store config for hashing
//TODO: This logic will need to be updated when we do http://issues.umbraco.org/issue/U4-10089
if (_passwordConfiguration != null && _passwordConfiguration.Count > 0)
{
var json = JsonConvert.SerializeObject(_passwordConfiguration);
userDto.PasswordConfig = json;
changedCols.Add("passwordConfig");
}
}
//only update the changed cols
if (changedCols.Count > 0)
{
Database.Update(userDto, changedCols);
}
if (entity.IsPropertyDirty("StartContentIds") || entity.IsPropertyDirty("StartMediaIds"))
{
var assignedStartNodes = Database.Fetch<UserStartNodeDto>("SELECT * FROM umbracoUserStartNode WHERE userId = @userId", new { userId = entity.Id });
if (entity.IsPropertyDirty("StartContentIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Content, entity.StartContentIds);
}
if (entity.IsPropertyDirty("StartMediaIds"))
{
AddingOrUpdateStartNodes(entity, assignedStartNodes, UserStartNodeDto.StartNodeTypeValue.Media, entity.StartMediaIds);
}
}
if (entity.IsPropertyDirty("Groups"))
{
//lookup all assigned
var assigned = entity.Groups == null || entity.Groups.Any() == false
? new List<UserGroupDto>()
: Database.Fetch<UserGroupDto>("SELECT * FROM umbracoUserGroup WHERE userGroupAlias IN (@aliases)", new { aliases = entity.Groups.Select(x => x.Alias) });
//first delete all
//TODO: We could do this a nicer way instead of "Nuke and Pave"
Database.Delete<User2UserGroupDto>("WHERE UserId = @UserId", new { UserId = entity.Id });
foreach (var groupDto in assigned)
{
var dto = new User2UserGroupDto
{
UserGroupId = groupDto.Id,
UserId = entity.Id
};
Database.Insert(dto);
}
}
entity.ResetDirtyProperties();
}
private void AddingOrUpdateStartNodes(IEntity entity, IEnumerable<UserStartNodeDto> current, UserStartNodeDto.StartNodeTypeValue startNodeType, int[] entityStartIds)
{
var assignedIds = current.Where(x => x.StartNodeType == (int)startNodeType).Select(x => x.StartNode).ToArray();
//remove the ones not assigned to the entity
var toDelete = assignedIds.Except(entityStartIds).ToArray();
if (toDelete.Length > 0)
Database.Delete<UserStartNodeDto>("WHERE UserId = @UserId AND startNode IN (@startNodes)", new { UserId = entity.Id, startNodes = toDelete });
//add the ones not currently in the db
var toAdd = entityStartIds.Except(assignedIds).ToArray();
foreach (var i in toAdd)
{
var dto = new UserStartNodeDto
{
StartNode = i,
StartNodeType = (int)startNodeType,
UserId = entity.Id
};
Database.Insert(dto);
}
}
#endregion
#region Implementation of IUserRepository
public int GetCountByQuery(IQuery<IUser> query)
{
var sqlClause = GetBaseQuery("umbracoUser.id");
var translator = new SqlTranslator<IUser>(sqlClause, query);
var subquery = translator.Translate();
//get the COUNT base query
var sql = GetBaseQuery(true)
.Append(new Sql("WHERE umbracoUser.id IN (" + subquery.SQL + ")", subquery.Arguments));
return Database.ExecuteScalar<int>(sql);
}
public bool Exists(string username)
{
var sql = new Sql();
sql.Select("COUNT(*)")
.From<UserDto>()
.Where<UserDto>(x => x.UserName == username);
return Database.ExecuteScalar<int>(sql) > 0;
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, true);
}
/// <summary>
/// Gets a list of <see cref="IUser"/> objects not associated with a given group
/// </summary>
/// <param name="groupId">Id of group</param>
public IEnumerable<IUser> GetAllNotInGroup(int groupId)
{
return GetAllInOrNotInGroup(groupId, false);
}
private IEnumerable<IUser> GetAllInOrNotInGroup(int groupId, bool include)
{
var sql = new Sql();
sql.Select("*")
.From<UserDto>();
var innerSql = new Sql();
innerSql.Select("umbracoUser.id")
.From<UserDto>()
.LeftJoin<User2UserGroupDto>()
.On<UserDto, User2UserGroupDto>(left => left.Id, right => right.UserId)
.Where("umbracoUser2UserGroup.userGroupId = " + groupId);
sql.Where(string.Format("umbracoUser.id {0} ({1})",
include ? "IN" : "NOT IN",
innerSql.SQL));
return ConvertFromDtos(Database.Fetch<UserDto>(sql));
}
[Obsolete("Use the overload with long operators instead")]
[EditorBrowsable(EditorBrowsableState.Never)]
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, int pageIndex, int pageSize, out int totalRecords, Expression<Func<IUser, string>> orderBy)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
long tr;
var results = GetPagedResultsByQuery(query, Convert.ToInt64(pageIndex), pageSize, out tr, mappedField, Direction.Ascending);
totalRecords = Convert.ToInt32(tr);
return results;
}
/// <summary>
/// Gets paged user results
/// </summary>
/// <param name="query"></param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <param name="orderDirection"></param>
/// <param name="includeUserGroups">
/// A filter to only include user that belong to these user groups
/// </param>
/// <param name="excludeUserGroups">
/// A filter to only include users that do not belong to these user groups
/// </param>
/// <param name="userState">Optional parameter to filter by specfied user state</param>
/// <param name="filter"></param>
/// <returns></returns>
/// <remarks>
/// The query supplied will ONLY work with data specifically on the umbracoUser table because we are using PetaPoco paging (SQL paging)
/// </remarks>
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords,
Expression<Func<IUser, object>> orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> filter = null)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
// get the referenced column name and find the corresp mapped column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
return GetPagedResultsByQuery(query, pageIndex, pageSize, out totalRecords, mappedField, orderDirection, includeUserGroups, excludeUserGroups, userState, filter);
}
private IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, long pageIndex, int pageSize, out long totalRecords, string orderBy, Direction orderDirection,
string[] includeUserGroups = null,
string[] excludeUserGroups = null,
UserState[] userState = null,
IQuery<IUser> customFilter = null)
{
if (string.IsNullOrWhiteSpace(orderBy)) throw new ArgumentException("Value cannot be null or whitespace.", "orderBy");
Sql filterSql = null;
var customFilterWheres = customFilter != null ? customFilter.GetWhereClauses().ToArray() : null;
var hasCustomFilter = customFilterWheres != null && customFilterWheres.Length > 0;
if (hasCustomFilter
|| (includeUserGroups != null && includeUserGroups.Length > 0) || (excludeUserGroups != null && excludeUserGroups.Length > 0)
|| (userState != null && userState.Length > 0 && userState.Contains(UserState.All) == false))
filterSql = new Sql();
if (hasCustomFilter)
{
foreach (var filterClause in customFilterWheres)
{
filterSql.Append($"AND ({filterClause.Item1})", filterClause.Item2);
}
}
if (includeUserGroups != null && includeUserGroups.Length > 0)
{
const string subQuery = @"AND (umbracoUser.id IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = includeUserGroups });
}
if (excludeUserGroups != null && excludeUserGroups.Length > 0)
{
const string subQuery = @"AND (umbracoUser.id NOT IN (SELECT DISTINCT umbracoUser.id
FROM umbracoUser
INNER JOIN umbracoUser2UserGroup ON umbracoUser2UserGroup.userId = umbracoUser.id
INNER JOIN umbracoUserGroup ON umbracoUserGroup.id = umbracoUser2UserGroup.userGroupId
WHERE umbracoUserGroup.userGroupAlias IN (@userGroups)))";
filterSql.Append(subQuery, new { userGroups = excludeUserGroups });
}
if (userState != null && userState.Length > 0)
{
//the "ALL" state doesn't require any filtering so we ignore that, if it exists in the list we don't do any filtering
if (userState.Contains(UserState.All) == false)
{
var sb = new StringBuilder("(");
var appended = false;
if (userState.Contains(UserState.Active))
{
sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NOT NULL)");
appended = true;
}
if (userState.Contains(UserState.Inactive))
{
if (appended) sb.Append(" OR ");
sb.Append("(userDisabled = 0 AND userNoConsole = 0 AND lastLoginDate IS NULL)");
appended = true;
}
if (userState.Contains(UserState.Disabled))
{
if (appended) sb.Append(" OR ");
sb.Append("(userDisabled = 1)");
appended = true;
}
if (userState.Contains(UserState.LockedOut))
{
if (appended) sb.Append(" OR ");
sb.Append("(userNoConsole = 1)");
appended = true;
}
if (userState.Contains(UserState.Invited))
{
if (appended) sb.Append(" OR ");
sb.Append("(lastLoginDate IS NULL AND userDisabled = 1 AND invitedDate IS NOT NULL)");
appended = true;
}
sb.Append(")");
filterSql.Append("AND " + sb);
}
}
// Get base query for returning IDs
var sqlBaseIds = GetBaseQuery("id");
if (query == null) query = new Query<IUser>();
var queryHasWhereClause = query.GetWhereClauses().Any();
var translatorIds = new SqlTranslator<IUser>(sqlBaseIds, query);
var sqlQueryIds = translatorIds.Translate();
var sqlBaseFull = GetBaseQuery("umbracoUser.*, umbracoUserGroup.*, umbracoUserGroup2App.*, umbracoUserStartNode.*");
var translatorFull = new SqlTranslator<IUser>(sqlBaseFull, query);
//get sorted and filtered sql
var sqlNodeIdsWithSort = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(sqlQueryIds, filterSql, queryHasWhereClause),
orderDirection, orderBy);
// Get page of results and total count
var pagedResult = Database.Page<UserDto>(pageIndex + 1, pageSize, sqlNodeIdsWithSort);
totalRecords = Convert.ToInt32(pagedResult.TotalItems);
//NOTE: We need to check the actual items returned, not the 'totalRecords', that is because if you request a page number
// that doesn't actually have any data on it, the totalRecords will still indicate there are records but there are none in
// the pageResult.
if (pagedResult.Items.Any())
{
//Create the inner paged query that was used above to get the paged result, we'll use that as the inner sub query
var args = sqlNodeIdsWithSort.Arguments;
string sqlStringCount, sqlStringPage;
Database.BuildPageQueries<UserDto>(pageIndex * pageSize, pageSize, sqlNodeIdsWithSort.SQL, ref args, out sqlStringCount, out sqlStringPage);
var sqlQueryFull = translatorFull.Translate();
//We need to make this FULL query an inner join on the paged ID query
var splitQuery = sqlQueryFull.SQL.Split(new[] { "WHERE " }, StringSplitOptions.None);
var fullQueryWithPagedInnerJoin = new Sql(splitQuery[0])
.Append("INNER JOIN (")
//join the paged query with the paged query arguments
.Append(sqlStringPage, args)
.Append(") temp ")
.Append("ON umbracoUser.id = temp.id");
AddGroupLeftJoin(fullQueryWithPagedInnerJoin);
if (splitQuery.Length > 1)
{
//add the original where clause back with the original arguments
fullQueryWithPagedInnerJoin.Where(splitQuery[1], sqlQueryIds.Arguments);
}
//get sorted and filtered sql
var fullQuery = GetSortedSqlForPagedResults(
GetFilteredSqlForPagedResults(fullQueryWithPagedInnerJoin, filterSql, queryHasWhereClause),
orderDirection, orderBy);
var users = ConvertFromDtos(Database.Fetch<UserDto, UserGroupDto, UserGroup2AppDto, UserStartNodeDto, UserDto>(new UserGroupRelator().Map, fullQuery))
.ToArray(); // important so we don't iterate twice, if we don't do this we can end up with null values in cache if we were caching.
return users;
}
return Enumerable.Empty<IUser>();
}
private Sql GetFilteredSqlForPagedResults(Sql sql, Sql filterSql, bool hasWhereClause)
{
Sql filteredSql;
// Apply filter
if (filterSql != null)
{
//ensure we don't append a WHERE if there is already one
var sqlFilter = hasWhereClause
? filterSql.SQL
: " WHERE " + filterSql.SQL.TrimStart("AND ");
//NOTE: this is certainly strange - NPoco handles this much better but we need to re-create the sql
// instance a couple of times to get the parameter order correct, for some reason the first
// time the arguments don't show up correctly but the SQL argument parameter names are actually updated
// accordingly - so we re-create it again. In v8 we don't need to do this and it's already taken care of.
filteredSql = new Sql(sql.SQL, sql.Arguments);
var args = filteredSql.Arguments.Concat(filterSql.Arguments).ToArray();
filteredSql = new Sql(
string.Format("{0} {1}", filteredSql.SQL, sqlFilter),
args);
filteredSql = new Sql(filteredSql.SQL, args);
}
else
{
//copy to var so that the original isn't changed
filteredSql = new Sql(sql.SQL, sql.Arguments);
}
return filteredSql;
}
private Sql GetSortedSqlForPagedResults(Sql sql, Direction orderDirection, string orderBy)
{
//copy to var so that the original isn't changed
var sortedSql = new Sql(sql.SQL, sql.Arguments);
// Apply order according to parameters
if (string.IsNullOrEmpty(orderBy) == false)
{
//each order by param needs to be in a bracket! see: https://github.com/toptensoftware/PetaPoco/issues/177
var orderByParams = new[] { string.Format("({0})", orderBy) };
if (orderDirection == Direction.Ascending)
{
sortedSql.OrderBy(orderByParams);
}
else
{
sortedSql.OrderByDescending(orderByParams);
}
}
return sortedSql;
}
internal IEnumerable<IUser> GetNextUsers(int id, int count)
{
var idsQuery = new Sql()
.Select("umbracoUser.id")
.From<UserDto>(SqlSyntax)
.Where<UserDto>(x => x.Id >= id)
.OrderBy<UserDto>(x => x.Id, SqlSyntax);
// first page is index 1, not zero
var ids = Database.Page<int>(1, count, idsQuery).Items.ToArray();
// now get the actual users and ensure they are ordered properly (same clause)
return ids.Length == 0 ? Enumerable.Empty<IUser>() : GetAll(ids).OrderBy(x => x.Id);
}
#endregion
private IEnumerable<IUser> ConvertFromDtos(IEnumerable<UserDto> dtos)
{
return dtos.Select(UserFactory.BuildEntity);
}
}
}
| |
/*
Copyright (c) 2003-2006 Niels Kokholm and Peter Sestoft
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.
*/
// C5 example: 2006-01-29
// Compile with
// csc /r:C5.dll MultiDictionary.cs
using System;
using C5;
using SCG = System.Collections.Generic;
namespace MultiDictionaries
{
using Inner = HashSet<String>;
using MultiDictionary3;
public class MyTest
{
public static void Main()
{
MultiHashDictionary<int, String, Inner> mdict = new MultiHashDictionary<int, String, Inner>();
mdict.Add(2, "to");
mdict.Add(2, "deux");
mdict.Add(2, "two");
mdict.Add(20, "tyve");
mdict.Add(20, "tyve");
mdict.Add(20, "twenty");
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
Console.WriteLine("mdict.Count (keys) is {0}",
((IDictionary<int, Inner>)mdict).Count);
Console.WriteLine("mdict[2].Count is {0}", mdict[2].Count);
mdict.Remove(20, "tyve");
mdict.Remove(20, "twenty");
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
Inner zwei = new Inner();
zwei.Add("zwei");
mdict[2] = zwei;
mdict[-2] = zwei;
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
zwei.Add("kaksi");
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
Inner empty = new Inner();
mdict[0] = empty;
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
Console.WriteLine("mdict contains key 0: {0}", mdict.Contains(0));
mdict.Remove(-2);
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
zwei.Remove("kaksi");
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
zwei.Clear();
Console.WriteLine(mdict);
Console.WriteLine("mdict.Count is {0}", mdict.Count);
}
}
}
namespace MultiDictionary1
{
// Here we implement a multivalued dictionary as a hash dictionary
// from keys to value collections. The value collections may have set
// or bag semantics.
// The value collections are externally modifiable (as in Peter
// Golde's PowerCollections library), and therefore:
//
// * A value collection associated with a key may be null or
// non-empty. Hence for correct semantics, the Contains(k) method
// must check that the value collection associated with a key is
// non-null and non-empty.
//
// * A value collection may be shared between two or more keys.
//
// A C5 hash dictionary each of whose keys map to a collection of values.
public class MultiHashDictionary<K, V> : HashDictionary<K, ICollection<V>>
{
// Return total count of values associated with keys. This basic
// implementation simply sums over all value collections, and so
// is a linear-time operation in the total number of values.
public new virtual int Count
{
get
{
int count = 0;
foreach (KeyValuePair<K, ICollection<V>> entry in this)
if (entry.Value != null)
count += entry.Value.Count;
return count;
}
}
public override Speed CountSpeed
{
get { return Speed.Linear; }
}
// Add a (key,value) pair
public virtual void Add(K k, V v)
{
ICollection<V> values;
if (!base.Find(k, out values) || values == null)
{
values = new HashSet<V>();
Add(k, values);
}
values.Add(v);
}
// Remove a single (key,value) pair, if present; return true if
// anything was removed, else false
public virtual bool Remove(K k, V v)
{
ICollection<V> values;
if (base.Find(k, out values) && values != null)
{
if (values.Remove(v))
{
if (values.IsEmpty)
base.Remove(k);
return true;
}
}
return false;
}
// Determine whether key k is associated with a value
public override bool Contains(K k)
{
ICollection<V> values;
return Find(k, out values) && values != null && !values.IsEmpty;
}
// Determine whether each key in ks is associated with a value
public override bool ContainsAll<U>(SCG.IEnumerable<U> ks)
{
foreach (K k in ks)
if (!Contains(k))
return false;
return true;
}
// Get or set the value collection associated with key k
public override ICollection<V> this[K k]
{
get
{
ICollection<V> values;
return base.Find(k, out values) && values != null ? values : new HashSet<V>();
}
set
{
base[k] = value;
}
}
// Inherited from base class HashDictionary<K,ICollection<V>>:
// Add(K k, ICollection<V> values)
// AddAll(IEnumerable<KeyValuePair<K,ICollection<V>>> kvs)
// Clear
// Clone
// Find(K k, out ICollection<V> values)
// Find(ref K k, out ICollection<V> values)
// FindOrAdd(K k, ref ICollection<V> values)
// Remove(K k)
// Remove(K k, out ICollection<V> values)
// Update(K k, ICollection<V> values)
// Update(K k, ICollection<V> values, out ICollection<V> oldValues)
// UpdateOrAdd(K k, ICollection<V> values)
// UpdateOrAdd(K k, ICollection<V> values, out ICollection<V> oldValues)
}
}
namespace MultiDictionary2
{
// Here we implement a multivalued dictionary as a hash dictionary
// from keys to value collections. The value collections may have
// set or bag semantics. This version uses event listeners to make
// the Count operation constant time.
// * To avoid recomputing the total number of values for the Count
// property, one may cache it and then use event listeners on the
// value collections to keep the cached count updated. In turn, this
// requires such event listeners on the dictionary also.
// A C5 hash dictionary each of whose keys map to a collection of values.
public class MultiHashDictionary<K, V> : HashDictionary<K, ICollection<V>>
{
private int count = 0; // Cached value count, updated by events only
private void IncrementCount(Object sender, ItemCountEventArgs<V> args)
{
count += args.Count;
}
private void DecrementCount(Object sender, ItemCountEventArgs<V> args)
{
count -= args.Count;
}
private void ClearedCount(Object sender, ClearedEventArgs args)
{
count -= args.Count;
}
public MultiHashDictionary()
{
ItemsAdded +=
delegate(Object sender, ItemCountEventArgs<KeyValuePair<K, ICollection<V>>> args)
{
ICollection<V> values = args.Item.Value;
if (values != null)
{
count += values.Count;
values.ItemsAdded += IncrementCount;
values.ItemsRemoved += DecrementCount;
values.CollectionCleared += ClearedCount;
}
};
ItemsRemoved +=
delegate(Object sender, ItemCountEventArgs<KeyValuePair<K, ICollection<V>>> args)
{
ICollection<V> values = args.Item.Value;
if (values != null)
{
count -= values.Count;
values.ItemsAdded -= IncrementCount;
values.ItemsRemoved -= DecrementCount;
values.CollectionCleared -= ClearedCount;
}
};
}
// Return total count of values associated with keys.
public new virtual int Count
{
get
{
return count;
}
}
public override Speed CountSpeed
{
get { return Speed.Constant; }
}
// Add a (key,value) pair
public virtual void Add(K k, V v)
{
ICollection<V> values;
if (!base.Find(k, out values) || values == null)
{
values = new HashSet<V>();
Add(k, values);
}
values.Add(v);
}
// Remove a single (key,value) pair, if present; return true if
// anything was removed, else false
public virtual bool Remove(K k, V v)
{
ICollection<V> values;
if (base.Find(k, out values) && values != null)
{
if (values.Remove(v))
{
if (values.IsEmpty)
base.Remove(k);
return true;
}
}
return false;
}
// Determine whether key k is associated with a value
public override bool Contains(K k)
{
ICollection<V> values;
return Find(k, out values) && values != null && !values.IsEmpty;
}
// Determine whether each key in ks is associated with a value
public override bool ContainsAll<U>(SCG.IEnumerable<U> ks)
{
foreach (K k in ks)
if (!Contains(k))
return false;
return true;
}
// Get or set the value collection associated with key k
public override ICollection<V> this[K k]
{
get
{
ICollection<V> values;
return base.Find(k, out values) && values != null ? values : new HashSet<V>();
}
set
{
base[k] = value;
}
}
}
}
namespace MultiDictionary3
{
// Here we implement a multivalued dictionary as a hash dictionary
// from keys to value collections. The value collections may have
// set or bag semantics. This version uses event listeners to make
// the Count operation constant time.
// * To avoid recomputing the total number of values for the Count
// property, one may cache it and then use event listeners on the
// value collections to keep the cached count updated. In turn, this
// requires such event listeners on the dictionary also.
// A C5 hash dictionary each of whose keys map to a collection of values.
public class MultiHashDictionary<K, V, W> : HashDictionary<K, W> where W : ICollection<V>, new()
{
private int count = 0; // Cached value count, updated by events only
private void IncrementCount(Object sender, ItemCountEventArgs<V> args)
{
count += args.Count;
}
private void DecrementCount(Object sender, ItemCountEventArgs<V> args)
{
count -= args.Count;
}
private void ClearedCount(Object sender, ClearedEventArgs args)
{
count -= args.Count;
}
public MultiHashDictionary()
{
ItemsAdded +=
delegate(Object sender, ItemCountEventArgs<KeyValuePair<K, W>> args)
{
ICollection<V> values = args.Item.Value;
if (values != null)
{
count += values.Count;
values.ItemsAdded += IncrementCount;
values.ItemsRemoved += DecrementCount;
values.CollectionCleared += ClearedCount;
}
};
ItemsRemoved +=
delegate(Object sender, ItemCountEventArgs<KeyValuePair<K, W>> args)
{
ICollection<V> values = args.Item.Value;
if (values != null)
{
count -= values.Count;
values.ItemsAdded -= IncrementCount;
values.ItemsRemoved -= DecrementCount;
values.CollectionCleared -= ClearedCount;
}
};
}
// Return total count of values associated with keys.
public new virtual int Count
{
get
{
return count;
}
}
public override Speed CountSpeed
{
get { return Speed.Constant; }
}
// Add a (key,value) pair
public virtual void Add(K k, V v)
{
W values;
if (!base.Find(k, out values) || values == null)
{
values = new W();
Add(k, values);
}
values.Add(v);
}
// Remove a single (key,value) pair, if present; return true if
// anything was removed, else false
public virtual bool Remove(K k, V v)
{
W values;
if (base.Find(k, out values) && values != null)
{
if (values.Remove(v))
{
if (values.IsEmpty)
base.Remove(k);
return true;
}
}
return false;
}
// Determine whether key k is associated with a value
public override bool Contains(K k)
{
W values;
return Find(k, out values) && values != null && !values.IsEmpty;
}
// Determine whether each key in ks is associated with a value
public override bool ContainsAll<U>(SCG.IEnumerable<U> ks)
{
foreach (K k in ks)
if (!Contains(k))
return false;
return true;
}
// Get or set the value collection associated with key k
public override W this[K k]
{
get
{
W values;
return base.Find(k, out values) && values != null ? values : new W();
}
set
{
base[k] = 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 System.Diagnostics;
using System.Threading.Tasks;
namespace System.Net.Sockets
{
// The System.Net.Sockets.TcpClient class provide TCP services at a higher level
// of abstraction than the System.Net.Sockets.Socket class. System.Net.Sockets.TcpClient
// is used to create a Client connection to a remote host.
public partial class TcpClient : IDisposable
{
private readonly AddressFamily _family;
private Socket _clientSocket;
private NetworkStream _dataStream;
private bool _cleanedUp = false;
private bool _active;
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient() : this(AddressFamily.InterNetwork)
{
}
// Initializes a new instance of the System.Net.Sockets.TcpClient class.
public TcpClient(AddressFamily family)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", family);
}
// Validate parameter
if (family != AddressFamily.InterNetwork && family != AddressFamily.InterNetworkV6)
{
throw new ArgumentException(SR.Format(SR.net_protocol_invalid_family, "TCP"), nameof(family));
}
_family = family;
InitializeClientSocket();
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by TcpListener.Accept().
internal TcpClient(Socket acceptedSocket)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "TcpClient", acceptedSocket);
}
_clientSocket = acceptedSocket;
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "TcpClient", null);
}
}
// Used by the class to indicate that a connection has been made.
protected bool Active
{
get { return _active; }
set { _active = value; }
}
public int Available { get { return AvailableCore; } }
// Used by the class to provide the underlying network socket.
[DebuggerBrowsable(DebuggerBrowsableState.Never)] // TODO: Remove once https://github.com/dotnet/corefx/issues/5868 is addressed.
public Socket Client
{
get { return ClientCore; }
set { ClientCore = value; }
}
public bool Connected { get { return ConnectedCore; } }
public bool ExclusiveAddressUse
{
get { return ExclusiveAddressUseCore; }
set { ExclusiveAddressUseCore = value; }
}
public Task ConnectAsync(IPAddress address, int port)
{
return Task.Factory.FromAsync(
(targetAddess, targetPort, callback, state) => ((TcpClient)state).BeginConnect(targetAddess, targetPort, callback, state),
asyncResult => ((TcpClient)asyncResult.AsyncState).EndConnect(asyncResult),
address,
port,
state: this);
}
public Task ConnectAsync(string host, int port)
{
return ConnectAsyncCore(host, port);
}
public Task ConnectAsync(IPAddress[] addresses, int port)
{
return ConnectAsyncCore(addresses, port);
}
private IAsyncResult BeginConnect(IPAddress address, int port, AsyncCallback requestCallback, object state)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "BeginConnect", address);
}
IAsyncResult result = Client.BeginConnect(address, port, requestCallback, state);
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "BeginConnect", null);
}
return result;
}
private void EndConnect(IAsyncResult asyncResult)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "EndConnect", asyncResult);
}
Socket s = Client;
if (s == null)
{
// Dispose nulls out the client socket field.
throw new ObjectDisposedException(GetType().Name);
}
s.EndConnect(asyncResult);
_active = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "EndConnect", null);
}
}
// Returns the stream used to read and write data to the remote host.
public NetworkStream GetStream()
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "GetStream", "");
}
if (_cleanedUp)
{
throw new ObjectDisposedException(this.GetType().FullName);
}
if (!Connected)
{
throw new InvalidOperationException(SR.net_notconnected);
}
if (_dataStream == null)
{
_dataStream = new NetworkStream(Client, true);
}
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "GetStream", _dataStream);
}
return _dataStream;
}
// Disposes the Tcp connection.
protected virtual void Dispose(bool disposing)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Enter(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
if (_cleanedUp)
{
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
return;
}
if (disposing)
{
IDisposable dataStream = _dataStream;
if (dataStream != null)
{
dataStream.Dispose();
}
else
{
// If the NetworkStream wasn't created, the Socket might
// still be there and needs to be closed. In the case in which
// we are bound to a local IPEndPoint this will remove the
// binding and free up the IPEndPoint for later uses.
Socket chkClientSocket = _clientSocket;
if (chkClientSocket != null)
{
try
{
chkClientSocket.InternalShutdown(SocketShutdown.Both);
}
finally
{
chkClientSocket.Dispose();
_clientSocket = null;
}
}
}
DisposeCore(); // platform-specific disposal work
GC.SuppressFinalize(this);
}
_cleanedUp = true;
if (NetEventSource.Log.IsEnabled())
{
NetEventSource.Exit(NetEventSource.ComponentType.Socket, this, "Dispose", "");
}
}
public void Dispose()
{
Dispose(true);
}
~TcpClient()
{
#if DEBUG
GlobalLog.SetThreadSource(ThreadKinds.Finalization);
using (GlobalLog.SetThreadKind(ThreadKinds.System | ThreadKinds.Async))
{
#endif
Dispose(false);
#if DEBUG
}
#endif
}
// Gets or sets the size of the receive buffer in bytes.
public int ReceiveBufferSize
{
get { return ReceiveBufferSizeCore; }
set { ReceiveBufferSizeCore = value; }
}
// Gets or sets the size of the send buffer in bytes.
public int SendBufferSize
{
get { return SendBufferSizeCore; }
set { SendBufferSizeCore = value; }
}
// Gets or sets the receive time out value of the connection in milliseconds.
public int ReceiveTimeout
{
get { return ReceiveTimeoutCore; }
set { ReceiveTimeoutCore = value; }
}
// Gets or sets the send time out value of the connection in milliseconds.
public int SendTimeout
{
get { return SendTimeoutCore; }
set { SendTimeoutCore = value; }
}
// Gets or sets the value of the connection's linger option.
public LingerOption LingerState
{
get { return LingerStateCore; }
set { LingerStateCore = value; }
}
// Enables or disables delay when send or receive buffers are full.
public bool NoDelay
{
get { return NoDelayCore; }
set { NoDelayCore = value; }
}
private Socket CreateSocket()
{
return new Socket(_family, SocketType.Stream, ProtocolType.Tcp);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Windows.Forms; // MessageBox
using System.Diagnostics;
using System.Xml;
using System.Text;
using Moritz.Globals;
using Moritz.Xml;
using Moritz.Spec;
namespace Moritz.Symbols
{
public class SvgPage
{
/// <summary>
/// The systems contain Metrics info, but their top staffline is at 0.
/// The systems are moved to their correct vertical positions on the page here.
/// If pageNumber is set to 0, all the systems in pageSystems will be printed
/// in a single .svg file, whose page height has been changed accordingly.
/// </summary>
/// <param name="Systems"></param>
public SvgPage(SvgScore containerScore, PageFormat pageFormat, int pageNumber, TextInfo infoTextInfo, List<SvgSystem> pageSystems, bool lastPage)
{
_score = containerScore;
_pageFormat = pageFormat;
_pageNumber = pageNumber;
_infoTextInfo = infoTextInfo;
Systems = pageSystems;
if(pageNumber == 0)
{
pageFormat.BottomVBPX = GetNewBottomVBPX(pageSystems);
pageFormat.BottomMarginPos = (int) (pageFormat.BottomVBPX - pageFormat.DefaultDistanceBetweenSystems);
}
MoveSystemsVertically(pageFormat, pageSystems, (pageNumber == 1 || pageNumber == 0), lastPage);
}
private int GetNewBottomVBPX(List<SvgSystem> pageSystems)
{
int frameHeight = _pageFormat.TopMarginPage1 + 20;
foreach(SvgSystem system in pageSystems)
{
SystemMetrics sm = system.Metrics;
frameHeight += (int)((sm.Bottom - sm.Top) + _pageFormat.DefaultDistanceBetweenSystems);
}
return frameHeight;
}
/// <summary>
/// Moves the systems to their correct vertical position. Justifies on all but the last page.
/// On the first page use pageFormat.FirstPageFrameHeight.
/// On the last page (which may also be the first), the systems are separated by
/// pageFormat.MinimumDistanceBetweenSystems.
/// </summary>
private void MoveSystemsVertically(PageFormat pageFormat, List<SvgSystem> pageSystems, bool firstPage, bool lastPage)
{
float frameTop;
float frameHeight;
if(firstPage)
{
frameTop = pageFormat.TopMarginPage1;
frameHeight = pageFormat.FirstPageFrameHeight; // property uses BottomMarginPos
}
else
{
frameTop = pageFormat.TopMarginOtherPages;
frameHeight = pageFormat.OtherPagesFrameHeight;
}
MoveSystemsVertically(pageSystems, frameTop, frameHeight, pageFormat.DefaultDistanceBetweenSystems, lastPage);
}
private void MoveSystemsVertically(List<SvgSystem> pageSystems, float frameTop, float frameHeight, float defaultSystemSeparation, bool lastPage)
{
float systemSeparation = 0;
if(lastPage) // dont justify
{
systemSeparation = defaultSystemSeparation;
}
else
{
if(pageSystems.Count >= 1)
{
float totalSystemHeight = 0;
foreach(SvgSystem system in pageSystems)
{
Debug.Assert(system.Metrics != null);
totalSystemHeight += (system.Metrics.NotesBottom - system.Metrics.NotesTop);
}
systemSeparation = (frameHeight - totalSystemHeight) / (pageSystems.Count - 1);
}
}
float top = frameTop;
foreach(SvgSystem system in pageSystems)
{
if(system.Metrics != null)
{
float deltaY = top - system.Metrics.NotesTop;
// Limit stafflineHeight to multiples of _pageMetrics.Gap
// so that stafflines are not displayed as thick grey lines.
// The following works, because the top staffline of each system is currently at 0.
deltaY -= (deltaY % _pageFormat.Gap);
system.Metrics.Move(0F, deltaY);
top = system.Metrics.NotesBottom + systemSeparation;
}
}
}
/// <summary>
/// Writes this page.
/// </summary>
/// <param name="w"></param>
public void WriteSVG(SvgWriter w, Metadata metadata, bool isSinglePageScore)
{
int nOutputVoices = 0;
int nInputVoices = 0;
GetNumbersOfVoices(Systems[0], ref nOutputVoices, ref nInputVoices);
w.WriteStartDocument(); // standalone="no"
//<?xml-stylesheet href="../../fontsStyleSheet.css" type="text/css"?>
w.WriteProcessingInstruction("xml-stylesheet", "href=\"../../fontsStyleSheet.css\" type=\"text/css\"");
w.WriteStartElement("svg", "http://www.w3.org/2000/svg");
WriteSvgHeader(w);
metadata.WriteSVG(w, _pageNumber, _score.PageCount, _pageFormat.AboutLinkURL, nOutputVoices, nInputVoices);
_score.WriteDefs(w, _pageNumber);
if(isSinglePageScore)
{
_score.WriteScoreData(w);
}
#region layers
if(_pageNumber > 0)
{
WriteFrameLayer(w, _pageFormat.Right, _pageFormat.Bottom);
}
WriteSystemsLayer(w, _pageNumber, metadata);
w.WriteComment(@" Annotations that are added here will be ignored by the AssistantPerformer. ");
#endregion layers
w.WriteEndElement(); // close the svg element
w.WriteEndDocument();
}
private void GetNumbersOfVoices(SvgSystem svgSystem, ref int nOutputVoices, ref int nInputVoices)
{
nOutputVoices = 0;
nInputVoices = 0;
foreach(Staff staff in svgSystem.Staves)
{
foreach(Voice voice in staff.Voices)
{
if(voice is OutputVoice)
{
nOutputVoices++;
}
else if(voice is InputVoice)
{
nInputVoices++;
}
}
}
}
private void WriteFrameLayer(SvgWriter w, float width, float height)
{
w.SvgRect(CSSObjectClass.frame, 0, 0, width, height);
}
private void WriteSystemsLayer(SvgWriter w, int pageNumber, Metadata metadata)
{
w.SvgStartGroup(CSSObjectClass.systems.ToString());
//w.WriteAttributeString("style", "display:inline");
w.SvgText(CSSObjectClass.timeStamp, _infoTextInfo.Text, 32, _infoTextInfo.FontHeight);
if(pageNumber == 1 || pageNumber == 0)
{
WritePage1TitleAndAuthor(w, metadata);
}
List<CarryMsgs> carryMsgsPerChannel = new List<CarryMsgs>();
foreach(Staff staff in Systems[0].Staves)
{
foreach(Voice voice in staff.Voices)
{
carryMsgsPerChannel.Add(new CarryMsgs());
}
}
int systemNumber = 1;
foreach(SvgSystem system in Systems)
{
system.WriteSVG(w, systemNumber++, _pageFormat, carryMsgsPerChannel);
}
w.WriteEndElement(); // end layer
}
private void WriteSvgHeader(SvgWriter w)
{
w.WriteAttributeString("xmlns", "http://www.w3.org/2000/svg");
// I think the following is redundant...
//w.WriteAttributeString("xmlns", "svg", null, "http://www.w3.org/2000/svg");
// Deleted the following, since it is only advisory, and I think the latest version is 2. See deprecated xlink below.
//w.WriteAttributeString("version", "1.1");
// Namespaces used for standard metadata
w.WriteAttributeString("xmlns", "dc", null, "http://purl.org/dc/elements/1.1/");
w.WriteAttributeString("xmlns", "cc", null, "http://creativecommons.org/ns#");
w.WriteAttributeString("xmlns", "rdf", null, "http://www.w3.org/1999/02/22-rdf-syntax-ns#");
// Namespace used for linking to svg defs (defined objects)
// N.B.: xlink is deprecated in SVG 2
// w.WriteAttributeString("xmlns", "xlink", null, "http://www.w3.org/1999/xlink");
// Standard definition of the "score" namespace.
// The file documents the additional attributes and elements available in the "score" namespace.
w.WriteAttributeString("xmlns", "score", null, "https://www.james-ingram-act-two.de/open-source/svgScoreExtensions.html");
// The file defines and documents all the element classes used in this particular scoreType.
// The definitions include information as to how the classes nest, and the directions in which they are read.
// For example:
// 1) in cmn_core files, systems are read from top to bottom on a page, and contain
// staves that are read in parallel, left to right.
// 2) cmn_1950.html files might include elements having class="tupletBracket", but
// cmn_core files don't. As with the score namespace, the file does not actually
// need to be read by the client code in order to discover the scoreType.
w.WriteAttributeString("data-scoreType", null, "https://www.james-ingram-act-two.de/open-source/cmn_core.html");
w.WriteAttributeString("width", M.FloatToShortString(_pageFormat.ScreenRight)); // the intended screen display size (100%)
w.WriteAttributeString("height", M.FloatToShortString(_pageFormat.ScreenBottom)); // the intended screen display size (100%)
string viewBox = "0 0 " + _pageFormat.RightVBPX.ToString() + " " + _pageFormat.BottomVBPX.ToString();
w.WriteAttributeString("viewBox", viewBox); // the size of SVG's internal drawing surface (800%)
}
/// <summary>
/// Adds the main title and the author to the first page.
/// </summary>
protected void WritePage1TitleAndAuthor(SvgWriter w, Metadata metadata)
{
string titlesFontFamily = "Open Sans";
TextInfo titleInfo =
new TextInfo(metadata.Page1Title, titlesFontFamily, _pageFormat.Page1TitleHeight,
null, TextHorizAlign.center);
TextInfo authorInfo =
new TextInfo(metadata.Page1Author, titlesFontFamily, _pageFormat.Page1AuthorHeight,
null, TextHorizAlign.right);
w.WriteStartElement("g");
w.WriteAttributeString("class", CSSObjectClass.titles.ToString());
w.SvgText(CSSObjectClass.mainTitle, titleInfo.Text, _pageFormat.Right / 2F, _pageFormat.Page1TitleY);
w.SvgText(CSSObjectClass.author, authorInfo.Text, _pageFormat.RightMarginPos, _pageFormat.Page1TitleY);
w.WriteEndElement(); // group
}
#region used when creating graphic score
private readonly SvgScore _score;
private PageFormat _pageFormat;
private readonly int _pageNumber;
private TextInfo _infoTextInfo;
#endregion
public List<SvgSystem> Systems = new List<SvgSystem>();
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ConversationTest.cs" company="Brandon Seydel">
// N/A
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System.Linq;
using System.Threading.Tasks;
using MailChimp.Net.Core;
using MailChimp.Net.Models;
using Xunit;
namespace MailChimp.Net.Tests
{
/// <summary>
/// The campaign test.
/// </summary>
public class CampaignTest : MailChimpTest
{
/// <summary>
/// The should_ create_ campaign_
/// </summary>
/// <returns></returns>
[Fact]
public async Task Should_Add_Campaign()
{
var campaign = await this.MailChimpManager.Campaigns.AddAsync(new Campaign
{
Settings = new Setting
{
ReplyTo = "test@test.com",
Title = "Get Rich or Die Trying To Add Campaigns",
FromName = "AddCampaign",
SubjectLine = "TestingAddCampaign"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
Assert.NotNull(campaign);
}
/// <summary>
/// The should_ update_ campaign_
/// </summary>
/// <returns></returns>
[Fact]
public async Task Should_Update_Campaign()
{
var campaigns = await this.MailChimpManager.Campaigns.GetAll(new CampaignRequest { Limit = 1 }).ConfigureAwait(false);
var campaign = campaigns.FirstOrDefault();
if (campaign != null)
{
var updated = await this.MailChimpManager.Campaigns.UpdateAsync(campaign.Id, new Campaign
{
Settings = new Setting
{
ReplyTo = "updatedtest@updatedtest.com",
Title = "Updated from Unit Test",
FromName = "Updated Tester",
SubjectLine = "Updated Test"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
Assert.NotNull(updated);
}
}
/// <summary>
/// The should_ replicate_ campaign_
/// </summary>
/// <returns></returns>
[Fact]
public async Task Should_Replicate_Campaign()
{
var campaigns = await this.MailChimpManager.Campaigns.GetAllAsync().ConfigureAwait(false);
var campaign = campaigns.FirstOrDefault();
if (campaign != null)
{
var response = await this.MailChimpManager.Campaigns.ReplicateCampaignAsync(campaign.Id).ConfigureAwait(false);
Assert.NotNull(response);
}
}
/// <summary>
/// The should_ delete_ campaign_
/// </summary>
/// <returns></returns>
[Fact]
public async Task Should_Delete_Campaign()
{
var campaigns = (await this.MailChimpManager.Campaigns.GetAllAsync().ConfigureAwait(false)).ToList();
var campaign = campaigns.FirstOrDefault();
if (campaign != null)
{
await this.MailChimpManager.Campaigns.DeleteAsync(campaign.Id).ConfigureAwait(false);
var campaignsnow = await this.MailChimpManager.Campaigns.GetAllAsync();
Assert.NotEqual(campaigns.Count(), campaignsnow.Count());
}
}
/// <summary>
/// The should_ get_ one_ campaign_ id_ and_ get_ campaign.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Fact]
public async Task Should_Get_One_Campain_Id_And_Get_Campaign()
{
await this.ClearMailChimpAsync().ConfigureAwait(true);
await this.MailChimpManager.Campaigns.AddAsync(new Campaign
{
Settings = new Setting
{
ReplyTo = "test@test.com",
Title = "Get Rich or Die Trying",
FromName = "TESTER",
SubjectLine = "TEST"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
await this.MailChimpManager.Campaigns.AddAsync(new Campaign
{
Settings = new Setting
{
ReplyTo = "test@test.com",
Title = "Get Rich or Die Trying part 2",
FromName = "TESTER",
SubjectLine = "TEST"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
var campaigns = await this.MailChimpManager.Campaigns.GetAll(new CampaignRequest { Limit = 1 });
Assert.True(campaigns.Count() == 1);
var campaign = await this.MailChimpManager.Campaigns.GetAsync(campaigns.FirstOrDefault().Id);
Assert.NotNull(campaign);
}
/// <summary>
/// The should_ return_ campaigns.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Fact]
public async Task Should_Return_Campaigns()
{
var campaigns = await this.MailChimpManager.Campaigns.GetAll();
Assert.NotNull(campaigns);
}
/// <summary>
/// The should_ return_ one_ campaign.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Fact]
public async Task Should_Return_One_Campaign()
{
var campaign = await this.MailChimpManager.Campaigns.AddAsync(new Campaign
{
Settings = new Setting
{
ReplyTo = "test@test.com",
Title = "Get Rich or Die Trying To Add Campaigns",
FromName = "AddCampaign",
SubjectLine = "TestingAddCampaign"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
var campaigns = await this.MailChimpManager.Campaigns.GetAll(new CampaignRequest { Limit = 1 });
Assert.True(campaigns.Count() == 1);
}
/// <summary>
/// Should_Return_Zero_Campaigns_After_Removal.
/// </summary>
/// <returns>
/// The <see cref="Task"/>.
/// </returns>
[Fact]
public async Task Should_Return_No_Campaigns_After_Removal()
{
await this.ClearMailChimpAsync().ConfigureAwait(true);
var campaign = await this.MailChimpManager.Campaigns.AddAsync(new Campaign
{
Settings = new Setting
{
ReplyTo = "test@test.com",
Title = "Test Campaign",
FromName = "TESTER",
SubjectLine = "TEST"
},
Type = CampaignType.Plaintext
}).ConfigureAwait(false);
await this.MailChimpManager.Campaigns.DeleteAsync(campaign.Id).ConfigureAwait(false);
var existingCampaigns = await this.MailChimpManager.Campaigns.GetAllAsync().ConfigureAwait(false);
Assert.Empty(existingCampaigns);
}
}
}
| |
// 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.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Use these APIs to manage Azure CDN resources through the Azure
/// Resource Manager. You must make sure that requests made to these
/// resources are secure.
/// </summary>
public partial class CdnManagementClient : Microsoft.Rest.ServiceClient<CdnManagementClient>, ICdnManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public Microsoft.Rest.ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Azure Subscription ID.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Version of the API to be used with the client request. Current version is
/// 2016-10-02.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IProfilesOperations.
/// </summary>
public virtual IProfilesOperations Profiles { get; private set; }
/// <summary>
/// Gets the IEndpointsOperations.
/// </summary>
public virtual IEndpointsOperations Endpoints { get; private set; }
/// <summary>
/// Gets the IOriginsOperations.
/// </summary>
public virtual IOriginsOperations Origins { get; private set; }
/// <summary>
/// Gets the ICustomDomainsOperations.
/// </summary>
public virtual ICustomDomainsOperations CustomDomains { get; private set; }
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected CdnManagementClient(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient 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>
protected CdnManagementClient(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient 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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CdnManagementClient(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected CdnManagementClient(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CdnManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CdnManagementClient(Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CdnManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the CdnManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <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>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public CdnManagementClient(System.Uri baseUri, Microsoft.Rest.ServiceClientCredentials credentials, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.Profiles = new ProfilesOperations(this);
this.Endpoints = new EndpointsOperations(this);
this.Origins = new OriginsOperations(this);
this.CustomDomains = new CustomDomainsOperations(this);
this.BaseUri = new System.Uri("https://management.azure.com");
this.ApiVersion = "2016-10-02";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(),
Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter>
{
new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new Microsoft.Rest.Serialization.TransformationJsonConverter());
DeserializationSettings.Converters.Add(new Microsoft.Rest.Azure.CloudErrorJsonConverter());
}
/// <summary>
/// Check the availability of a resource name without creating the resource.
/// This is needed for resources where name is globally unique, such as a CDN
/// endpoint.
/// </summary>
/// <param name='name'>
/// The resource name to validate.
/// </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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<CheckNameAvailabilityOutput>> CheckNameAvailabilityWithHttpMessagesAsync(string name, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.ApiVersion");
}
if (name == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "name");
}
CheckNameAvailabilityInput checkNameAvailabilityInput = new CheckNameAvailabilityInput();
if (name != null)
{
checkNameAvailabilityInput.Name = name;
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("checkNameAvailabilityInput", checkNameAvailabilityInput);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/checkNameAvailability").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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;
if(checkNameAvailabilityInput != null)
{
_requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(checkNameAvailabilityInput, this.SerializationSettings);
_httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<CheckNameAvailabilityOutput>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CheckNameAvailabilityOutput>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the available CDN REST API operations.
/// </summary>
/// <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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Operation>>> ListOperationsWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (this.ApiVersion == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.ApiVersion");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListOperations", tracingParameters);
}
// Construct URL
var _baseUrl = this.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "providers/Microsoft.Cdn/operations").ToString();
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (this.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(this.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Operation>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Lists all of the available CDN REST API operations.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List 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="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Operation>>> ListOperationsNextWithHttpMessagesAsync(string nextPageLink, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (nextPageLink == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "nextPageLink");
}
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("nextPageLink", nextPageLink);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "ListOperationsNext", tracingParameters);
}
// Construct URL
string _url = "{nextLink}";
_url = _url.Replace("{nextLink}", nextPageLink);
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.GenerateClientRequestId != null && this.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.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 (this.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, this.DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Microsoft.Rest.Azure.IPage<Operation>>();
_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 = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<Operation>>(_responseContent, this.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
* Swaggy Jenkins
*
* Jenkins API clients generated from Swagger / Open API specification
*
* The version of the OpenAPI document: 1.1.2-pre.0
* Contact: blah@cliffano.com
* Generated by: https://github.com/openapitools/openapi-generator.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter;
namespace Org.OpenAPITools.Model
{
/// <summary>
/// PipelineActivity
/// </summary>
[DataContract]
public partial class PipelineActivity : IEquatable<PipelineActivity>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="PipelineActivity" /> class.
/// </summary>
/// <param name="_class">_class.</param>
/// <param name="artifacts">artifacts.</param>
/// <param name="durationInMillis">durationInMillis.</param>
/// <param name="estimatedDurationInMillis">estimatedDurationInMillis.</param>
/// <param name="enQueueTime">enQueueTime.</param>
/// <param name="endTime">endTime.</param>
/// <param name="id">id.</param>
/// <param name="organization">organization.</param>
/// <param name="pipeline">pipeline.</param>
/// <param name="result">result.</param>
/// <param name="runSummary">runSummary.</param>
/// <param name="startTime">startTime.</param>
/// <param name="state">state.</param>
/// <param name="type">type.</param>
/// <param name="commitId">commitId.</param>
public PipelineActivity(string _class = default(string), List<PipelineActivityartifacts> artifacts = default(List<PipelineActivityartifacts>), int durationInMillis = default(int), int estimatedDurationInMillis = default(int), string enQueueTime = default(string), string endTime = default(string), string id = default(string), string organization = default(string), string pipeline = default(string), string result = default(string), string runSummary = default(string), string startTime = default(string), string state = default(string), string type = default(string), string commitId = default(string))
{
this.Class = _class;
this.Artifacts = artifacts;
this.DurationInMillis = durationInMillis;
this.EstimatedDurationInMillis = estimatedDurationInMillis;
this.EnQueueTime = enQueueTime;
this.EndTime = endTime;
this.Id = id;
this.Organization = organization;
this.Pipeline = pipeline;
this.Result = result;
this.RunSummary = runSummary;
this.StartTime = startTime;
this.State = state;
this.Type = type;
this.CommitId = commitId;
}
/// <summary>
/// Gets or Sets Class
/// </summary>
[DataMember(Name="_class", EmitDefaultValue=false)]
public string Class { get; set; }
/// <summary>
/// Gets or Sets Artifacts
/// </summary>
[DataMember(Name="artifacts", EmitDefaultValue=false)]
public List<PipelineActivityartifacts> Artifacts { get; set; }
/// <summary>
/// Gets or Sets DurationInMillis
/// </summary>
[DataMember(Name="durationInMillis", EmitDefaultValue=false)]
public int DurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EstimatedDurationInMillis
/// </summary>
[DataMember(Name="estimatedDurationInMillis", EmitDefaultValue=false)]
public int EstimatedDurationInMillis { get; set; }
/// <summary>
/// Gets or Sets EnQueueTime
/// </summary>
[DataMember(Name="enQueueTime", EmitDefaultValue=false)]
public string EnQueueTime { get; set; }
/// <summary>
/// Gets or Sets EndTime
/// </summary>
[DataMember(Name="endTime", EmitDefaultValue=false)]
public string EndTime { get; set; }
/// <summary>
/// Gets or Sets Id
/// </summary>
[DataMember(Name="id", EmitDefaultValue=false)]
public string Id { get; set; }
/// <summary>
/// Gets or Sets Organization
/// </summary>
[DataMember(Name="organization", EmitDefaultValue=false)]
public string Organization { get; set; }
/// <summary>
/// Gets or Sets Pipeline
/// </summary>
[DataMember(Name="pipeline", EmitDefaultValue=false)]
public string Pipeline { get; set; }
/// <summary>
/// Gets or Sets Result
/// </summary>
[DataMember(Name="result", EmitDefaultValue=false)]
public string Result { get; set; }
/// <summary>
/// Gets or Sets RunSummary
/// </summary>
[DataMember(Name="runSummary", EmitDefaultValue=false)]
public string RunSummary { get; set; }
/// <summary>
/// Gets or Sets StartTime
/// </summary>
[DataMember(Name="startTime", EmitDefaultValue=false)]
public string StartTime { get; set; }
/// <summary>
/// Gets or Sets State
/// </summary>
[DataMember(Name="state", EmitDefaultValue=false)]
public string State { get; set; }
/// <summary>
/// Gets or Sets Type
/// </summary>
[DataMember(Name="type", EmitDefaultValue=false)]
public string Type { get; set; }
/// <summary>
/// Gets or Sets CommitId
/// </summary>
[DataMember(Name="commitId", EmitDefaultValue=false)]
public string CommitId { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class PipelineActivity {\n");
sb.Append(" Class: ").Append(Class).Append("\n");
sb.Append(" Artifacts: ").Append(Artifacts).Append("\n");
sb.Append(" DurationInMillis: ").Append(DurationInMillis).Append("\n");
sb.Append(" EstimatedDurationInMillis: ").Append(EstimatedDurationInMillis).Append("\n");
sb.Append(" EnQueueTime: ").Append(EnQueueTime).Append("\n");
sb.Append(" EndTime: ").Append(EndTime).Append("\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" Organization: ").Append(Organization).Append("\n");
sb.Append(" Pipeline: ").Append(Pipeline).Append("\n");
sb.Append(" Result: ").Append(Result).Append("\n");
sb.Append(" RunSummary: ").Append(RunSummary).Append("\n");
sb.Append(" StartTime: ").Append(StartTime).Append("\n");
sb.Append(" State: ").Append(State).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" CommitId: ").Append(CommitId).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as PipelineActivity);
}
/// <summary>
/// Returns true if PipelineActivity instances are equal
/// </summary>
/// <param name="input">Instance of PipelineActivity to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(PipelineActivity input)
{
if (input == null)
return false;
return
(
this.Class == input.Class ||
(this.Class != null &&
this.Class.Equals(input.Class))
) &&
(
this.Artifacts == input.Artifacts ||
this.Artifacts != null &&
input.Artifacts != null &&
this.Artifacts.SequenceEqual(input.Artifacts)
) &&
(
this.DurationInMillis == input.DurationInMillis ||
(this.DurationInMillis != null &&
this.DurationInMillis.Equals(input.DurationInMillis))
) &&
(
this.EstimatedDurationInMillis == input.EstimatedDurationInMillis ||
(this.EstimatedDurationInMillis != null &&
this.EstimatedDurationInMillis.Equals(input.EstimatedDurationInMillis))
) &&
(
this.EnQueueTime == input.EnQueueTime ||
(this.EnQueueTime != null &&
this.EnQueueTime.Equals(input.EnQueueTime))
) &&
(
this.EndTime == input.EndTime ||
(this.EndTime != null &&
this.EndTime.Equals(input.EndTime))
) &&
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.Organization == input.Organization ||
(this.Organization != null &&
this.Organization.Equals(input.Organization))
) &&
(
this.Pipeline == input.Pipeline ||
(this.Pipeline != null &&
this.Pipeline.Equals(input.Pipeline))
) &&
(
this.Result == input.Result ||
(this.Result != null &&
this.Result.Equals(input.Result))
) &&
(
this.RunSummary == input.RunSummary ||
(this.RunSummary != null &&
this.RunSummary.Equals(input.RunSummary))
) &&
(
this.StartTime == input.StartTime ||
(this.StartTime != null &&
this.StartTime.Equals(input.StartTime))
) &&
(
this.State == input.State ||
(this.State != null &&
this.State.Equals(input.State))
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.CommitId == input.CommitId ||
(this.CommitId != null &&
this.CommitId.Equals(input.CommitId))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Class != null)
hashCode = hashCode * 59 + this.Class.GetHashCode();
if (this.Artifacts != null)
hashCode = hashCode * 59 + this.Artifacts.GetHashCode();
if (this.DurationInMillis != null)
hashCode = hashCode * 59 + this.DurationInMillis.GetHashCode();
if (this.EstimatedDurationInMillis != null)
hashCode = hashCode * 59 + this.EstimatedDurationInMillis.GetHashCode();
if (this.EnQueueTime != null)
hashCode = hashCode * 59 + this.EnQueueTime.GetHashCode();
if (this.EndTime != null)
hashCode = hashCode * 59 + this.EndTime.GetHashCode();
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.Organization != null)
hashCode = hashCode * 59 + this.Organization.GetHashCode();
if (this.Pipeline != null)
hashCode = hashCode * 59 + this.Pipeline.GetHashCode();
if (this.Result != null)
hashCode = hashCode * 59 + this.Result.GetHashCode();
if (this.RunSummary != null)
hashCode = hashCode * 59 + this.RunSummary.GetHashCode();
if (this.StartTime != null)
hashCode = hashCode * 59 + this.StartTime.GetHashCode();
if (this.State != null)
hashCode = hashCode * 59 + this.State.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.CommitId != null)
hashCode = hashCode * 59 + this.CommitId.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Diagnostics;
namespace m
{
/// <summary>
/// Summary description for CaNew.
/// </summary>
public class CaNew : System.Windows.Forms.Form
{
Type[] m_atype;
CaBase m_cab;
string m_strParse;
string m_strKind;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.Label m_labelWhatType;
private System.Windows.Forms.Label m_labelText;
private System.Windows.Forms.RichTextBox m_richTextBox;
private System.Windows.Forms.ComboBox m_comboBoxType;
private System.Windows.Forms.Button buttonCancel;
private System.Windows.Forms.Label m_labelDescription;
private System.Windows.Forms.GroupBox groupBox1;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public CaNew(CaBase cab, string strTitle, string strKind, Type[] atype, string[] astrName)
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
m_atype = atype;
m_cab = null;
m_strParse = null;
m_strKind = strKind;
// To do - might want to pretty print these type names
Text = strTitle;
m_labelWhatType.Text = m_labelWhatType.Text.Replace("$1", strKind);
m_labelText.Text = m_labelText.Text.Replace("$1", strKind);
Array.Sort(astrName, atype);
Array.Sort(astrName);
m_comboBoxType.DataSource = astrName;
m_cab = cab;
if (cab != null) {
m_comboBoxType.SelectedIndex = Array.IndexOf(atype, m_cab.GetType());
} else {
m_comboBoxType.SelectedIndex = 0;
}
SelectCa(m_comboBoxType.SelectedIndex);
}
CaBase GetCab() {
return m_cab;
}
public static CaBase DoModal(CaBase cab, string strTitle, string strKind) {
string strEndsWith = strKind;
System.Reflection.Assembly ass = typeof(CaBase).Module.Assembly;
Type[] atype = ass.GetTypes();
ArrayList alsType = new ArrayList();
ArrayList alsName = new ArrayList();
foreach (Type type in atype) {
string strName = type.ToString();
if (strName.EndsWith(strEndsWith)) {
alsType.Add(type);
string strDisplayName = Helper.GetDisplayName(type);
if (strDisplayName == null) {
int ichDot = strName.IndexOf('.');
strDisplayName = strName.Substring(ichDot + 1, strName.Length - (ichDot + 1 + strEndsWith.Length));
}
alsName.Add(strDisplayName);
}
}
CaNew frmCaNew = new CaNew(cab, strTitle, strKind, (Type[])alsType.ToArray(typeof(Type)), (string[])alsName.ToArray(typeof(string)) );
frmCaNew.ShowDialog();
if (frmCaNew.DialogResult == DialogResult.Cancel)
return null;
return frmCaNew.GetCab();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.m_labelWhatType = new System.Windows.Forms.Label();
this.m_comboBoxType = new System.Windows.Forms.ComboBox();
this.m_labelText = new System.Windows.Forms.Label();
this.button1 = new System.Windows.Forms.Button();
this.buttonCancel = new System.Windows.Forms.Button();
this.m_richTextBox = new System.Windows.Forms.RichTextBox();
this.m_labelDescription = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// m_labelWhatType
//
this.m_labelWhatType.Location = new System.Drawing.Point(8, 16);
this.m_labelWhatType.Name = "m_labelWhatType";
this.m_labelWhatType.Size = new System.Drawing.Size(496, 16);
this.m_labelWhatType.TabIndex = 0;
this.m_labelWhatType.Text = "&What type of $1 do you wish to create?";
//
// m_comboBoxType
//
this.m_comboBoxType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.m_comboBoxType.Location = new System.Drawing.Point(8, 40);
this.m_comboBoxType.MaxDropDownItems = 16;
this.m_comboBoxType.Name = "m_comboBoxType";
this.m_comboBoxType.Size = new System.Drawing.Size(496, 21);
this.m_comboBoxType.TabIndex = 1;
this.m_comboBoxType.SelectedIndexChanged += new System.EventHandler(this.m_comboBoxType_SelectedIndexChanged);
//
// m_labelText
//
this.m_labelText.Location = new System.Drawing.Point(8, 80);
this.m_labelText.Name = "m_labelText";
this.m_labelText.Size = new System.Drawing.Size(496, 16);
this.m_labelText.TabIndex = 2;
this.m_labelText.Text = "&$1 Text (click on underlined words to set values):";
//
// button1
//
this.button1.Location = new System.Drawing.Point(168, 328);
this.button1.Name = "button1";
this.button1.TabIndex = 4;
this.button1.Text = "Ok";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// buttonCancel
//
this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
this.buttonCancel.Location = new System.Drawing.Point(288, 328);
this.buttonCancel.Name = "buttonCancel";
this.buttonCancel.TabIndex = 4;
this.buttonCancel.Text = "Cancel";
this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click);
//
// m_richTextBox
//
this.m_richTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.m_richTextBox.Location = new System.Drawing.Point(8, 104);
this.m_richTextBox.Name = "m_richTextBox";
this.m_richTextBox.ReadOnly = true;
this.m_richTextBox.Size = new System.Drawing.Size(496, 120);
this.m_richTextBox.TabIndex = 5;
this.m_richTextBox.Text = "richTextBox1";
this.m_richTextBox.MouseDown += new System.Windows.Forms.MouseEventHandler(this.m_richTextBox_MouseDown);
//
// m_labelDescription
//
this.m_labelDescription.Dock = System.Windows.Forms.DockStyle.Fill;
this.m_labelDescription.ForeColor = System.Drawing.Color.Indigo;
this.m_labelDescription.Location = new System.Drawing.Point(3, 16);
this.m_labelDescription.Name = "m_labelDescription";
this.m_labelDescription.Size = new System.Drawing.Size(490, 61);
this.m_labelDescription.TabIndex = 7;
this.m_labelDescription.Text = "label2";
this.m_labelDescription.UseMnemonic = false;
//
// groupBox1
//
this.groupBox1.Controls.AddRange(new System.Windows.Forms.Control[] {
this.m_labelDescription});
this.groupBox1.Location = new System.Drawing.Point(8, 240);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(496, 80);
this.groupBox1.TabIndex = 8;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Description";
//
// CaNew
//
this.AcceptButton = this.button1;
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.CancelButton = this.buttonCancel;
this.ClientSize = new System.Drawing.Size(514, 360);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.groupBox1,
this.m_richTextBox,
this.button1,
this.m_labelText,
this.m_comboBoxType,
this.m_labelWhatType,
this.buttonCancel});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "CaNew";
this.ShowInTaskbar = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent;
this.Text = "CaNew";
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
void SelectCa(int n) {
if (m_cab == null || m_cab.GetType() != m_atype[n])
m_cab = (CaBase)System.Activator.CreateInstance(m_atype[n]);
m_labelDescription.Text = Helper.GetDescription(m_cab.GetType());
m_richTextBox.Clear();
// String replacement, order independent
string str = m_cab.GetString();
CaType[] acat = m_cab.GetTypes();
for (int j = 0; j < acat.Length; j++)
str = str.Replace("$" + (j + 1), "~" + j + acat[j].ToString() + "~" + j);
// Save this away for hittesting purposes
m_strParse = (string)str.Clone();
// && delimited pieces are links
while (str.Length != 0) {
int ichT = str.IndexOf("~");
if (ichT == -1) {
m_richTextBox.AppendText(str);
break;
}
if (ichT != 0)
m_richTextBox.AppendText(str.Substring(0, ichT));
str = str.Remove(0, ichT + 2);
// Now add the underlined text
int ichStart = m_richTextBox.TextLength;
int cchLink = str.IndexOf("~");
Debug.Assert(cchLink != -1);
m_richTextBox.AppendText(str.Substring(0, cchLink));
str = str.Remove(0, cchLink + 2);
m_richTextBox.Select(ichStart, cchLink);
Color clr = m_richTextBox.SelectionColor;
Font fnt = m_richTextBox.SelectionFont;
m_richTextBox.SelectionColor = Color.Blue;
m_richTextBox.SelectionFont = new Font(fnt.FontFamily, fnt.Size, /* FontStyle.Bold | */ FontStyle.Underline);
m_richTextBox.Select(m_richTextBox.TextLength, 0);
m_richTextBox.SelectionFont = fnt;
m_richTextBox.SelectionColor = clr;
}
}
private void m_comboBoxType_SelectedIndexChanged(object sender, System.EventArgs e) {
SelectCa(m_comboBoxType.SelectedIndex);
}
int GetCatIndexFromCharIndex(int ich) {
int ichTranslated = 0;
int icat = -1;
for (int ichT = 0; ichT < m_strParse.Length; ichT++) {
if (m_strParse[ichT] == '~') {
if (icat == -1) {
icat = m_strParse[ichT + 1] - '0';
} else {
icat = -1;
}
ichT++;
continue;
}
if (ich == ichTranslated)
return icat;
ichTranslated++;
}
return -1;
}
private void m_richTextBox_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) {
int ich = m_richTextBox.GetCharIndexFromPosition(new Point(e.X, e.Y));
if (ich == -1)
return;
int icat = GetCatIndexFromCharIndex(ich);
if (icat == -1)
return;
CaType[] acat = m_cab.GetTypes();
if (acat[icat].EditProperties())
SelectCa(m_comboBoxType.SelectedIndex);
}
private void button1_Click(object sender, System.EventArgs e) {
if (m_cab == null || !m_cab.IsValid()) {
MessageBox.Show(this, "Invalid " + m_strKind);
return;
}
DialogResult = DialogResult.OK;
}
private void buttonCancel_Click(object sender, System.EventArgs e) {
DialogResult = DialogResult.Cancel;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
using Thrift.Collections;
using Thrift.Protocol;
using Thrift.Transport;
using Thrift.Test;
namespace Test
{
public class TestClient
{
private static int numIterations = 1;
private static string protocol = "";
public static bool Execute(string[] args)
{
try
{
string host = "localhost";
int port = 9090;
string url = null, pipe = null;
int numThreads = 1;
bool buffered = false, framed = false, encrypted = false;
string certPath = "../../../../../keys/server.pem";
try
{
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "-u")
{
url = args[++i];
}
else if (args[i] == "-n")
{
numIterations = Convert.ToInt32(args[++i]);
}
else if (args[i] == "-pipe") // -pipe <name>
{
pipe = args[++i];
Console.WriteLine("Using named pipes transport");
}
else if (args[i].Contains("--host="))
{
host = args[i].Substring(args[i].IndexOf("=") + 1);
}
else if (args[i].Contains("--port="))
{
port = int.Parse(args[i].Substring(args[i].IndexOf("=")+1));
}
else if (args[i] == "-b" || args[i] == "--buffered" || args[i] == "--transport=buffered")
{
buffered = true;
Console.WriteLine("Using buffered sockets");
}
else if (args[i] == "-f" || args[i] == "--framed" || args[i] == "--transport=framed")
{
framed = true;
Console.WriteLine("Using framed transport");
}
else if (args[i] == "-t")
{
numThreads = Convert.ToInt32(args[++i]);
}
else if (args[i] == "--compact" || args[i] == "--protocol=compact")
{
protocol = "compact";
Console.WriteLine("Using compact protocol");
}
else if (args[i] == "--json" || args[i] == "--protocol=json")
{
protocol = "json";
Console.WriteLine("Using JSON protocol");
}
else if (args[i] == "--ssl")
{
encrypted = true;
Console.WriteLine("Using encrypted transport");
}
else if (args[i].StartsWith("--cert="))
{
certPath = args[i].Substring("--cert=".Length);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
//issue tests on separate threads simultaneously
Thread[] threads = new Thread[numThreads];
DateTime start = DateTime.Now;
for (int test = 0; test < numThreads; test++)
{
Thread t = new Thread(new ParameterizedThreadStart(ClientThread));
threads[test] = t;
if (url == null)
{
// endpoint transport
TTransport trans = null;
if (pipe != null)
trans = new TNamedPipeClientTransport(pipe);
else
{
if (encrypted)
trans = new TTLSSocket(host, port, certPath);
else
trans = new TSocket(host, port);
}
// layered transport
if (buffered)
trans = new TBufferedTransport(trans as TStreamTransport);
if (framed)
trans = new TFramedTransport(trans);
//ensure proper open/close of transport
trans.Open();
trans.Close();
t.Start(trans);
}
else
{
THttpClient http = new THttpClient(new Uri(url));
t.Start(http);
}
}
for (int test = 0; test < numThreads; test++)
{
threads[test].Join();
}
Console.Write("Total time: " + (DateTime.Now - start));
}
catch (Exception outerEx)
{
Console.WriteLine(outerEx.Message + " ST: " + outerEx.StackTrace);
return false;
}
Console.WriteLine();
Console.WriteLine();
return true;
}
public static void ClientThread(object obj)
{
TTransport transport = (TTransport)obj;
for (int i = 0; i < numIterations; i++)
{
ClientTest(transport);
}
transport.Close();
}
public static string BytesToHex(byte[] data) {
return BitConverter.ToString(data).Replace("-", string.Empty);
}
public static byte[] PrepareTestData(bool randomDist)
{
byte[] retval = new byte[0x100];
int initLen = Math.Min(0x100,retval.Length);
// linear distribution, unless random is requested
if (!randomDist) {
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)i;
}
return retval;
}
// random distribution
for (var i = 0; i < initLen; ++i) {
retval[i] = (byte)0;
}
var rnd = new Random();
for (var i = 1; i < initLen; ++i) {
while( true) {
int nextPos = rnd.Next() % initLen;
if (retval[nextPos] == 0) {
retval[nextPos] = (byte)i;
break;
}
}
}
return retval;
}
public static void ClientTest(TTransport transport)
{
TProtocol proto;
if (protocol == "compact")
proto = new TCompactProtocol(transport);
else if (protocol == "json")
proto = new TJSONProtocol(transport);
else
proto = new TBinaryProtocol(transport);
ThriftTest.Client client = new ThriftTest.Client(proto);
try
{
if (!transport.IsOpen)
{
transport.Open();
}
}
catch (TTransportException ttx)
{
Console.WriteLine("Connect failed: " + ttx.Message);
return;
}
long start = DateTime.Now.ToFileTime();
Console.Write("testVoid()");
client.testVoid();
Console.WriteLine(" = void");
Console.Write("testString(\"Test\")");
string s = client.testString("Test");
Console.WriteLine(" = \"" + s + "\"");
Console.Write("testByte(1)");
sbyte i8 = client.testByte((sbyte)1);
Console.WriteLine(" = " + i8);
Console.Write("testI32(-1)");
int i32 = client.testI32(-1);
Console.WriteLine(" = " + i32);
Console.Write("testI64(-34359738368)");
long i64 = client.testI64(-34359738368);
Console.WriteLine(" = " + i64);
Console.Write("testDouble(5.325098235)");
double dub = client.testDouble(5.325098235);
Console.WriteLine(" = " + dub);
byte[] binOut = PrepareTestData(true);
Console.Write("testBinary(" + BytesToHex(binOut) + ")");
try
{
byte[] binIn = client.testBinary(binOut);
Console.WriteLine(" = " + BytesToHex(binIn));
if (binIn.Length != binOut.Length)
throw new Exception("testBinary: length mismatch");
for (int ofs = 0; ofs < Math.Min(binIn.Length, binOut.Length); ++ofs)
if (binIn[ofs] != binOut[ofs])
throw new Exception("testBinary: content mismatch at offset " + ofs.ToString());
}
catch (Thrift.TApplicationException e)
{
Console.Write("testBinary(" + BytesToHex(binOut) + "): "+e.Message);
}
// binary equals? only with hashcode option enabled ...
if( typeof(CrazyNesting).GetMethod("Equals").DeclaringType == typeof(CrazyNesting))
{
CrazyNesting one = new CrazyNesting();
CrazyNesting two = new CrazyNesting();
one.String_field = "crazy";
two.String_field = "crazy";
one.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
two.Binary_field = new byte[10] { 0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0xFF };
if (!one.Equals(two))
throw new Exception("CrazyNesting.Equals failed");
}
Console.Write("testStruct({\"Zero\", 1, -3, -5})");
Xtruct o = new Xtruct();
o.String_thing = "Zero";
o.Byte_thing = (sbyte)1;
o.I32_thing = -3;
o.I64_thing = -5;
Xtruct i = client.testStruct(o);
Console.WriteLine(" = {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}");
Console.Write("testNest({1, {\"Zero\", 1, -3, -5}, 5})");
Xtruct2 o2 = new Xtruct2();
o2.Byte_thing = (sbyte)1;
o2.Struct_thing = o;
o2.I32_thing = 5;
Xtruct2 i2 = client.testNest(o2);
i = i2.Struct_thing;
Console.WriteLine(" = {" + i2.Byte_thing + ", {\"" + i.String_thing + "\", " + i.Byte_thing + ", " + i.I32_thing + ", " + i.I64_thing + "}, " + i2.I32_thing + "}");
Dictionary<int, int> mapout = new Dictionary<int, int>();
for (int j = 0; j < 5; j++)
{
mapout[j] = j - 10;
}
Console.Write("testMap({");
bool first = true;
foreach (int key in mapout.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapout[key]);
}
Console.Write("})");
Dictionary<int, int> mapin = client.testMap(mapout);
Console.Write(" = {");
first = true;
foreach (int key in mapin.Keys)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(key + " => " + mapin[key]);
}
Console.WriteLine("}");
List<int> listout = new List<int>();
for (int j = -2; j < 3; j++)
{
listout.Add(j);
}
Console.Write("testList({");
first = true;
foreach (int j in listout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
List<int> listin = client.testList(listout);
Console.Write(" = {");
first = true;
foreach (int j in listin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
//set
THashSet<int> setout = new THashSet<int>();
for (int j = -2; j < 3; j++)
{
setout.Add(j);
}
Console.Write("testSet({");
first = true;
foreach (int j in setout)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.Write("})");
THashSet<int> setin = client.testSet(setout);
Console.Write(" = {");
first = true;
foreach (int j in setin)
{
if (first)
{
first = false;
}
else
{
Console.Write(", ");
}
Console.Write(j);
}
Console.WriteLine("}");
Console.Write("testEnum(ONE)");
Numberz ret = client.testEnum(Numberz.ONE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(TWO)");
ret = client.testEnum(Numberz.TWO);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(THREE)");
ret = client.testEnum(Numberz.THREE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(FIVE)");
ret = client.testEnum(Numberz.FIVE);
Console.WriteLine(" = " + ret);
Console.Write("testEnum(EIGHT)");
ret = client.testEnum(Numberz.EIGHT);
Console.WriteLine(" = " + ret);
Console.Write("testTypedef(309858235082523)");
long uid = client.testTypedef(309858235082523L);
Console.WriteLine(" = " + uid);
Console.Write("testMapMap(1)");
Dictionary<int, Dictionary<int, int>> mm = client.testMapMap(1);
Console.Write(" = {");
foreach (int key in mm.Keys)
{
Console.Write(key + " => {");
Dictionary<int, int> m2 = mm[key];
foreach (int k2 in m2.Keys)
{
Console.Write(k2 + " => " + m2[k2] + ", ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
Insanity insane = new Insanity();
insane.UserMap = new Dictionary<Numberz, long>();
insane.UserMap[Numberz.FIVE] = 5000L;
Xtruct truck = new Xtruct();
truck.String_thing = "Truck";
truck.Byte_thing = (sbyte)8;
truck.I32_thing = 8;
truck.I64_thing = 8;
insane.Xtructs = new List<Xtruct>();
insane.Xtructs.Add(truck);
Console.Write("testInsanity()");
Dictionary<long, Dictionary<Numberz, Insanity>> whoa = client.testInsanity(insane);
Console.Write(" = {");
foreach (long key in whoa.Keys)
{
Dictionary<Numberz, Insanity> val = whoa[key];
Console.Write(key + " => {");
foreach (Numberz k2 in val.Keys)
{
Insanity v2 = val[k2];
Console.Write(k2 + " => {");
Dictionary<Numberz, long> userMap = v2.UserMap;
Console.Write("{");
if (userMap != null)
{
foreach (Numberz k3 in userMap.Keys)
{
Console.Write(k3 + " => " + userMap[k3] + ", ");
}
}
else
{
Console.Write("null");
}
Console.Write("}, ");
List<Xtruct> xtructs = v2.Xtructs;
Console.Write("{");
if (xtructs != null)
{
foreach (Xtruct x in xtructs)
{
Console.Write("{\"" + x.String_thing + "\", " + x.Byte_thing + ", " + x.I32_thing + ", " + x.I32_thing + "}, ");
}
}
else
{
Console.Write("null");
}
Console.Write("}");
Console.Write("}, ");
}
Console.Write("}, ");
}
Console.WriteLine("}");
sbyte arg0 = 1;
int arg1 = 2;
long arg2 = long.MaxValue;
Dictionary<short, string> multiDict = new Dictionary<short, string>();
multiDict[1] = "one";
Numberz arg4 = Numberz.FIVE;
long arg5 = 5000000;
Console.Write("Test Multi(" + arg0 + "," + arg1 + "," + arg2 + "," + multiDict + "," + arg4 + "," + arg5 + ")");
Xtruct multiResponse = client.testMulti(arg0, arg1, arg2, multiDict, arg4, arg5);
Console.Write(" = Xtruct(byte_thing:" + multiResponse.Byte_thing + ",String_thing:" + multiResponse.String_thing
+ ",i32_thing:" + multiResponse.I32_thing + ",i64_thing:" + multiResponse.I64_thing + ")\n");
Console.WriteLine("Test Oneway(1)");
client.testOneway(1);
Console.Write("Test Calltime()");
var startt = DateTime.UtcNow;
for ( int k=0; k<1000; ++k )
client.testVoid();
Console.WriteLine(" = " + (DateTime.UtcNow - startt).TotalSeconds.ToString() + " ms a testVoid() call" );
}
}
}
| |
using System;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Windows.Forms;
using PCSComMaterials.Inventory.DS;
using PCSComMaterials.Inventory.BO;
using PCSComProcurement.Purchase.DS;
using PCSComProduct.Costing.DS;
using PCSComProduct.Items.BO;
using PCSComProduct.Items.DS;
using PCSComUtils.Common;
using PCSComUtils.MasterSetup.DS;
using PCSComUtils.PCSExc;
namespace PCSComProcurement.Purchase.BO
{
public class POPurchaseOrderReceiptsBO
{
private const string THIS = "PCSComProcurement.Purchase.BO.POPurchaseOrderReceiptsBO";
public object GetObjectVO(int pintID, string VOclass)
{
// TODO:
return null;
}
public void Update(object pObjectDetail)
{
// TODO:
}
public void UpdateDataSet(DataSet dstData)
{
// try
// {
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
dsReceiptDetail.UpdateDataSet(dstData);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public int AddMasterReceipt(object pobjMasterObject, DataSet pdstDetailData, int pintCCNID, DateTime pdtmServerDate)
{
#region Variables
PO_PurchaseOrderReceiptMasterDS dsMasterReceipt = new PO_PurchaseOrderReceiptMasterDS();
PO_PurchaseOrderReceiptDetailDS dsDetail = new PO_PurchaseOrderReceiptDetailDS();
PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();
MST_TransactionHistoryDS dsTransaction = new MST_TransactionHistoryDS();
ITM_BOMDS dsBOM = new ITM_BOMDS();
PO_DeliveryScheduleDS dsSchedule = new PO_DeliveryScheduleDS();
InventoryUtilsBO boIv = new InventoryUtilsBO();
StringBuilder sbDeliveryScheduleIDs = new StringBuilder();
StringBuilder sbLocationID = new StringBuilder();
StringBuilder sbBinID = new StringBuilder();
StringBuilder sbProductID = new StringBuilder();
int intTranTypeID = new MST_TranTypeDS().GetTranTypeID(TransactionTypeEnum.POPurchaseOrderReceipts.ToString());
#endregion
#region validate data
PO_PurchaseOrderReceiptMasterVO voMasterReceipt = (PO_PurchaseOrderReceiptMasterVO)pobjMasterObject;
int intProLocationID = 0, intProBinID = 0;
DataTable dtbLocationBin = new DataTable();
if (voMasterReceipt.ProductionLineID > 0)
{
dtbLocationBin = dsDetail.GetLocationBin(voMasterReceipt.ProductionLineID);
if(dtbLocationBin.Rows.Count == 0)
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
intProLocationID = Convert.ToInt32(dtbLocationBin.Rows[0][MST_BINTable.LOCATIONID_FLD]);
intProBinID = Convert.ToInt32(dtbLocationBin.Rows[0][MST_BINTable.BINID_FLD]);
sbLocationID.Append(intProLocationID.ToString()).Append(",");
sbBinID.Append(intProBinID.ToString()).Append(",");
}
#endregion
#region receipt master & detail data
// add new Master Receipt first
voMasterReceipt.PurchaseOrderReceiptID = dsMasterReceipt.AddAndReturnID(pobjMasterObject);
string strPODetailIDs = "(";
// assign master receipt to each detail
foreach (DataRow drowData in pdstDetailData.Tables[0].Rows)
{
// ignore deleted row
if (drowData.RowState == DataRowState.Deleted)
continue;
drowData[PO_PurchaseOrderReceiptMasterTable.PURCHASEORDERRECEIPTID_FLD] = voMasterReceipt.PurchaseOrderReceiptID;
strPODetailIDs += drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERDETAILID_FLD] + ",";
sbLocationID.Append(drowData[PO_PurchaseOrderReceiptDetailTable.LOCATIONID_FLD].ToString()).Append(",");
sbBinID.Append(drowData[PO_PurchaseOrderReceiptDetailTable.BINID_FLD].ToString()).Append(",");
sbProductID.Append(drowData[PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD].ToString()).Append(",");
string strComponentID = dsBOM.GetComponentOfItem(drowData[PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD].ToString());
if (strComponentID != string.Empty)
sbProductID.Append(strComponentID);
}
if(strPODetailIDs.Length > 1)
strPODetailIDs = strPODetailIDs.Substring(0,strPODetailIDs.Length-1) + ")";
else
strPODetailIDs = string.Empty;
sbLocationID.Append("0");
sbBinID.Append("0");
sbProductID.Append("0");
// update detail dataset
dsDetail.UpdateDataSet(pdstDetailData);
#endregion
#region prepare data
// Check receipted to Close PO
dsDetail.CheckToClosePO(voMasterReceipt.PurchaseOrderMasterID,strPODetailIDs);
// refresh the detail list to get extract ID from database
DataTable dtbNewDetail = dsDetail.ListByMaster(voMasterReceipt.PurchaseOrderReceiptID);
// onhand data for transaction history
DataSet dstOnhandData = dsTransaction.RetrieveCacheData(voMasterReceipt.MasterLocationID, sbLocationID.ToString(),
sbBinID.ToString(), sbProductID.ToString());
DataTable dtbMasLocCacheData = dstOnhandData.Tables[0];
DataTable dtbLocCacheData = dstOnhandData.Tables[1];
DataTable dtbBinCacheData = dstOnhandData.Tables[2];
// get transaction history table schema
DataTable dtbTransaction = dsTransaction.GetSchema();
#endregion
#region update inventory
if ((dtbNewDetail != null) && (dtbNewDetail.Rows.Count > 0))
{
foreach (DataRow drowData in dtbNewDetail.Rows)
{
int intProductID = Convert.ToInt32(drowData[ITM_ProductTable.PRODUCTID_FLD]);
sbDeliveryScheduleIDs.Append(drowData[PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD].ToString()).Append(",");
decimal decReceiveQuantity = 0, decReceiveQuantityUMRate = 0, decUMRate = 0;
int intBinID = 0, intLocationID = 0;
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
decUMRate = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString().Trim());
decReceiveQuantityUMRate = decReceiveQuantity * decUMRate;
}
catch{}
#region Inventory
try
{
intBinID = int.Parse(drowData[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drowData[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
boIv.UpdateAddOHQuantity(pintCCNID, voMasterReceipt.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantityUMRate, string.Empty, string.Empty);
#endregion
#region Transasction History
decimal decOHQuantity = 0, decCommitQuantity = 0;
DataRow drowTransaction = dtbTransaction.NewRow();
drowTransaction[MST_TransactionHistoryTable.CCNID_FLD] = voMasterReceipt.CCNID;
drowTransaction[MST_TransactionHistoryTable.TRANSDATE_FLD] = DateTime.Now;
drowTransaction[MST_TransactionHistoryTable.POSTDATE_FLD] = voMasterReceipt.PostDate;
drowTransaction[MST_TransactionHistoryTable.REFMASTERID_FLD] = voMasterReceipt.PurchaseOrderReceiptID;
drowTransaction[MST_TransactionHistoryTable.REFDETAILID_FLD] = drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD];
drowTransaction[MST_TransactionHistoryTable.PRODUCTID_FLD] = intProductID;
drowTransaction[MST_TransactionHistoryTable.TRANTYPEID_FLD] = intTranTypeID;
drowTransaction[MST_TransactionHistoryTable.USERNAME_FLD] = voMasterReceipt.Username;
drowTransaction[MST_TransactionHistoryTable.QUANTITY_FLD] = decReceiveQuantity;
drowTransaction[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD] = voMasterReceipt.MasterLocationID;
decOHQuantity = GetQuantityFromCache(dtbMasLocCacheData, voMasterReceipt.MasterLocationID, intProductID, 1, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.LOCATIONID_FLD] = intLocationID;
decOHQuantity = GetQuantityFromCache(dtbLocCacheData, intLocationID, intProductID, 2, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.BINID_FLD] = intBinID;
decOHQuantity = GetQuantityFromCache(dtbBinCacheData, intBinID, intProductID, 3, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.BINOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.STOCKUMID_FLD] = drowData[ITM_ProductTable.STOCKUMID_FLD];
dtbTransaction.Rows.Add(drowTransaction);
#endregion
}
}
#endregion
#region Receipt by outside
if(voMasterReceipt.ReceiptType == (int)POReceiptTypeEnum.ByOutside)
{
BomBO boBom = new BomBO();
foreach (DataRow drow in dtbNewDetail.Rows)
{
DataTable dtbBom = boBom.ListBOMDetailsOfProduct(Convert.ToInt32(drow[ITM_ProductTable.PRODUCTID_FLD]));
foreach(DataRow drowBom in dtbBom.Rows)
{
#region subtract cache
// Get available quantity by Postdate
int intComponentID = Convert.ToInt32(drowBom[ITM_BOMTable.COMPONENTID_FLD]);
decimal decAvail = boIv.GetAvailableQtyByPostDate(pdtmServerDate,
voMasterReceipt.CCNID,voMasterReceipt.MasterLocationID,intProLocationID,intProBinID,
intComponentID);
decimal decBOMQty = Convert.ToDecimal(drowBom[ITM_BOMTable.QUANTITY_FLD]);
decimal decOrderQty = Convert.ToDecimal(drow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD]);
if(decAvail < decOrderQty * decBOMQty)
throw new PCSBOException(ErrorCode.MESSAGE_ISSUE_MATERIAL_TO_OUTSIDE, string.Empty, new Exception());
try
{
boIv.UpdateSubtractOHQuantity(voMasterReceipt.CCNID,voMasterReceipt.MasterLocationID,
intProLocationID,intProBinID,Convert.ToInt32(drowBom[ITM_BOMTable.COMPONENTID_FLD]),decBOMQty*decOrderQty,string.Empty,string.Empty);
}
catch (PCSBOException ex)
{
throw ex;
}
#endregion
#region Transasction History
decimal decOHQuantity = 0, decCommitQuantity = 0;
DataRow drowTransaction = dtbTransaction.NewRow();
drowTransaction[MST_TransactionHistoryTable.CCNID_FLD] = voMasterReceipt.CCNID;
drowTransaction[MST_TransactionHistoryTable.TRANSDATE_FLD] = DateTime.Now;
drowTransaction[MST_TransactionHistoryTable.POSTDATE_FLD] = voMasterReceipt.PostDate;
drowTransaction[MST_TransactionHistoryTable.REFMASTERID_FLD] = voMasterReceipt.PurchaseOrderReceiptID;
drowTransaction[MST_TransactionHistoryTable.REFDETAILID_FLD] = drow[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD];
drowTransaction[MST_TransactionHistoryTable.PRODUCTID_FLD] = intComponentID;
drowTransaction[MST_TransactionHistoryTable.TRANTYPEID_FLD] = intTranTypeID;
drowTransaction[MST_TransactionHistoryTable.USERNAME_FLD] = voMasterReceipt.Username;
drowTransaction[MST_TransactionHistoryTable.QUANTITY_FLD] = -decOrderQty * decBOMQty;
drowTransaction[MST_TransactionHistoryTable.MASTERLOCATIONID_FLD] = voMasterReceipt.MasterLocationID;
decOHQuantity = GetQuantityFromCache(dtbMasLocCacheData, voMasterReceipt.MasterLocationID, intComponentID, 1, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.MASLOCOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.MASLOCCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.LOCATIONID_FLD] = intProLocationID;
decOHQuantity = GetQuantityFromCache(dtbLocCacheData, intProLocationID, intComponentID, 2, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.LOCATIONOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.LOCATIONCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.BINID_FLD] = intProBinID;
decOHQuantity = GetQuantityFromCache(dtbBinCacheData, intProBinID, intComponentID, 3, out decCommitQuantity);
drowTransaction[MST_TransactionHistoryTable.BINOHQUANTITY_FLD] = decOHQuantity;
drowTransaction[MST_TransactionHistoryTable.BINCOMMITQUANTITY_FLD] = decCommitQuantity;
drowTransaction[MST_TransactionHistoryTable.STOCKUMID_FLD] = drowBom[ITM_ProductTable.STOCKUMID_FLD];
dtbTransaction.Rows.Add(drowTransaction);
#endregion
}
}
}
#endregion
#region Update Received Quantity for Delivery Schedule
sbDeliveryScheduleIDs.Append("0");
DataSet dstSchedule = dsSchedule.List(sbDeliveryScheduleIDs.ToString());
foreach (DataRow drowData in dstSchedule.Tables[0].Rows)
{
string strFilter = PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD + "="
+ drowData[PO_DeliveryScheduleTable.DELIVERYSCHEDULEID_FLD];
decimal decReceiveQuantity = Convert.ToDecimal(dtbNewDetail.Compute("SUM(" + PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD + ")", strFilter));
decimal decCurrentReceived = 0;
try
{
decCurrentReceived = Convert.ToDecimal(drowData[PO_DeliveryScheduleTable.RECEIVEDQUANTITY_FLD]);
}
catch{}
drowData[PO_DeliveryScheduleTable.RECEIVEDQUANTITY_FLD] = decCurrentReceived + decReceiveQuantity;
}
dsSchedule.UpdateDataSet(dstSchedule);
#endregion
#region Update Total Delivery of PO detail
DataSet dstPODetail = dsPODetail.List(strPODetailIDs);
foreach (DataRow drowData in dstPODetail.Tables[0].Rows)
{
string strFilter = PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERDETAILID_FLD + "="
+ drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD];
decimal decReceiveQuantity = Convert.ToDecimal(dtbNewDetail.Compute("SUM(" + PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD + ")", strFilter));
decimal decCurrentReceived = 0;
try
{
decCurrentReceived = Convert.ToDecimal(drowData[PO_PurchaseOrderDetailTable.TOTALDELIVERY_FLD]);
}
catch{}
drowData[PO_PurchaseOrderDetailTable.TOTALDELIVERY_FLD] = decCurrentReceived + decReceiveQuantity;
}
dsPODetail.UpdateDataSetForReceipt(dstPODetail);
#endregion
#region Close PO
// check if total delivery of PO Line >= to order quantity
// then update auto close of PO Line
foreach (DataRow drowData in pdstDetailData.Tables[0].Rows)
{
// ignore deleted row
if (drowData.RowState == DataRowState.Deleted)
continue;
// now get PO detail id of current row
int intPODetailID = int.Parse(drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString());
// get PODetail object
PO_PurchaseOrderDetailVO voPODetail = new PO_PurchaseOrderDetailVO();
voPODetail = (PO_PurchaseOrderDetailVO)dsPODetail.GetObjectVO(intPODetailID);
PO_PurchaseOrderMasterDS objPO_PurchaseOrderMasterDS = new PO_PurchaseOrderMasterDS();
// total delivery of po line
decimal decTotalDelivery = GetTotalDelivery(voPODetail.PurchaseOrderDetailID);
if (voPODetail.OrderQuantity <= decTotalDelivery)
{
// close po line first
objPO_PurchaseOrderMasterDS.ClosePurchaseOrderLine(voPODetail.PurchaseOrderDetailID);
//close the Purchase Order
objPO_PurchaseOrderMasterDS.ClosePurchaseOrder(voPODetail.PurchaseOrderMasterID);
}
}
#endregion
#region save transaction history
DataSet dstData = new DataSet();
dstData.Tables.Add(dtbTransaction);
dsTransaction.UpdateDataSet(dstData);
#endregion
return voMasterReceipt.PurchaseOrderReceiptID;
}
/// <summary>
/// Get quantity from cache table
/// </summary>
/// <param name="pdtbCacheData">Cache Table</param>
/// <param name="pintID">Cache ID</param>
/// <param name="pintProductID"></param>
/// <param name="pintType">1: Master Location | 2: Location | 3: Bin</param>
/// <param name="odecCommitQuantity">Commit Quantity</param>
/// <returns>Onhand Quantity</returns>
private decimal GetQuantityFromCache(DataTable pdtbCacheData, int pintID, int pintProductID, int pintType, out decimal odecCommitQuantity)
{
odecCommitQuantity = 0;
try
{
string strFilter = ITM_ProductTable.PRODUCTID_FLD + "=" + pintProductID;
switch(pintType)
{
case 1: // master location
strFilter += " AND " + IV_MasLocCacheTable.MASTERLOCATIONID_FLD + "=" + pintID;
break;
case 2: // location
strFilter += " AND " + IV_LocationCacheTable.LOCATIONID_FLD + "=" + pintID;
break;
default: // bin
strFilter += " AND " + IV_BinCacheTable.BINID_FLD + "=" + pintID;
break;
}
odecCommitQuantity = Convert.ToDecimal(pdtbCacheData.Select(strFilter)[0][IV_BinCacheTable.COMMITQUANTITY_FLD]);
return Convert.ToDecimal(pdtbCacheData.Select(strFilter)[0][IV_BinCacheTable.OHQUANTITY_FLD]);
}
catch (Exception ex)
{
Debug.Write(ex.ToString());
return 0;
}
}
public void UpdateMasterReceipt(object pobjMasterObject, DataSet pdstDetailData, int pintCCNID)
{
// update master receipt first
PO_PurchaseOrderReceiptMasterDS dsMasterReceipt = new PO_PurchaseOrderReceiptMasterDS();
dsMasterReceipt.Update(pobjMasterObject);
UpdateDataSet(pdstDetailData);
// update inventory
UpdateInventory(pobjMasterObject, pdstDetailData, pintCCNID);
}
public object GetReceiptMasterVO(int pintID)
{
// try
// {
PO_PurchaseOrderReceiptMasterDS dsReceiptMaster = new PO_PurchaseOrderReceiptMasterDS();
return dsReceiptMaster.GetObjectVO(pintID);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public MST_PartyVO GetCustomerInfo(int pintPartyID)
{
// try
// {
MST_PartyDS dsParty = new MST_PartyDS();
return (MST_PartyVO)dsParty.GetObjectVO(pintPartyID);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public MST_PartyLocationVO GetPartyLocation(int pintPartyID, string pstrCode)
{
// try
// {
MST_PartyLocationDS dsPartyLocation = new MST_PartyLocationDS();
return (MST_PartyLocationVO)dsPartyLocation.GetObjectVO(pintPartyID, pstrCode);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public MST_PartyLocationVO GetPartyLocation(int pintPartyLocationID)
{
// try
// {
MST_PartyLocationDS dsPartyLocation = new MST_PartyLocationDS();
return (MST_PartyLocationVO)dsPartyLocation.GetObjectVO(pintPartyLocationID);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public DataSet ListReceiptDetailByReceiptMaster(int pintReceiptMasterID)
{
// try
// {
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
MST_LocationDS dsLocation = new MST_LocationDS();
MST_BINDS dsBin = new MST_BINDS();
DataSet dstData = dsReceiptDetail.List(pintReceiptMasterID);
// now we need to fill Bin, Location and Lot if any
foreach (DataRow drowData in dstData.Tables[0].Rows)
{
int intBinID = 0;
int intLocationID = 0;
try
{
intBinID = int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.BINID_FLD].ToString().Trim());
}
catch{}
try
{
intLocationID = int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.LOCATIONID_FLD].ToString().Trim());
}
catch{}
MST_LocationVO voLocation = new MST_LocationVO();
MST_BINVO voBin = new MST_BINVO();
// if product have location then update data
if (intLocationID > 0)
{
// get Location object
voLocation = (MST_LocationVO)dsLocation.GetObjectVO(intLocationID);
// update data row
drowData[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = voLocation.Code;
drowData[MST_LocationTable.LOCATIONID_FLD] = voLocation.LocationID;
}
// if product have bin then update data
if (intBinID > 0)
{
// get bin object
voBin = (MST_BINVO)dsBin.GetObjectVO(intBinID);
// update data row
drowData[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = voBin.Code;
drowData[MST_BINTable.BINID_FLD] = voBin.BinID;
}
}
return dstData;
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public DataSet ListByPOID(int pintPOMasterID)
{
// try
// {
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
DataSet dstData = dsReceiptDetail.ListByPOID(pintPOMasterID);
// fill default Location, Bin, Lot if any
dstData = AssignDefaultInfo(dstData, false);
return dstData;
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public DataSet ListByItem(int pintProductID)
{
// try
// {
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
return dsReceiptDetail.ListByItem(pintProductID);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public object GetPOMasterVO(int pintPOMasterID)
{
PO_PurchaseOrderMasterDS dsPOMaster = new PO_PurchaseOrderMasterDS();
return dsPOMaster.GetObjectVO(pintPOMasterID);
}
/// <summary>
/// This method uses to get PO Master VO object from PO Code
/// </summary>
/// <param name="pstrPOCode">PO Number</param>
/// <returns>PO_PurchaseOrderMasterVO</returns>
public object GetPOMasterVO(string pstrPOCode)
{
PO_PurchaseOrderMasterDS dsPOMaster = new PO_PurchaseOrderMasterDS();
return dsPOMaster.GetObjectVO(pstrPOCode);
}
public object GetPODetailVO(int pintPODetailID)
{
// try
// {
PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();
return dsPODetail.GetObjectVO(pintPODetailID);
// }
// catch (PCSException ex)
// {
// throw ex;
// }
// catch (Exception ex)
// {
// throw ex;
// }
}
public object GetProductInfo(int pintProductID)
{
try
{
ITM_ProductDS dsProduct = new ITM_ProductDS();
return dsProduct.GetProductInfo(pintProductID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetUnitOfMeasureInfo(int pintID)
{
try
{
MST_UnitOfMeasureDS dsUM = new MST_UnitOfMeasureDS();
return dsUM.GetObjectVO(pintID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetMasterLocationInfo(int pintMasterLocationID)
{
try
{
MST_MasterLocationDS dsMasterLocation = new MST_MasterLocationDS();
return dsMasterLocation.GetObjectVO(pintMasterLocationID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetLocationInfo(int pintLocationID)
{
try
{
MST_LocationDS dsLocation = new MST_LocationDS();
return dsLocation.GetObjectVO(pintLocationID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public object GetBinInfo(int pintBinID)
{
try
{
MST_BINDS dsBin = new MST_BINDS();
return dsBin.GetObjectVO(pintBinID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public void UpdateInventory(object pobjMasterReceipt, DataSet pdstDetailData, int pintCCNID)
{
const string METHOD_NAME = THIS + ".UpdateInventory()";
InventoryUtilsBO boIVUtils = new InventoryUtilsBO();
if ((pdstDetailData != null) && (pdstDetailData.Tables.Count > 0))
{
PO_PurchaseOrderReceiptMasterVO voMasterReceipt = (PO_PurchaseOrderReceiptMasterVO)pobjMasterReceipt;
PO_PurchaseOrderDetailVO voPODetail = new PO_PurchaseOrderDetailVO();
PO_DeliveryScheduleVO voSchedule = new PO_DeliveryScheduleVO();
PO_PurchaseOrderDetailDS dsPODetail = new PO_PurchaseOrderDetailDS();
PO_DeliveryScheduleDS dsSchedule = new PO_DeliveryScheduleDS();
foreach (DataRow drowData in pdstDetailData.Tables[0].Rows)
{
int intProductID = int.Parse(drowData[ITM_ProductTable.PRODUCTID_FLD].ToString().Trim());
int intDeliveryScheduleID = int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD].ToString().Trim());
string strLot = drowData[PO_PurchaseOrderReceiptDetailTable.LOT_FLD].ToString().Trim();
string strSerial = drowData[PO_PurchaseOrderReceiptDetailTable.SERIAL_FLD].ToString().Trim();
// PurchaseOrderDetail
voPODetail = (PO_PurchaseOrderDetailVO)dsPODetail.GetObjectVO(int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERDETAILID_FLD].ToString().Trim()));
decimal decReceiveQuantity = 0;
decimal decReceiveQuantityUMRate = 0;
decimal decUMRate = 0;
int intBinID = 0;
int intLocationID = 0;
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
decUMRate = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString().Trim());
decReceiveQuantityUMRate = decReceiveQuantity * decUMRate;
}
catch{}
#region Inventory
try
{
intBinID = int.Parse(drowData[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drowData[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, METHOD_NAME, new Exception());
}
boIVUtils.UpdateAddOHQuantity(pintCCNID, voMasterReceipt.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantityUMRate, strLot, strSerial);
#endregion
// update the delivery schedule
voSchedule = (PO_DeliveryScheduleVO)dsSchedule.GetObjectVO(intDeliveryScheduleID);
// update received quantity without UM rate
voSchedule.ReceivedQuantity += decReceiveQuantity;
// update schedule
dsSchedule.Update(voSchedule);
// get current total delivery of PO Detail
decimal decTotalDelivery = dsPODetail.GetTotalDelivery(voPODetail.PurchaseOrderDetailID);
// update total delivery of PO Detail
dsPODetail.UpdateTotalDelivery(decReceiveQuantity + decTotalDelivery, voPODetail.PurchaseOrderDetailID);
}
}
}
public decimal GetTotalDelivery(int pintPODetailID)
{
try
{
PO_PurchaseOrderDetailDS dsDetail = new PO_PurchaseOrderDetailDS();
return dsDetail.GetTotalDelivery(pintPODetailID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// GetTotalReceiptQuantity
/// </summary>
/// <param name="pintDeliveryScheduleID"></param>
/// <returns></returns>
/// <author>Trada</author>
/// <date>Saturday, June 10 2006</date>
public decimal GetTotalReceiptQuantity(int pintDeliveryScheduleID)
{
PO_PurchaseOrderReceiptDetailDS dsDetail = new PO_PurchaseOrderReceiptDetailDS();
return dsDetail.GetTotalReceiptQuantityByDeliveryScheduleID(pintDeliveryScheduleID);
}
public decimal GetTotalReceiveQuantity(int pintPODetailID)
{
try
{
PO_PurchaseOrderReceiptDetailDS dsDetail = new PO_PurchaseOrderReceiptDetailDS();
return dsDetail.GetTotalReceiveQuantity(pintPODetailID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public bool IsReceived(int pintPODetailID)
{
try
{
PO_PurchaseOrderReceiptDetailDS dsDetail = new PO_PurchaseOrderReceiptDetailDS();
return dsDetail.IsReceived(pintPODetailID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
public decimal GetUMRate(int pintInUMID, int pintOutUMID)
{
try
{
MST_UMRateDS dsUMRate = new MST_UMRateDS();
return dsUMRate.GetUMRate(pintInUMID, pintOutUMID);
}
catch (PCSException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// List receipt detail by PO code
/// </summary>
/// <param name="pstrPOCode">PO Code</param>
/// <param name="pdtmSlipDate">The schedule date</param>
/// <returns>Receipt Details</returns>
public DataSet ListByPOCode(string pstrPOCode, DateTime pdtmSlipDate)
{
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
DataSet dstData = dsReceiptDetail.ListByPOCode(pstrPOCode, pdtmSlipDate);
/// assign default value of Location, Bin and Lot if any
dstData = AssignDefaultInfo(dstData, true);
return dstData;
}
/// <summary>
/// List receipt detail by Invoice
/// </summary>
/// <param name="pInvoiceMasterID">Invoice Master ID</param>
/// <returns>Receipt Detail</returns>
public DataSet ListByInvoice(int pInvoiceMasterID)
{
PO_PurchaseOrderReceiptDetailDS dsReceiptDetail = new PO_PurchaseOrderReceiptDetailDS();
DataSet dstData = dsReceiptDetail.ListByInvoice(pInvoiceMasterID);
/// assign default value of Location, Bin and Lot if any
dstData = AssignDefaultInfo(dstData, true);
return dstData;
}
/// <summary>
/// Assign default Location, Bin and Lot if any
/// </summary>
/// <param name="pdstData">Data to assign</param>
/// <param name="pblnByInvoice">Receipt by invoice or not</param>
/// <returns>Assigned Data</returns>
private DataSet AssignDefaultInfo(DataSet pdstData, bool pblnByInvoice)
{
ITM_ProductDS dsProduct = new ITM_ProductDS();
MST_LocationDS dsLocation = new MST_LocationDS();
MST_BINDS dsBin = new MST_BINDS();
PO_DeliveryScheduleDS dsSchedule = new PO_DeliveryScheduleDS();
// now we need to fill Bin, Location and Lot if any
foreach (DataRow drowData in pdstData.Tables[0].Rows)
{
// get product information
ITM_ProductVO voProduct = new ITM_ProductVO();
MST_LocationVO voLocation = new MST_LocationVO();
MST_BINVO voBin = new MST_BINVO();
PO_DeliveryScheduleVO voSchedule = new PO_DeliveryScheduleVO();
int intDeliveryScheduleID = 0;
try
{
intDeliveryScheduleID = int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD].ToString().Trim());
}
catch{}
voProduct = (ITM_ProductVO)dsProduct.GetObjectVO(int.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.PRODUCTID_FLD].ToString().Trim()));
// if product have location then update data
if (voProduct.LocationID > 0)
{
// get Location object
voLocation = (MST_LocationVO)dsLocation.GetObjectVO(voProduct.LocationID);
// update data row
drowData[MST_LocationTable.TABLE_NAME + MST_LocationTable.CODE_FLD] = voLocation.Code;
drowData[MST_LocationTable.LOCATIONID_FLD] = voLocation.LocationID;
}
// if product have bin then update data
if (voProduct.BinID > 0)
{
// get bin object
voBin = (MST_BINVO)dsBin.GetObjectVO(voProduct.BinID);
// update data row
drowData[MST_BINTable.TABLE_NAME + MST_BINTable.CODE_FLD] = voBin.Code;
drowData[MST_BINTable.BINID_FLD] = voBin.BinID;
}
// we need to get remain quantity from delivery schedule
voSchedule = (PO_DeliveryScheduleVO)dsSchedule.GetObjectVO(intDeliveryScheduleID);
if (!pblnByInvoice)
drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = voSchedule.DeliveryQuantity - voSchedule.ReceivedQuantity;
#region // HACK: DEL dungla 10-28-2005
// //get the total receive quantity
// decimal dcmToTalReceiveQty = GetTotalReceiveQuantity(int.Parse(drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString()));
// //get the total delivery schedule
// decimal decTotalOrderQty = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString()) ;// GetTotalDelivery(int.Parse(drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD].ToString()));
//
// //get the remain quantity
// if (decTotalOrderQty - dcmToTalReceiveQty > 0)
// {
// drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = decTotalOrderQty - dcmToTalReceiveQty;
// }
// else
// {
// drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD] = 0;
// }
#endregion // END: DEL dungla 10-28-2005
}
return pdstData;
}
/// <summary>
/// Save transaction history
/// </summary>
public void SaveTransaction(object pobjReceiptMaster)
{
MST_TransactionHistoryDS dsTransactionHistory = new MST_TransactionHistoryDS();
dsTransactionHistory.Add(pobjReceiptMaster);
}
/// <summary>
/// Get onhand quantity from master location
/// </summary>
/// <param name="pintProductID">Product</param>
/// <param name="pintCCNID">CCN</param>
/// <param name="pintMasterLocationID">Master Location</param>
/// <returns>OnHand quantity</returns>
public decimal GetOnHandQty(int pintProductID, int pintCCNID, int pintMasterLocationID)
{
IV_MasLocCacheDS dsMasLoc = new IV_MasLocCacheDS();
return dsMasLoc.GetOnHanQty(pintProductID, pintCCNID, pintMasterLocationID);
}
/// <summary>
/// Get Avegrate cost of product in master location
/// </summary>
/// <param name="pintProductID">Product</param>
/// <param name="pintCCNID">CCN</param>
/// <param name="pintMasterLocationID">Master LocationID</param>
/// <returns>Avg Cost</returns>
public decimal GetAvgCost(int pintProductID, int pintCCNID, int pintMasterLocationID)
{
IV_MasLocCacheDS dsMasLoc = new IV_MasLocCacheDS();
return dsMasLoc.GetAvgCost(pintProductID, pintCCNID, pintMasterLocationID);
}
/// <summary>
///
/// </summary>
/// <param name="pintProductionLineID"></param>
/// <returns>Avg Cost</returns>
public DataTable GetLocationBin(int pintProductionLineID)
{
PO_PurchaseOrderReceiptDetailDS dsPO = new PO_PurchaseOrderReceiptDetailDS();
return dsPO.GetLocationBin(pintProductionLineID);
}
/// <summary>
/// Assign common value for transaction history object
/// </summary>
/// <param name="pobjTransactionHistory">Transaction history object</param>
/// <returns>New TransactionHistory object</returns>
public object AssignCommonValue(object pobjTransactionHistory)
{
MST_TransactionHistoryVO voTransHis = (MST_TransactionHistoryVO)pobjTransactionHistory;
// assign username
voTransHis.Username = SystemProperty.UserName;
//1. MasLocOHQuantity
if(voTransHis.Lot != null)
{
voTransHis.MasLocOHQuantity = (new IV_MasLocCacheDS()).GetQuantityOnHandByLot(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.ProductID, voTransHis.Lot);
voTransHis.MasLocCommitQuantity = (new IV_MasLocCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.Lot, voTransHis.ProductID);
}
else
{
voTransHis.MasLocOHQuantity = (new IV_MasLocCacheDS()).GetQuantityOnHand(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.ProductID);
voTransHis.MasLocCommitQuantity = (new IV_MasLocCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.ProductID);
}
// 2. LocationOHQuantity
// If MST_TransactionHistoryVO.LocationID > 0
// - If MST_TransactionHistoryVO.Lot != null: MST_TransactionHistoryVO.LocationOHQuantity = IV_LocationCacheDS.GetQuantityOnHandByLot(MST_TransactionHistoryVO.CCNID, MST_TransactionHistoryVO.MasterLocationID, MST_TransactionHistoryVO.LocationID, MST_TransactionHistoryVO.ProductID, MST_TransactionHistoryVO.Lot)
// - Else MST_TransactionHistoryVO.LocationOHQuantity = IV_LocationCacheDS.GetQuantityOnHand(MST_TransactionHistoryVO.CCNID, MST_TransactionHistoryVO.MasterLocationID, MST_TransactionHistoryVO.LocationID, MST_TransactionHistoryVO.ProductID)
if(voTransHis.LocationID > 0 )
{
if(voTransHis.Lot != null)
{
voTransHis.LocationOHQuantity = (new IV_LocationCacheDS()).GetQuantityOnHandByLot(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.ProductID, voTransHis.Lot);
voTransHis.LocationCommitQuantity = (new IV_LocationCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.Lot, voTransHis.ProductID);
}
else
{
voTransHis.LocationOHQuantity = (new IV_LocationCacheDS()).GetQuantityOnHand(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.ProductID);
voTransHis.LocationCommitQuantity = (new IV_LocationCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.ProductID);
}
}
// 3. BinOHQuantity
// If MST_TransactionHistoryVO.BinID > 0
// - If MST_TransactionHistoryVO.Lot != null: MST_TransactionHistoryVO.BinOHQuantity = IV_BinCacheDS.GetQuantityOnHandByLot(MST_TransactionHistoryVO.CCNID, MST_TransactionHistoryVO.MasterLocationID, MST_TransactionHistoryVO.LocationID, MST_TransactionHistoryVO.BinID, MST_TransactionHistoryVO.ProductID, MST_TransactionHistoryVO.Lot)
// - Else MST_TransactionHistoryVO.BinOHQuantity = IV_BinCacheDS.GetQuantityOnHand(MST_TransactionHistoryVO.CCNID, MST_TransactionHistoryVO.MasterLocationID, MST_TransactionHistoryVO.BinID, MST_TransactionHistoryVO.LocationID, MST_TransactionHistoryVO.ProductID)
if(voTransHis.BinID > 0 )
{
if(voTransHis.Lot != null)
{
voTransHis.BinOHQuantity = (new IV_BinCacheDS()).GetQuantityOnHandByLot(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.BinID, voTransHis.ProductID, voTransHis.Lot);
voTransHis.BinCommitQuantity = (new IV_BinCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.BinID, voTransHis.Lot, voTransHis.ProductID);
}
else
{
voTransHis.BinOHQuantity = (new IV_BinCacheDS()).GetQuantityOnHand(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.BinID, voTransHis.ProductID);
voTransHis.BinCommitQuantity = (new IV_BinCacheDS()).GetCommitQuantity(voTransHis.CCNID, voTransHis.MasterLocationID, voTransHis.LocationID, voTransHis.BinID, voTransHis.ProductID);
}
}
MST_TranTypeDS dsTransType = new MST_TranTypeDS();
voTransHis.TranTypeID = dsTransType.GetIDFromCode(TransactionTypeEnum.POPurchaseOrderReceipts.ToString());
//Reassign TransactionHistory
return voTransHis;
}
/// <summary>
///
/// </summary>
/// <param name="pintPOReceiptMasterID"></param>
/// <returns></returns>
public DataTable GetPOReceiptMaster(int pintPOReceiptMasterID)
{
PO_PurchaseOrderReceiptMasterDS dsPOMaster = new PO_PurchaseOrderReceiptMasterDS();
return dsPOMaster.GetPOReceiptMaster(pintPOReceiptMasterID);
}
/// <summary>
/// Gets invoice master infor
/// </summary>
/// <param name="pintInvoiceMasterID"></param>
/// <returns></returns>
public object GetInvoiceInfo(int pintInvoiceMasterID)
{
PO_InvoiceMasterDS dsInvoice = new PO_InvoiceMasterDS();
return dsInvoice.GetObjectVO(pintInvoiceMasterID);
}
/// <summary>
/// Delete Purchase Order Receipt
/// </summary>
/// <param name="printPurchaseOrderReceiptId"></param>
/// <returns></returns>
public void DeletePOReceipt(int printPurchaseOrderReceiptId)
{
//0. Variables
int constInspStatus = 11;
MST_TranTypeDS dsTranType = new MST_TranTypeDS();
int intOldTranTypeID = dsTranType.GetTranTypeID(TransactionTypeEnum.POPurchaseOrderReceipts.ToString());
int intNewTranTypeID = dsTranType.GetTranTypeID(TransactionTypeEnum.DeleteTransaction.ToString());
//1. Get info Purchase Order Receipt
PO_PurchaseOrderReceiptMasterDS objPOReceiptMasterDS = new PO_PurchaseOrderReceiptMasterDS();
PO_PurchaseOrderReceiptMasterVO voPurchaseOrderMaster = new PO_PurchaseOrderReceiptMasterVO();
voPurchaseOrderMaster = (PO_PurchaseOrderReceiptMasterVO) objPOReceiptMasterDS.GetObjectVO(printPurchaseOrderReceiptId);
//2. Get info detail to Dataset
PO_PurchaseOrderReceiptDetailDS objPOReceiptDetailDS = new PO_PurchaseOrderReceiptDetailDS();
DataSet dstData = objPOReceiptDetailDS.List(printPurchaseOrderReceiptId);
InventoryUtilsBO objInventoryBO = new InventoryUtilsBO();
MST_TransactionHistoryDS objTransactionHistoryDS = new MST_TransactionHistoryDS();
//3. Subtract and Update Inventory and TransactionHistory
switch(voPurchaseOrderMaster.ReceiptType)
{
case (int)POReceiptTypeEnum.ByDeliverySlip:
#region 3.1 Update TransactionHistory Inventory ByDeliverySlip
foreach (DataRow drowData in dstData.Tables[0].Rows)
{
//3.1.1 subtract Inventory
int intProductID = Convert.ToInt32(drowData[ITM_ProductTable.PRODUCTID_FLD]);
decimal decReceiveQuantity = 0, decReceiveQuantityUMRate = 0, decUMRate = 0;
int intBinID = 0, intLocationID = 0;
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
decUMRate = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString().Trim());
decReceiveQuantityUMRate = decReceiveQuantity * decUMRate;
}
catch{}
try
{
intBinID = int.Parse(drowData[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drowData[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantityUMRate, string.Empty, string.Empty);
//3.1.2 Update TransactionHistory
// int RefPurchaseMaster = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTID_FLD];
// int RefPurchaseDetail = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD];
// objTransactionHistoryDS.UpdateTranType(RefPurchaseMaster,RefPurchaseDetail,constTranTypeID,constInspStatus);
}
break;
#endregion
case (int)POReceiptTypeEnum.ByInvoice:
#region 3.2 Update TransactionHistory Inventory ByInvoice
foreach (DataRow drowData in dstData.Tables[0].Rows)
{
//3.1.1 subtract Inventory
int intProductID = Convert.ToInt32(drowData[ITM_ProductTable.PRODUCTID_FLD]);
decimal decReceiveQuantity = 0, decReceiveQuantityUMRate = 0, decUMRate = 0;
int intBinID = 0, intLocationID = 0;
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
decUMRate = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString().Trim());
decReceiveQuantityUMRate = decReceiveQuantity * decUMRate;
}
catch{}
try
{
intBinID = int.Parse(drowData[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drowData[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantityUMRate, string.Empty, string.Empty);
//3.1.2 Update TransactionHistory
// int RefPurchaseMaster = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTID_FLD];
// int RefPurchaseDetail = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD];
// objTransactionHistoryDS.UpdateTranType(RefPurchaseMaster,RefPurchaseDetail,constTranTypeID,constInspStatus);
}
break;
#endregion
case (int)POReceiptTypeEnum.ByOutside:
#region 3.3 Update TransactionHistory Inventory ByOutside
DataTable dtLocbin = objPOReceiptDetailDS.GetLocationBin(voPurchaseOrderMaster.ProductionLineID);
if(dtLocbin.Rows.Count == 0)
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
int intProLocationID = Convert.ToInt32(dtLocbin.Rows[0][MST_BINTable.LOCATIONID_FLD]);
int intProBinID = Convert.ToInt32(dtLocbin.Rows[0][MST_BINTable.BINID_FLD]);
foreach (DataRow drowData in dstData.Tables[0].Rows)
{
#region 3.3.1 get info from PO Receipt details
int intProductID = Convert.ToInt32(drowData[ITM_ProductTable.PRODUCTID_FLD]);
decimal decReceiveQuantity = 0, decReceiveQuantityUMRate = 0, decUMRate = 0;
int intBinID = 0, intLocationID = 0;
try
{
decReceiveQuantity = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
decUMRate = decimal.Parse(drowData[PO_PurchaseOrderReceiptDetailTable.UMRATE_FLD].ToString().Trim());
decReceiveQuantityUMRate = decReceiveQuantity * decUMRate;
}
catch{}
try
{
intBinID = int.Parse(drowData[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drowData[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
#endregion
#region 3.3.2 Add Inventory by Bom
BomBO boBom = new BomBO();
DataTable dtbBom = boBom.ListBOMDetailsOfProduct(intProductID);
foreach(DataRow drowBom in dtbBom.Rows)
{
#region subtract cache
// Get available quantity by Postdate
int intComponentID = Convert.ToInt32(drowBom[ITM_BOMTable.COMPONENTID_FLD]);
decimal decBOMQty = Convert.ToDecimal(drowBom[ITM_BOMTable.QUANTITY_FLD]);
objInventoryBO.UpdateAddOHQuantity(voPurchaseOrderMaster.CCNID,voPurchaseOrderMaster.MasterLocationID,
intProLocationID,intProBinID,intComponentID,decBOMQty*decReceiveQuantity,string.Empty,string.Empty);
#endregion
}
#endregion
//3.3.3 subtract Inventory by Purchase Order Receipt
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantityUMRate, string.Empty, string.Empty);
//3.3.4 Update TransactionHistory
// int RefPurchaseMasterBom = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTID_FLD];
// int RefPurchaseDetailBom = (int)drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERRECEIPTDETAILID_FLD];
// objTransactionHistoryDS.UpdateTranType(RefPurchaseMasterBom,RefPurchaseDetailBom,constTranTypeID,constInspStatus);
}
break;
#endregion
}
//4. Delete Rows in PO_PurchaseOrderReceiptDetail
objPOReceiptDetailDS.Delete(voPurchaseOrderMaster.PurchaseOrderReceiptID);
//5. Delete Row in PO_PurchaseOrderReceiptMaster
objPOReceiptMasterDS.Delete(voPurchaseOrderMaster.PurchaseOrderReceiptID);
//6. UnClose Purchase Order details
string strPODetailIDs = "(";
PO_PurchaseOrderMasterDS objPurchaseOrderMasterDS = new PO_PurchaseOrderMasterDS();
foreach (DataRow drowData in dstData.Tables[0].Rows)
{
// close po line first
objPurchaseOrderMasterDS.OpenPurchaseOrderLine((int) drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD]);
strPODetailIDs += drowData[PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERDETAILID_FLD] + ",";
}
if(strPODetailIDs.Length > 1)
strPODetailIDs = strPODetailIDs.Substring(0,strPODetailIDs.Length-1) + ")";
else
strPODetailIDs = string.Empty;
//7. Update PO_DeliverySchedule
#region Update Total Delivery of PO detail
PO_PurchaseOrderDetailDS objPODetailDS = new PO_PurchaseOrderDetailDS();
DataSet dstPODetail = objPODetailDS.List(strPODetailIDs);
//DataTable dtbNewDetail = objPOReceiptDetailDS.ListByMaster(voPurchaseOrderMaster.PurchaseOrderReceiptID);
foreach (DataRow drowData in dstPODetail.Tables[0].Rows)
{
string strFilter = PO_PurchaseOrderReceiptDetailTable.PURCHASEORDERDETAILID_FLD + "="
+ drowData[PO_PurchaseOrderDetailTable.PURCHASEORDERDETAILID_FLD];
decimal decReceiveQuantity = Convert.ToDecimal(dstData.Tables[0].Compute("SUM(" + PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD + ")", strFilter));
decimal decCurrentReceived = 0;
try
{
decCurrentReceived = Convert.ToDecimal(drowData[PO_PurchaseOrderDetailTable.TOTALDELIVERY_FLD]);
}
catch{}
drowData[PO_PurchaseOrderDetailTable.TOTALDELIVERY_FLD] = decCurrentReceived - decReceiveQuantity;
}
objPODetailDS.UpdateDataSetForReceipt(dstPODetail);
// Update DeliverySchedule
PO_DeliveryScheduleDS objPODeliveryScheduleDS = new PO_DeliveryScheduleDS();
foreach (DataRow drow in dstData.Tables[0].Rows)
{
decimal decQuantityReceipt = (decimal) drow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD];
int printDeliveryScheduleID = (int) drow[PO_PurchaseOrderReceiptDetailTable.DELIVERYSCHEDULEID_FLD];
objPODeliveryScheduleDS.UpdateSubstractQuantityReceipt(printDeliveryScheduleID,decQuantityReceipt);
}
#endregion
// Update TransactionHistory
objTransactionHistoryDS.UpdateTranType(voPurchaseOrderMaster.PurchaseOrderReceiptID,
intOldTranTypeID, intNewTranTypeID, constInspStatus);
}
/// <summary>
/// DeleteRowPOReceipt
/// </summary>
/// <param name="printPOReceiptMasterID","printPOReceiptDetailID"></param>
/// <returns></returns>
public void DeleteRowPOReceipt(int printPOReceiptMasterID, int printPOReceiptDetailID)
{
//1. Variable
PO_PurchaseOrderReceiptDetailDS objPORDetailDS = new PO_PurchaseOrderReceiptDetailDS();
int constInspStatus = 11;
MST_TranTypeDS dsTranType = new MST_TranTypeDS();
int intOldTranTypeID = dsTranType.GetTranTypeID(TransactionTypeEnum.POPurchaseOrderReceipts.ToString());
int intNewTranTypeID = dsTranType.GetTranTypeID(TransactionTypeEnum.DeleteTransaction.ToString());
PO_PurchaseOrderReceiptMasterDS objPOReceiptMasterDS = new PO_PurchaseOrderReceiptMasterDS();
PO_PurchaseOrderReceiptMasterVO voPurchaseOrderMaster = new PO_PurchaseOrderReceiptMasterVO();
InventoryUtilsBO objInventoryBO = new InventoryUtilsBO();
//2. Get Master Infomation
voPurchaseOrderMaster = (PO_PurchaseOrderReceiptMasterVO) objPOReceiptMasterDS.GetObjectVO(printPOReceiptMasterID);
//3. Get info row detail to DataRow
PO_PurchaseOrderReceiptDetailDS objPOReceiptDetailDS = new PO_PurchaseOrderReceiptDetailDS();
DataRow drDataRow = objPOReceiptDetailDS.GetRow(printPOReceiptMasterID,printPOReceiptDetailID);
int intProductID = Convert.ToInt32(drDataRow[ITM_ProductTable.PRODUCTID_FLD]);
decimal decReceiveQuantity = 0;
int intBinID = 0, intLocationID = 0;
//4. Update Inventory
switch(voPurchaseOrderMaster.ReceiptType)
{
case (int)POReceiptTypeEnum.ByDeliverySlip:
#region 3.1 Update TransactionHistory Inventory ByDeliverySlip
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drDataRow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
}
catch{}
try
{
intBinID = int.Parse(drDataRow[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drDataRow[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantity, string.Empty, string.Empty);
break;
#endregion
case (int)POReceiptTypeEnum.ByInvoice:
#region 3.2 Update TransactionHistory Inventory ByInvoice
// get ReceiveQuantity from PO Receipt
try
{
decReceiveQuantity = decimal.Parse(drDataRow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
}
catch{}
try
{
intBinID = int.Parse(drDataRow[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drDataRow[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantity, string.Empty, string.Empty);
break;
#endregion
case (int)POReceiptTypeEnum.ByOutside:
#region 3.3 Update TransactionHistory Inventory ByOutside
DataTable dtLocbin = objPOReceiptDetailDS.GetLocationBin(voPurchaseOrderMaster.ProductionLineID);
if(dtLocbin.Rows.Count == 0)
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
int intProLocationID = Convert.ToInt32(dtLocbin.Rows[0][MST_BINTable.LOCATIONID_FLD]);
int intProBinID = Convert.ToInt32(dtLocbin.Rows[0][MST_BINTable.BINID_FLD]);
#region 3.3.1 get info from PO Receipt details
try
{
decReceiveQuantity = decimal.Parse(drDataRow[PO_PurchaseOrderReceiptDetailTable.RECEIVEQUANTITY_FLD].ToString().Trim());
}
catch{}
try
{
intBinID = int.Parse(drDataRow[MST_BINTable.BINID_FLD].ToString());
}
catch{}
try
{
intLocationID = int.Parse(drDataRow[MST_LocationTable.LOCATIONID_FLD].ToString().Trim());
}
catch
{
throw new PCSBOException(ErrorCode.MESSAGE_MUST_SELECT_LOCATION, string.Empty, new Exception());
}
#endregion
#region 3.3.2 Add Inventory by Bom
BomBO boBom = new BomBO();
DataTable dtbBom = boBom.ListBOMDetailsOfProduct(intProductID);
foreach(DataRow drowBom in dtbBom.Rows)
{
#region subtract cache
// Get available quantity by Postdate
int intComponentID = Convert.ToInt32(drowBom[ITM_BOMTable.COMPONENTID_FLD]);
decimal decBOMQty = Convert.ToDecimal(drowBom[ITM_BOMTable.QUANTITY_FLD]);
objInventoryBO.UpdateAddOHQuantity(voPurchaseOrderMaster.CCNID,voPurchaseOrderMaster.MasterLocationID,
intProLocationID,intProBinID,intComponentID,decBOMQty*decReceiveQuantity,string.Empty,string.Empty);
#endregion
}
#endregion
//3.3.3 subtract Inventory by Purchase Order Receipt
objInventoryBO.UpdateSubtractOHQuantity(voPurchaseOrderMaster.CCNID, voPurchaseOrderMaster.MasterLocationID, intLocationID, intBinID, intProductID, decReceiveQuantity, string.Empty, string.Empty);
break;
#endregion
}
//3. Update TransactionHistory
objPORDetailDS.UpdateTranType(printPOReceiptMasterID,printPOReceiptDetailID,intOldTranTypeID,intNewTranTypeID,constInspStatus);
//4. Delete row in PurchaseOrderReceipt Detail (One row)
objPORDetailDS.DeleteRowDetail(printPOReceiptMasterID,printPOReceiptDetailID);
}
public string CheckReturn(PO_PurchaseOrderReceiptMasterVO pvoReceiptMaster, string pstrProductID, bool pblnByInvoice)
{
PO_PurchaseOrderReceiptMasterDS dsReceiptMaster = new PO_PurchaseOrderReceiptMasterDS();
return dsReceiptMaster.CheckReturn(pvoReceiptMaster, pstrProductID, pblnByInvoice);
}
}
}
| |
using System;
using System.IO;
using QED.Business;
using QED.Util;
using QED.Net;
using QED.SEC;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using System.Collections;
using JCSLA;
namespace QED.Business.CodePromotion {
public enum RollType{
Remote_UAT, Local_UAT, Prod_Prep, Prod, Merge, General
}
public abstract class Roller {
RollType _rollType;
Thread _rollThread;
DateTime _dateTimeStarted ;
RolloutLog _log; // = new RolloutLog();
protected string ps = "\\";
protected string n = System.Environment.NewLine;
public delegate void ReportHandler(Roller roller, ReportEventArgs reportEventArgs);
public ReportHandler OnReport;
public delegate void PromptHandler(Roller roller, EventArgs EventArgs);
public PromptHandler OnPrompt;
public delegate void CompletedHandler(Roller roller, ReportEventArgs reportEventArgs);
public CompletedHandler OnCompleted;
private void LogRollEntry(string msg){
_log.Append(msg);
_log.UserEmail = System.Threading.Thread.CurrentPrincipal.Identity.Name;
_log.RollClass = this.GetType().Name;
_log.RollType = this.RollType;
_log.Update();
}
#region Report Helper Methods
protected void Report(object obj){
string msg = obj.ToString();
LogRollEntry(msg);
OnReport(this, new ReportEventArgs(msg));
}
protected void Report(string msg){
LogRollEntry(msg);
OnReport(this, new ReportEventArgs(msg));
}
protected void ReportCopy(FileSystemInfo from, FileSystemInfo to){
Report("Copying " + from.FullName + " to " + to.FullName);
}
protected void ReportCopy(DirectoryInfo dir){
Report("Deleting " + dir.FullName);
}
protected void ReportAndCopy(DirectoryInfo from, DirectoryInfo to, bool force){
ReportCopy(from, to);
IO.Copy(from, to, force);
}
protected void ReportAndCopy(FileInfo from, FileInfo to, bool force){
ReportCopy(from, to);
from.CopyTo(to.FullName, force);
}
protected void ReportAndZip(DirectoryInfo from, FileInfo to, bool force){
Report("Zipping " + from.FullName + " to " + to.FullName);
IO.Zip(from, to, force);
}
protected void ReportAndDelete(FileSystemInfo fsi){
Report("Delete " + fsi.FullName);
this.DeleteFileIfExists(fsi);
}
protected void ReportAndEmptyDir(DirectoryInfo dir){
Report("Empty Working Directory: " + dir.FullName);
this.EmptyWorkingDir(dir);
}
protected void ReportAndCheckoutCVS(string CVSUser,
string CVSServer, string CVSPath,
string CVSModule, DirectoryInfo CVSExportRoot, string branch, bool report){
ShellCmd cmd;
if (report) Report("Exporting CVS files");
cmd = new ShellCmd(CVS,
" -d :pserver:" + CVSUser + "@cvs.:" + CVSPath + " checkout -r " + branch + " " + CVSModule , CVSExportRoot, false);
if (report) Report(cmd.ToString() + " --(This may take a minute.)");
cmd.Run();
cmd.WaitForCommandToFinish();
}
protected bool ReportAndLoginToCVS(string CVSUser, string CVSPass, string CVSServer, string CVSPath){
ShellCmd cmd;
Report("Login to CVS");
cmd = new ShellCmd(CVS,
" -d :pserver:" + CVSUser + "@cvs.:" + CVSPath + " login", true);
cmd.Stdin.WriteLine(CVSPass);
cmd.WaitForCommandToFinish();
Report(cmd.ToString());
cmd.WaitForCommandToFinish();
return true;
}
#endregion
protected void DeleteFileIfExists(FileSystemInfo file) {
if (file.Exists){
Report("Deleting " + file.FullName);
if (file is DirectoryInfo)
((DirectoryInfo)file).Delete(true);
else
file.Delete();
}
}
protected void ReportAndCopy(FileSystemInfo src, FileSystemInfo dest, bool force){
if (src is FileInfo){
FileInfo srcFile = (FileInfo) src;
if (dest is DirectoryInfo){
DirectoryInfo destDir = (DirectoryInfo) dest;
ReportAndCopy(srcFile, destDir, true);
}else if (dest is FileInfo){
FileInfo destFile = (FileInfo) dest;
ReportAndCopy(srcFile, destFile, true);
}
}else if (src is DirectoryInfo){
DirectoryInfo srcDir = (DirectoryInfo) src;
if (dest is DirectoryInfo){
DirectoryInfo destDir = (DirectoryInfo) dest;
ReportAndCopy(srcDir, destDir, true);
}else if (dest is FileInfo){
throw new Exception("Can't copy a directory to a file");
}
}
}
protected DialogResult AskYesNotDefNo(string msg){
DialogEventArgs args = new DialogEventArgs(msg, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
OnPrompt(this, (EventArgs)args);
return args.DialogResults;
}
protected Hashtable Ask(string prompt, params string[] questions){
AskEventArgs args = new AskEventArgs(prompt, questions);
OnPrompt(this, (EventArgs)args);
return args.AnswerTable;
}
public Roller(RollType rollType){
_rollType = rollType;
}
protected abstract void BK();
protected abstract void GET();
protected abstract void PREP();
protected abstract void PUT();
public abstract void Roll();
public abstract bool IsRolling{
get;
set;
}
protected void roll() {
if (!this.IsRolling){
_rollThread = new Thread(new ThreadStart(_roll));
_rollThread.Name = this.ToString();
_rollThread.Start();
}else{
throw new Exception("Operations is currently in progress.");
}
}
private void _roll() {
try{
if (UI.UI.ClientVerMatchesDBVer()){
this.IsRolling = true;
this._dateTimeStarted = DateTime.Now;
_log = new RolloutLog();
Report("-".PadLeft(87, '-'));
Report("Begin rollout at " + DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString());
Report("Roller class: " + this.GetType().Name + "\r\nRollType = " + this.RollType.ToString());
Report("-".PadLeft(87, '-'));
this.BK();
this.GET();
this.PREP();
this.PUT();
this.IsRolling = false;
Report("---Rollout has finished---");
OnCompleted(this, new ReportEventArgs("Rollout completed successfully"));
}else{
throw new Exception("Client version is out of synch with DB version. Please update QED client before performing this roll.");
}
}
catch(Exception ex){
this.IsRolling = false;
Report(ex.Message + "\r\n" + ex.StackTrace);
throw new Exception(ex.Message, ex);
}
}
public static string DirTimeStamp{
get{
string ret;
DateTime now =DateTime.Now;
ret = now.Year.ToString().PadLeft(4, '0');
ret += now.Month.ToString().PadLeft(2, '0');
ret += now.Day.ToString().PadLeft(2, '0');
return ret;
}
}
public RollType RollType{
get{
return _rollType;
}
set{
_rollType = value;
}
}
public DirectoryInfo BinDir{
get{
return new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "\\bin");
}
}
public string CVS{
get{
return this.BinDir.GetFiles("cvs.exe")[0].FullName;
}
}
public string Plink{
get{
return this.BinDir.GetFiles("plink.exe")[0].FullName;
}
}
public string CVSUser{
get{
return ((BusinessIdentity)System.Threading.Thread.CurrentPrincipal.Identity).UserName;
}
}
public void EmptyWorkingDir(DirectoryInfo WorkingDir){
FileSystemInfo[] fsis = IO.GetFileSystemInfosRecursively(WorkingDir);
FileInfo file;
DirectoryInfo dir;
foreach(FileSystemInfo fsi in fsis){
if (fsi.Exists){
if (fsi is DirectoryInfo){
if (fsi.Name == "CVS"){
dir = (DirectoryInfo)fsi;
dir.Attributes = 0;
dir.Delete(true);
}
}else{
file = ((FileInfo)fsi);
file.Attributes = 0;
file.Delete();
}
}
}
}
public override string ToString() {
return this.GetType().Name + " " + this.RollType.ToString();
}
public string InstanceId{
get{
return this.GetType().Name + "_" + this.RollType.ToString() + "_" + this.DateTimeStarted.Ticks;
}
}
public DateTime DateTimeStarted{
get{
return _dateTimeStarted;
}
}
}
#endregion
#region General Roller
public enum SourceType{
CVS, Directory
}
public class General_Roller : Roller {
bool _dry = false;
static bool _isRolling;
string _plan = "";
GeneralRollSrc _genSrc;
GeneralRollDests _genDests;
public bool _cvsPullComplete;
public General_Roller() : base(RollType.General){
_genSrc = new GeneralRollSrc(this);
_genDests = new GeneralRollDests(this);
}
protected override void BK() {
if ( ! this.IsValid) throw new Exception("Can't run " + this.GetType().ToString() + " because it is in an invalid state");
_plan += "BACKUP:" + n;
FileSystemInfo qualifiedDestBK;
FileSystemInfo fsi;
foreach(GeneralRollDest dest in this.GeneralRollDestinations){
foreach(string path in dest.PathsToRoll){
fsi = IO.PathToFSI(path);
if (fsi != null){ // fsi represents an existing FileInfo or DirectoryInfo
qualifiedDestBK = dest.GetQualifiedBackup(fsi);
if ( fsi.Exists){
if ( !_dry){
EnsureDirectoryExists(qualifiedDestBK);
ReportAndCopy(fsi, qualifiedDestBK, false);
}else{
_plan += "\tCopy " + fsi.FullName + " " + qualifiedDestBK.FullName + n;
}
}
}
}
}
}
protected override void GET() {
}
protected override void PREP() {}
protected override void PUT() {
_plan += "DEPLOY:" + n;
FileSystemInfo destFSI;
foreach(FileSystemInfo srcFSI in _genSrc.FileSystemInfosToRoll){
foreach(GeneralRollDest genDest in this.GeneralRollDestinations){
destFSI = genDest.GetDestFSI(srcFSI);
if (!_dry){
if (!srcFSI.Exists) throw new Exception(srcFSI.FullName + " was scheduled to roll but isn't available.");
this.EnsureDirectoryExists(destFSI);
ReportAndCopy(srcFSI, destFSI, true);
}else{
_plan += "\tCopy " + srcFSI.FullName + " " + destFSI.FullName + n;
}
}
}
}
public void UpdateCVSWorkingCopy(){
if (_genSrc.SourceType == SourceType.CVS){
if ( ! _genSrc.CVSExportRoot.Exists) _genSrc.CVSExportRoot.Create();
ReportAndCheckoutCVS(_genSrc.CVSUser, _genSrc.CVSServer, _genSrc.CVSPath, _genSrc.CVSModule, _genSrc.CVSExportRoot, _genSrc.Branch, false);
}else{
throw new Exception("Can't update CVS on roller that isn't of CVS source type.");
}
}
public override void Roll() {
base.roll();
}
public override bool IsRolling {
get {
return _isRolling;
}
set {
_isRolling = value;
}
}
public string Plan{
get{
_plan = "";
BrokenRules rules = this.BrokenRulesWarnings;
if (rules.Count > 0){
foreach (BrokenRule rule in rules){
_plan += "WARNING: " + rule.Desc + n;
}
}
if (this.IsValid){
_dry = true;
this.BK(); this.GET(); this.PREP(); this.PUT();
_dry = false;
}else{
_plan += "Plan can not be created yet because the information supplied is either invalid or incomplete. See below:" + n + this.BrokenRules;
}
return _plan;
}
}
public GeneralRollSrc GeneralRollSource{
get{
return _genSrc;
}
set{
_genSrc = value;
}
}
public GeneralRollDests GeneralRollDestinations{
get{
return _genDests;
}
set{
_genDests = value;
}
}
public void Clear(){
this.GeneralRollDestinations = new GeneralRollDests(this);
this.GeneralRollSource = new GeneralRollSrc(this);
this.GeneralRollSource.RelativeFileSystemInfosToRoll.Clear();
this.GeneralRollDestinations.Clear();
}
public void EnsureDirectoryExists(FileSystemInfo fsi){
DirectoryInfo dir;
if (fsi is DirectoryInfo)
dir =(DirectoryInfo)fsi;
else
dir = ((FileInfo)fsi).Directory;
if (!dir.Exists) dir.Create();
}
public bool IsValid{
get{
return (this.BrokenRules.Count == 0);
}
}
public BrokenRules BrokenRulesWarnings{
get{
BrokenRules ret = new BrokenRules();
FileSystemInfo destFSI;
foreach(FileSystemInfo srcFSI in _genSrc.FileSystemInfosToRoll){
foreach(GeneralRollDest genDest in this.GeneralRollDestinations){
destFSI = genDest.GetDestFSI(srcFSI);
ret.Assert("FYI: The destination file or directory " + destFSI.FullName + " doesn't exist yet. It will be created after you roll", !destFSI.Exists);
}
}
return ret;
}
}
public BrokenRules BrokenRules{
get{
BrokenRules ret = new BrokenRules();
if (this.GeneralRollSource.SourceType == SourceType.CVS){
ret.Assert("CVS Branch required", this.GeneralRollSource.Branch == "");
if (this.GeneralRollSource.CVSExportRoot == null)
ret.Add("CVS Export Root required");
ret.Assert("CVS Module required", this.GeneralRollSource.CVSModule == "");
ret.Assert("CVS Path required", this.GeneralRollSource.CVSPath == "");
ret.Assert("CVS Server required", this.GeneralRollSource.CVSServer == "");
ret.Assert("CVS User required", this.GeneralRollSource.CVSUser == "");
}else{
if (this.GeneralRollSource.BaseDir == null)
ret.Add("Source Directory required");
else
ret.Assert("Source directory doesn't exists", !this.GeneralRollSource.BaseDir.Exists);
}
ret.Assert("At lease one source file or directory needs to be provided",
this.GeneralRollSource.RelativeFileSystemInfosToRoll.Count == 0);
ret.Assert("At lease one destination is required", this.GeneralRollDestinations.Count == 0);
foreach(GeneralRollDest dest in this.GeneralRollDestinations){
if (dest.BaseDir != null){
ret.Assert("Destination directory doesn't exist: " + dest.BaseDir.FullName, !dest.BaseDir.Exists);
}else{
ret.Add("Destination directory missing");
}
if (dest.BackupDir != null){
ret.Assert("Backup directory doesn't exist: " + dest.BackupDir.FullName, !dest.BackupDir.Exists);
}else{
ret.Add("Backup directory missing for destination for " + dest.BaseDir.FullName);
}
}
foreach(FileSystemInfo srcFSI in _genSrc.FileSystemInfosToRoll){
ret.Assert("NO_SOURCE_FILE", "Source file or directory doesn't exist: " + srcFSI.FullName + "." , !srcFSI.Exists);
}
return ret;
}
}
}
public class GeneralRollSrc{
General_Roller _genRoller;
protected string ps = "\\";
string n = System.Environment.NewLine;
public GeneralRollSrc(General_Roller genRoller){
_genRoller = genRoller;
}
DirectoryInfo _cvsExportRoot;
DirectoryInfo _baseDir;
string _cvsUser = "";
string _cvsServer = "";
string _cvsPath = "";
string _cvsModule = "";
string _branch = "";
SourceType _sourceType;
ArrayList _relativefileSystemInfosToRoll = new ArrayList();
public void AddSourceFileSystemInfo(string fsi){
this.RelativeFileSystemInfosToRoll.Add(fsi);
}
public ArrayList RelativeFileSystemInfosToRoll{
get{
return _relativefileSystemInfosToRoll;
}
}
public FileSystemInfo[] FileSystemInfosToRoll{
get{
if (this.BaseDir == null) return new FileSystemInfo[0];
FileSystemInfo[] ret = new FileSystemInfo[this.RelativeFileSystemInfosToRoll.Count];
int i=0;
FileInfo file;
DirectoryInfo dir;
foreach (string relative in this.RelativeFileSystemInfosToRoll){
file = new FileInfo(this.BaseDir.FullName + ps + relative.Replace("/", @"\" ));
if (file.Exists){
ret[i++] = file;
}else{
dir = new DirectoryInfo(this.BaseDir.FullName + ps + relative.Replace("/", @"\" ));
ret[i++] = dir;
}
}
return ret;
}
}
public string CVSUser{
get{
return _cvsUser.Trim();
}
set{
_cvsUser= value;
}
}
public string CVSServer{
get{
return _cvsServer.Trim();
}
set{
_cvsServer= value;
}
}
public string CVSPath{
get{
return _cvsPath.Trim();
}
set{
_cvsPath= value;
}
}
public string CVSModule{
get{
return _cvsModule.Trim();
}
set{
_cvsModule= value;
}
}
public DirectoryInfo BaseDir{
get{
if (this.SourceType == SourceType.CVS)
return new DirectoryInfo(this.CVSExportRoot.FullName + ps + this.CVSModule.Replace("/", "\\"));
else
return _baseDir;
}
set{
if (this.SourceType == SourceType.CVS) throw new Exception("Can't set BaseDir for CVS SourceType");
_baseDir = value;
}
}
public DirectoryInfo CVSExportRoot{
get{
return _cvsExportRoot;
}
set{
if (this.SourceType == SourceType.Directory) throw new Exception("Can't set CVSExportRoot for Directory SourceType");
_cvsExportRoot = value;
}
}
public SourceType SourceType{
get{
return _sourceType;
}
set{
_sourceType = value;
}
}
public string Branch{
get{
return _branch.Trim();
}
set{
_branch = value;
}
}
}
public class GeneralRollDests : CollectionBase{
General_Roller _genRoller;
public GeneralRollDests(General_Roller genRoller){
_genRoller = genRoller;
}
public GeneralRollDest CreateNew(){
GeneralRollDest ret = new GeneralRollDest(_genRoller);
List.Add(ret);
return ret;
}
}
public class GeneralRollDest{
GeneralRollSrc _src;
DirectoryInfo _backupDir;
DirectoryInfo _baseDir;
General_Roller _genRoller;
string n = System.Environment.NewLine;
string ps = "\\";
public DirectoryInfo BaseDir{
get{
return _baseDir;
}
set{
_baseDir = value;
}
}
public GeneralRollDest(General_Roller genRoller){
_genRoller = genRoller;
_src = _genRoller.GeneralRollSource;
}
public FileSystemInfo[] FileSystemInfosToRoll{
get{
string ex_relative = "";
try{
FileSystemInfo[] ret = new FileSystemInfo[_src.RelativeFileSystemInfosToRoll.Count];
int i = 0;
foreach(string relative in _src.RelativeFileSystemInfosToRoll){
ex_relative = relative;
ret[i++] = new FileInfo(this._baseDir.FullName + @"\" + relative);
}
return ret;
}
catch(ArgumentException ex){
throw new Exception("ArgumentException was encountered. " +
"There may be an error in the syntax of the relative source path." + n +
"Relative source path: " + ex_relative + n +
"Base directory: " + this._baseDir.FullName + n + ex.Message) ;
}
}
}
public string[] PathsToRoll{
get{
string ex_relative = "";
string [] ret = new string[_src.RelativeFileSystemInfosToRoll.Count];
int i = 0;
foreach(string relative in _src.RelativeFileSystemInfosToRoll){
ex_relative = relative;
ret[i++] = this._baseDir.FullName + @"\" + relative;
}
return ret;
}
}
public FileSystemInfo GetDestFSI(FileSystemInfo srcFSI){
string relativePath = srcFSI.FullName.Substring(this._genRoller.GeneralRollSource.BaseDir.FullName.Length);
if (srcFSI is FileInfo)
return new FileInfo(this.BaseDir.FullName + ps + relativePath);
else
return new DirectoryInfo(this.BaseDir.FullName + ps + relativePath);
}
public DirectoryInfo BackupDir{
get{
return _backupDir;
}
set{
_backupDir = value;
}
}
public FileSystemInfo GetQualifiedBackup(FileSystemInfo fsi){
DirectoryInfo dir = null;
if (fsi is FileInfo)
dir = ((FileInfo)fsi).Directory;
else
dir = (DirectoryInfo)fsi;
string relative = dir.FullName.Substring(this.BaseDir.FullName.Length);
string progName = this.BaseDir.Name;
if (fsi is FileInfo)
return new FileInfo( this.BackupDir.FullName + ps + progName + "_" + Roller.DirTimeStamp + relative + ps + fsi.Name);
else
return new DirectoryInfo( this.BackupDir.FullName + ps + progName + "_" + Roller.DirTimeStamp + relative);
}
}
#endregion
#region EventArg Derivitives
public class ReportEventArgs : EventArgs{
public readonly string Message = "";
public ReportEventArgs(string msg){
Message = msg;
}
}
public class DialogEventArgs : EventArgs{
public readonly string Message = "";
public readonly MessageBoxButtons MessageBoxButtons;
public readonly MessageBoxIcon MessageBoxIcon;
public readonly MessageBoxDefaultButton MessageBoxDefaultButton;
private DialogResult _dialogResult;
public DialogEventArgs(string msg, MessageBoxButtons mbb, MessageBoxIcon ico, MessageBoxDefaultButton defBtn){
Message = msg;
this.MessageBoxButtons = mbb;
this.MessageBoxIcon = ico;
this.MessageBoxDefaultButton = defBtn;
}
public DialogResult DialogResults{
get{
return _dialogResult;
}
set{
_dialogResult = value;
}
}
}
public class AskEventArgs : EventArgs{
public readonly string Prompt = "";
public string[] Questions;
public Hashtable AnswerTable;
public DialogResult DialogResult;
public AskEventArgs(string prompt, params string[] questions){
Prompt = prompt;
Questions = questions;
}
}
#endregion
#region Template
/*public class TEMPLATE_Roller :roller {
static bool _isRolling;
public TEMPLATE_Roller(RollType rollType) : base(rollType){
}
protected override void BK() {
}
protected override void GET() {
}
protected override void PREP() {
}
protected override void PUT() {
}
public override void Roll() {
base.roll();
}
public override bool IsRolling {
get {
return _isRolling;
}
set {
_isRolling = value;
}
}
}
*/
#endregion
}
| |
using UnityEngine;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
public enum LocalDataVersion
{
VERSION_FIRST_PLAYABLE = 1,
VERSION_ALPHA_1 = 2,
VERSION_ALPHA_2 = 3,
CURRENT = VERSION_ALPHA_2,
ATLEAST = VERSION_ALPHA_2,
}
public interface ILocalSerializable
{
void Serialize(LocalSerializationContext context);
void Deserialize(LocalSerializationContext context);
}
public class LocalSerializationContext
{
public BinaryWriter writer = null;
public BinaryReader reader = null;
public int version = 0;
}
public class LocalDataConfig
{
}
public static class LocalDataManager
{
public static readonly byte[] cryptvector = new byte[16]
{
0x74, 0x65, 0x73, 0x74, 0x30, 0x30, 0x31, 0x2C, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x2C, 0x31
};
public static string localDataPath
{
get
{
return Application.persistentDataPath;
}
}
public static void Save<T>(T data, string filename, bool encrypt, byte[] cryptkey) where T : ILocalSerializable, new()
{
//check valid.
if (data == null)
throw new ArgumentNullException("data");
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException(filename);
if (encrypt && cryptkey == null || cryptkey.Length != 32)
throw new ArgumentException("cryptkey==null or cryptkey.Length != 32");
//get filepath;
int version = (int)LocalDataVersion.CURRENT;
byte[] lawdata = Serialize<T>(data, version);
string filepath = Path.Combine(localDataPath, filename);
byte[] finaldata = lawdata;
//if encrypt data if need.
string secret = "";
if (encrypt)
{
finaldata = AESHelper.Encrypt(lawdata, cryptkey, cryptvector);
secret = MD5Helper.GetHash(cryptkey);
}
//write file.
using (FileStream fs = File.Open(filepath, FileMode.OpenOrCreate, FileAccess.Write))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(version);//version.
bw.Write(encrypt);//is encrypted
if (encrypt)
{
bw.Write(secret);//add secret.
}
bw.Write(finaldata);
}
}
}
public static T Load<T>(string filename, byte[] cryptkey) where T : ILocalSerializable, new()
{
if (string.IsNullOrEmpty(filename))
throw new ArgumentNullException("instance");
string filepath = Path.Combine(localDataPath, filename);
if (!File.Exists(filepath))
return default(T);
//load file data to the memory stream.
MemoryStream ms = new MemoryStream();
using (FileStream fs = File.Open(filepath, FileMode.Open, FileAccess.Read))
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] buffer = new byte[1024];
int readbyte = 0;
while (((readbyte = br.Read(buffer, 0, buffer.Length)) != 0))
{
ms.Write(buffer, 0, readbyte);
}
}
}
ms.Position = 0;
BinaryReader reader = new BinaryReader(ms);
int version = reader.ReadInt32();
bool encrypt = reader.ReadBoolean();
//check version
if (version < (int)LocalDataVersion.ATLEAST)
{
reader.Close();
ms.Close();
//File.Delete(filepath);
return default(T);
}
if (encrypt)
{
if (cryptkey == null || cryptkey.Length != 32)
throw new ArgumentNullException("cryptkey == null || cryptkey.Length != 32");
//check secret
string secret = reader.ReadString();
if (secret != MD5Helper.GetHash(cryptkey))
{
reader.Close();
ms.Close();
return default(T);
}
}
byte[] data = reader.ReadBytes((int)(ms.Length - ms.Position));
ms.Close();
reader.Close();
if (encrypt)
{
data = AESHelper.Decrypt(data, cryptkey, cryptvector);
}
T ret = Deserialize<T>(data, version);
return ret;
}
public static byte[] Serialize<T>(T data, int version) where T : ILocalSerializable, new()
{
if (data == null)
throw new ArgumentException("data");
byte[] serialized = null;
try
{
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter bw = new BinaryWriter(ms))
{
LocalSerializationContext context = new LocalSerializationContext();
context.version = version;
context.writer = bw;
data.Serialize(context);
serialized = ms.ToArray();
}
}
}
catch
{
throw new Exception("Local data serialization exception");
}
return serialized;
}
public static T Deserialize<T>(byte[] data, int version) where T : ILocalSerializable, new()
{
T t = new T();
using (MemoryStream ms = new MemoryStream(data))
{
using (BinaryReader br = new BinaryReader(ms))
{
LocalSerializationContext context = new LocalSerializationContext();
context.version = version;
context.reader = br;
t.Deserialize(context);
}
}
return t;
}
public static void Delete(string filename)
{
string filepath = Path.Combine(localDataPath, filename);
if (File.Exists(filepath))
{
File.Delete(filepath);
}
}
}
| |
// 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.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Options;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.CodeAnalysis.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.GenerateType
{
[ExportLanguageService(typeof(IGenerateTypeService), LanguageNames.CSharp), Shared]
internal class CSharpGenerateTypeService :
AbstractGenerateTypeService<CSharpGenerateTypeService, SimpleNameSyntax, ObjectCreationExpressionSyntax, ExpressionSyntax, TypeDeclarationSyntax, ArgumentSyntax>
{
private static readonly SyntaxAnnotation s_annotation = new SyntaxAnnotation();
protected override string DefaultFileExtension => ".cs";
protected override ExpressionSyntax GetLeftSideOfDot(SimpleNameSyntax simpleName)
{
return simpleName.GetLeftSideOfDot();
}
protected override bool IsInCatchDeclaration(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.CatchDeclaration);
}
protected override bool IsArrayElementType(ExpressionSyntax expression)
{
return expression.IsParentKind(SyntaxKind.ArrayType) &&
expression.Parent.IsParentKind(SyntaxKind.ArrayCreationExpression);
}
protected override bool IsInValueTypeConstraintContext(
SemanticModel semanticModel,
ExpressionSyntax expression,
CancellationToken cancellationToken)
{
if (expression is TypeSyntax && expression.IsParentKind(SyntaxKind.TypeArgumentList))
{
var typeArgumentList = (TypeArgumentListSyntax)expression.Parent;
var symbolInfo = semanticModel.GetSymbolInfo(typeArgumentList.Parent, cancellationToken);
var symbol = symbolInfo.GetAnySymbol();
if (symbol.IsConstructor())
{
symbol = symbol.ContainingType;
}
var parameterIndex = typeArgumentList.Arguments.IndexOf((TypeSyntax)expression);
var type = symbol as INamedTypeSymbol;
if (type != null)
{
type = type.OriginalDefinition;
var typeParameter = parameterIndex < type.TypeParameters.Length ? type.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
var method = symbol as IMethodSymbol;
if (method != null)
{
method = method.OriginalDefinition;
var typeParameter = parameterIndex < method.TypeParameters.Length ? method.TypeParameters[parameterIndex] : null;
return typeParameter != null && typeParameter.HasValueTypeConstraint;
}
}
return false;
}
protected override bool IsInInterfaceList(ExpressionSyntax expression)
{
if (expression is TypeSyntax &&
expression.Parent is BaseTypeSyntax &&
expression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)expression.Parent).Type == expression)
{
var baseList = (BaseListSyntax)expression.Parent.Parent;
// If it's after the first item, then it's definitely an interface.
if (baseList.Types[0] != expression.Parent)
{
return true;
}
// If it's in the base list of an interface or struct, then it's definitely an
// interface.
return
baseList.IsParentKind(SyntaxKind.InterfaceDeclaration) ||
baseList.IsParentKind(SyntaxKind.StructDeclaration);
}
if (expression is TypeSyntax &&
expression.IsParentKind(SyntaxKind.TypeConstraint) &&
expression.Parent.IsParentKind(SyntaxKind.TypeParameterConstraintClause))
{
var typeConstraint = (TypeConstraintSyntax)expression.Parent;
var constraintClause = (TypeParameterConstraintClauseSyntax)typeConstraint.Parent;
var index = constraintClause.Constraints.IndexOf(typeConstraint);
// If it's after the first item, then it's definitely an interface.
return index > 0;
}
return false;
}
protected override bool TryGetNameParts(ExpressionSyntax expression, out IList<string> nameParts)
{
nameParts = new List<string>();
return expression.TryGetNameParts(out nameParts);
}
protected override bool TryInitializeState(
SemanticDocument document,
SimpleNameSyntax simpleName,
CancellationToken cancellationToken,
out GenerateTypeServiceStateOptions generateTypeServiceStateOptions)
{
generateTypeServiceStateOptions = new GenerateTypeServiceStateOptions();
if (simpleName.IsVar)
{
return false;
}
if (SyntaxFacts.IsAliasQualifier(simpleName))
{
return false;
}
// Never offer if we're in a using directive, unless its a static using. The feeling here is that it's highly
// unlikely that this would be a location where a user would be wanting to generate
// something. They're really just trying to reference something that exists but
// isn't available for some reason (i.e. a missing reference).
var usingDirectiveSyntax = simpleName.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirectiveSyntax != null && usingDirectiveSyntax.StaticKeyword.Kind() != SyntaxKind.StaticKeyword)
{
return false;
}
ExpressionSyntax nameOrMemberAccessExpression = null;
if (simpleName.IsRightSideOfDot())
{
// This simplename comes from the cref
if (simpleName.IsParentKind(SyntaxKind.NameMemberCref))
{
return false;
}
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = (ExpressionSyntax)simpleName.Parent;
// If we're on the right side of a dot, then the left side better be a name (and
// not an arbitrary expression).
var leftSideExpression = simpleName.GetLeftSideOfDot();
if (!leftSideExpression.IsKind(
SyntaxKind.QualifiedName,
SyntaxKind.IdentifierName,
SyntaxKind.AliasQualifiedName,
SyntaxKind.GenericName,
SyntaxKind.SimpleMemberAccessExpression))
{
return false;
}
}
else
{
nameOrMemberAccessExpression = generateTypeServiceStateOptions.NameOrMemberAccessExpression = simpleName;
}
// BUG(5712): Don't offer generate type in an enum's base list.
if (nameOrMemberAccessExpression.Parent is BaseTypeSyntax &&
nameOrMemberAccessExpression.Parent.IsParentKind(SyntaxKind.BaseList) &&
((BaseTypeSyntax)nameOrMemberAccessExpression.Parent).Type == nameOrMemberAccessExpression &&
nameOrMemberAccessExpression.Parent.Parent.IsParentKind(SyntaxKind.EnumDeclaration))
{
return false;
}
// If we can guarantee it's a type only context, great. Otherwise, we may not want to
// provide this here.
var semanticModel = document.SemanticModel;
if (!SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
// Don't offer Generate Type in an expression context *unless* we're on the left
// side of a dot. In that case the user might be making a type that they're
// accessing a static off of.
var syntaxTree = semanticModel.SyntaxTree;
var start = nameOrMemberAccessExpression.SpanStart;
var tokenOnLeftOfStart = syntaxTree.FindTokenOnLeftOfPosition(start, cancellationToken);
var isExpressionContext = syntaxTree.IsExpressionContext(start, tokenOnLeftOfStart, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel);
var isStatementContext = syntaxTree.IsStatementContext(start, tokenOnLeftOfStart, cancellationToken);
var isExpressionOrStatementContext = isExpressionContext || isStatementContext;
// Delegate Type Creation is not allowed in Non Type Namespace Context
generateTypeServiceStateOptions.IsDelegateAllowed = false;
if (!isExpressionOrStatementContext)
{
return false;
}
if (!simpleName.IsLeftSideOfDot() && !simpleName.IsInsideNameOf())
{
if (nameOrMemberAccessExpression == null || !nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || !simpleName.IsRightSideOfDot())
{
return false;
}
var leftSymbol = semanticModel.GetSymbolInfo(((MemberAccessExpressionSyntax)nameOrMemberAccessExpression).Expression, cancellationToken).Symbol;
var token = simpleName.GetLastToken().GetNextToken();
// We let only the Namespace to be left of the Dot
if (leftSymbol == null ||
!leftSymbol.IsKind(SymbolKind.Namespace) ||
!token.IsKind(SyntaxKind.DotToken))
{
return false;
}
else
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
// Global Namespace
if (!generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess &&
!SyntaxFacts.IsInNamespaceOrTypeContext(simpleName))
{
var token = simpleName.GetLastToken().GetNextToken();
if (token.IsKind(SyntaxKind.DotToken) &&
simpleName.Parent == token.Parent)
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
generateTypeServiceStateOptions.IsTypeGeneratedIntoNamespaceFromMemberAccess = true;
}
}
}
var fieldDeclaration = simpleName.GetAncestor<FieldDeclarationSyntax>();
if (fieldDeclaration != null &&
fieldDeclaration.Parent is CompilationUnitSyntax &&
document.Document.SourceCodeKind == SourceCodeKind.Regular)
{
return false;
}
// Check to see if Module could be an option in the Type Generation in Cross Language Generation
var nextToken = simpleName.GetLastToken().GetNextToken();
if (simpleName.IsLeftSideOfDot() ||
nextToken.IsKind(SyntaxKind.DotToken))
{
if (simpleName.IsRightSideOfDot())
{
var parent = simpleName.Parent as QualifiedNameSyntax;
if (parent != null)
{
var leftSymbol = semanticModel.GetSymbolInfo(parent.Left, cancellationToken).Symbol;
if (leftSymbol != null && leftSymbol.IsKind(SymbolKind.Namespace))
{
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
}
}
}
if (SyntaxFacts.IsInNamespaceOrTypeContext(nameOrMemberAccessExpression))
{
if (nextToken.IsKind(SyntaxKind.DotToken))
{
// In Namespace or Type Context we cannot have Interface, Enum, Delegate as part of the Left Expression of a QualifiedName
generateTypeServiceStateOptions.IsDelegateAllowed = false;
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
generateTypeServiceStateOptions.IsMembersWithModule = true;
}
// case: class Foo<T> where T: MyType
if (nameOrMemberAccessExpression.GetAncestors<TypeConstraintSyntax>().Any())
{
generateTypeServiceStateOptions.IsClassInterfaceTypes = true;
return true;
}
// Events
if (nameOrMemberAccessExpression.GetAncestors<EventFieldDeclarationSyntax>().Any() ||
nameOrMemberAccessExpression.GetAncestors<EventDeclarationSyntax>().Any())
{
// Case : event foo name11
// Only Delegate
if (simpleName.Parent != null && !(simpleName.Parent is QualifiedNameSyntax))
{
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
// Case : event SomeSymbol.foo name11
if (nameOrMemberAccessExpression is QualifiedNameSyntax)
{
// Only Namespace, Class, Struct and Module are allowed to contain Delegate
// Case : event Something.Mytype.<Delegate> Identifier
if (nextToken.IsKind(SyntaxKind.DotToken))
{
if (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.Parent is QualifiedNameSyntax)
{
return true;
}
else
{
Contract.Fail("Cannot reach this point");
}
}
else
{
// Case : event Something.<Delegate> Identifier
generateTypeServiceStateOptions.IsDelegateOnly = true;
return true;
}
}
}
}
else
{
// MemberAccessExpression
if ((nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression) || (nameOrMemberAccessExpression.Parent != null && nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression)))
&& nameOrMemberAccessExpression.IsLeftSideOfDot())
{
// Check to see if the expression is part of Invocation Expression
ExpressionSyntax outerMostMemberAccessExpression = null;
if (nameOrMemberAccessExpression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
outerMostMemberAccessExpression = nameOrMemberAccessExpression;
}
else
{
Debug.Assert(nameOrMemberAccessExpression.IsParentKind(SyntaxKind.SimpleMemberAccessExpression));
outerMostMemberAccessExpression = (ExpressionSyntax)nameOrMemberAccessExpression.Parent;
}
outerMostMemberAccessExpression = outerMostMemberAccessExpression.GetAncestorsOrThis<ExpressionSyntax>().SkipWhile((n) => n != null && n.IsKind(SyntaxKind.SimpleMemberAccessExpression)).FirstOrDefault();
if (outerMostMemberAccessExpression != null && outerMostMemberAccessExpression is InvocationExpressionSyntax)
{
generateTypeServiceStateOptions.IsEnumNotAllowed = true;
}
}
}
// Cases:
// // 1 - Function Address
// var s2 = new MyD2(foo);
// // 2 - Delegate
// MyD1 d = null;
// var s1 = new MyD2(d);
// // 3 - Action
// Action action1 = null;
// var s3 = new MyD2(action1);
// // 4 - Func
// Func<int> lambda = () => { return 0; };
// var s4 = new MyD3(lambda);
if (nameOrMemberAccessExpression.Parent is ObjectCreationExpressionSyntax)
{
var objectCreationExpressionOpt = generateTypeServiceStateOptions.ObjectCreationExpressionOpt = (ObjectCreationExpressionSyntax)nameOrMemberAccessExpression.Parent;
// Enum and Interface not Allowed in Object Creation Expression
generateTypeServiceStateOptions.IsInterfaceOrEnumNotAllowedInTypeContext = true;
if (objectCreationExpressionOpt.ArgumentList != null)
{
if (objectCreationExpressionOpt.ArgumentList.CloseParenToken.IsMissing)
{
return false;
}
// Get the Method symbol for the Delegate to be created
if (generateTypeServiceStateOptions.IsDelegateAllowed &&
objectCreationExpressionOpt.ArgumentList.Arguments.Count == 1 &&
objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, objectCreationExpressionOpt.ArgumentList.Arguments[0].Expression, cancellationToken);
}
else
{
generateTypeServiceStateOptions.IsDelegateAllowed = false;
}
}
if (objectCreationExpressionOpt.Initializer != null)
{
foreach (var expression in objectCreationExpressionOpt.Initializer.Expressions)
{
var simpleAssignmentExpression = expression as AssignmentExpressionSyntax;
if (simpleAssignmentExpression == null)
{
continue;
}
var name = simpleAssignmentExpression.Left as SimpleNameSyntax;
if (name == null)
{
continue;
}
generateTypeServiceStateOptions.PropertiesToGenerate.Add(name);
}
}
}
if (generateTypeServiceStateOptions.IsDelegateAllowed)
{
// MyD1 z1 = foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.VariableDeclaration))
{
var variableDeclaration = (VariableDeclarationSyntax)nameOrMemberAccessExpression.Parent;
if (variableDeclaration.Variables.Count != 0)
{
var firstVarDeclWithInitializer = variableDeclaration.Variables.FirstOrDefault(var => var.Initializer != null && var.Initializer.Value != null);
if (firstVarDeclWithInitializer != null && firstVarDeclWithInitializer.Initializer != null && firstVarDeclWithInitializer.Initializer.Value != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, firstVarDeclWithInitializer.Initializer.Value, cancellationToken);
}
}
}
// var w1 = (MyD1)foo;
if (nameOrMemberAccessExpression.Parent.IsKind(SyntaxKind.CastExpression))
{
var castExpression = (CastExpressionSyntax)nameOrMemberAccessExpression.Parent;
if (castExpression.Expression != null)
{
generateTypeServiceStateOptions.DelegateCreationMethodSymbol = GetMethodSymbolIfPresent(semanticModel, castExpression.Expression, cancellationToken);
}
}
}
return true;
}
private IMethodSymbol GetMethodSymbolIfPresent(SemanticModel semanticModel, ExpressionSyntax expression, CancellationToken cancellationToken)
{
if (expression == null)
{
return null;
}
var memberGroup = semanticModel.GetMemberGroup(expression, cancellationToken);
if (memberGroup.Length != 0)
{
return memberGroup.ElementAt(0).IsKind(SymbolKind.Method) ? (IMethodSymbol)memberGroup.ElementAt(0) : null;
}
var expressionType = semanticModel.GetTypeInfo(expression, cancellationToken).Type;
if (expressionType.IsDelegateType())
{
return ((INamedTypeSymbol)expressionType).DelegateInvokeMethod;
}
var expressionSymbol = semanticModel.GetSymbolInfo(expression, cancellationToken).Symbol;
if (expressionSymbol.IsKind(SymbolKind.Method))
{
return (IMethodSymbol)expressionSymbol;
}
return null;
}
private Accessibility DetermineAccessibilityConstraint(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
return semanticModel.DetermineAccessibilityConstraint(
state.NameOrMemberAccessExpression as TypeSyntax, cancellationToken);
}
protected override IList<ITypeParameterSymbol> GetTypeParameters(
State state,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
if (state.SimpleName is GenericNameSyntax)
{
var genericName = (GenericNameSyntax)state.SimpleName;
var typeArguments = state.SimpleName.Arity == genericName.TypeArgumentList.Arguments.Count
? genericName.TypeArgumentList.Arguments.OfType<SyntaxNode>().ToList()
: Enumerable.Repeat<SyntaxNode>(null, state.SimpleName.Arity);
return this.GetTypeParameters(state, semanticModel, typeArguments, cancellationToken);
}
return SpecializedCollections.EmptyList<ITypeParameterSymbol>();
}
protected override bool TryGetArgumentList(ObjectCreationExpressionSyntax objectCreationExpression, out IList<ArgumentSyntax> argumentList)
{
if (objectCreationExpression != null && objectCreationExpression.ArgumentList != null)
{
argumentList = objectCreationExpression.ArgumentList.Arguments.ToList();
return true;
}
argumentList = null;
return false;
}
protected override IList<ParameterName> GenerateParameterNames(
SemanticModel semanticModel, IList<ArgumentSyntax> arguments)
{
return semanticModel.GenerateParameterNames(arguments);
}
public override string GetRootNamespace(CompilationOptions options)
{
return string.Empty;
}
protected override bool IsInVariableTypeContext(ExpressionSyntax expression)
{
return false;
}
protected override INamedTypeSymbol DetermineTypeToGenerateIn(SemanticModel semanticModel, SimpleNameSyntax simpleName, CancellationToken cancellationToken)
{
return semanticModel.GetEnclosingNamedType(simpleName.SpanStart, cancellationToken);
}
protected override Accessibility GetAccessibility(State state, SemanticModel semanticModel, bool intoNamespace, CancellationToken cancellationToken)
{
var accessibility = DetermineDefaultAccessibility(state, semanticModel, intoNamespace, cancellationToken);
if (!state.IsTypeGeneratedIntoNamespaceFromMemberAccess)
{
var accessibilityConstraint = DetermineAccessibilityConstraint(state, semanticModel, cancellationToken);
if (accessibilityConstraint == Accessibility.Public ||
accessibilityConstraint == Accessibility.Internal)
{
accessibility = accessibilityConstraint;
}
}
return accessibility;
}
protected override ITypeSymbol DetermineArgumentType(SemanticModel semanticModel, ArgumentSyntax argument, CancellationToken cancellationToken)
{
return argument.DetermineParameterType(semanticModel, cancellationToken);
}
protected override bool IsConversionImplicit(Compilation compilation, ITypeSymbol sourceType, ITypeSymbol targetType)
{
return compilation.ClassifyConversion(sourceType, targetType).IsImplicit;
}
public override async Task<Tuple<INamespaceSymbol, INamespaceOrTypeSymbol, Location>> GetOrGenerateEnclosingNamespaceSymbolAsync(
INamedTypeSymbol namedTypeSymbol, string[] containers, Document selectedDocument, SyntaxNode selectedDocumentRoot, CancellationToken cancellationToken)
{
var compilationUnit = (CompilationUnitSyntax)selectedDocumentRoot;
var semanticModel = await selectedDocument.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
if (containers.Length != 0)
{
// Search the NS declaration in the root
var containerList = new List<string>(containers);
var enclosingNamespace = GetDeclaringNamespace(containerList, 0, compilationUnit);
if (enclosingNamespace != null)
{
var enclosingNamespaceSymbol = semanticModel.GetSymbolInfo(enclosingNamespace.Name, cancellationToken);
if (enclosingNamespaceSymbol.Symbol != null)
{
return Tuple.Create((INamespaceSymbol)enclosingNamespaceSymbol.Symbol,
(INamespaceOrTypeSymbol)namedTypeSymbol,
enclosingNamespace.CloseBraceToken.GetLocation());
}
}
}
var globalNamespace = semanticModel.GetEnclosingNamespace(0, cancellationToken);
var rootNamespaceOrType = namedTypeSymbol.GenerateRootNamespaceOrType(containers);
var lastMember = compilationUnit.Members.LastOrDefault();
Location afterThisLocation = null;
if (lastMember != null)
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan(lastMember.Span.End, 0));
}
else
{
afterThisLocation = semanticModel.SyntaxTree.GetLocation(new TextSpan());
}
return Tuple.Create(globalNamespace,
rootNamespaceOrType,
afterThisLocation);
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, CompilationUnitSyntax compilationUnit)
{
foreach (var member in compilationUnit.Members)
{
var namespaceDeclaration = GetDeclaringNamespace(containers, 0, member);
if (namespaceDeclaration != null)
{
return namespaceDeclaration;
}
}
return null;
}
private NamespaceDeclarationSyntax GetDeclaringNamespace(List<string> containers, int indexDone, SyntaxNode localRoot)
{
var namespaceDecl = localRoot as NamespaceDeclarationSyntax;
if (namespaceDecl == null || namespaceDecl.Name is AliasQualifiedNameSyntax)
{
return null;
}
List<string> namespaceContainers = new List<string>();
GetNamespaceContainers(namespaceDecl.Name, namespaceContainers);
if (namespaceContainers.Count + indexDone > containers.Count ||
!IdentifierMatches(indexDone, namespaceContainers, containers))
{
return null;
}
indexDone = indexDone + namespaceContainers.Count;
if (indexDone == containers.Count)
{
return namespaceDecl;
}
foreach (var member in namespaceDecl.Members)
{
var resultant = GetDeclaringNamespace(containers, indexDone, member);
if (resultant != null)
{
return resultant;
}
}
return null;
}
private bool IdentifierMatches(int indexDone, List<string> namespaceContainers, List<string> containers)
{
for (int i = 0; i < namespaceContainers.Count; ++i)
{
if (namespaceContainers[i] != containers[indexDone + i])
{
return false;
}
}
return true;
}
private void GetNamespaceContainers(NameSyntax name, List<string> namespaceContainers)
{
if (name is QualifiedNameSyntax)
{
GetNamespaceContainers(((QualifiedNameSyntax)name).Left, namespaceContainers);
namespaceContainers.Add(((QualifiedNameSyntax)name).Right.Identifier.ValueText);
}
else
{
Debug.Assert(name is SimpleNameSyntax);
namespaceContainers.Add(((SimpleNameSyntax)name).Identifier.ValueText);
}
}
internal override bool TryGetBaseList(ExpressionSyntax expression, out TypeKindOptions typeKindValue)
{
typeKindValue = TypeKindOptions.AllOptions;
if (expression == null)
{
return false;
}
var node = expression as SyntaxNode;
while (node != null)
{
if (node is BaseListSyntax)
{
if (node.Parent != null && (node.Parent is InterfaceDeclarationSyntax || node.Parent is StructDeclarationSyntax))
{
typeKindValue = TypeKindOptions.Interface;
return true;
}
typeKindValue = TypeKindOptions.BaseList;
return true;
}
node = node.Parent;
}
return false;
}
internal override bool IsPublicOnlyAccessibility(ExpressionSyntax expression, Project project)
{
if (expression == null)
{
return false;
}
if (GeneratedTypesMustBePublic(project))
{
return true;
}
var node = expression as SyntaxNode;
SyntaxNode previousNode = null;
while (node != null)
{
// Types in BaseList, Type Constraint or Member Types cannot be of more restricted accessibility than the declaring type
if ((node is BaseListSyntax || node is TypeParameterConstraintClauseSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
var typeDecl = node.Parent as TypeDeclarationSyntax;
if (typeDecl != null)
{
if (typeDecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return IsAllContainingTypeDeclsPublic(typeDecl);
}
else
{
// The Type Decl which contains the BaseList does not contain Public
return false;
}
}
Contract.Fail("Cannot reach this point");
}
if ((node is EventDeclarationSyntax || node is EventFieldDeclarationSyntax) &&
node.Parent != null &&
node.Parent is TypeDeclarationSyntax)
{
// Make sure the GFU is not inside the Accessors
if (previousNode != null && previousNode is AccessorListSyntax)
{
return false;
}
// Make sure that Event Declaration themselves are Public in the first place
if (!node.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword))
{
return false;
}
return IsAllContainingTypeDeclsPublic(node);
}
previousNode = node;
node = node.Parent;
}
return false;
}
private bool IsAllContainingTypeDeclsPublic(SyntaxNode node)
{
// Make sure that all the containing Type Declarations are also Public
var containingTypeDeclarations = node.GetAncestors<TypeDeclarationSyntax>();
if (containingTypeDeclarations.Count() == 0)
{
return true;
}
else
{
return containingTypeDeclarations.All(typedecl => typedecl.GetModifiers().Any(m => m.Kind() == SyntaxKind.PublicKeyword));
}
}
internal override bool IsGenericName(SimpleNameSyntax simpleName)
{
if (simpleName == null)
{
return false;
}
var genericName = simpleName as GenericNameSyntax;
return genericName != null;
}
internal override bool IsSimpleName(ExpressionSyntax expression)
{
return expression is SimpleNameSyntax;
}
internal override async Task<Solution> TryAddUsingsOrImportToDocumentAsync(Solution updatedSolution, SyntaxNode modifiedRoot, Document document, SimpleNameSyntax simpleName, string includeUsingsOrImports, CancellationToken cancellationToken)
{
// Nothing to include
if (string.IsNullOrWhiteSpace(includeUsingsOrImports))
{
return updatedSolution;
}
SyntaxNode root = null;
if (modifiedRoot == null)
{
root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
}
else
{
root = modifiedRoot;
}
if (root is CompilationUnitSyntax)
{
var compilationRoot = (CompilationUnitSyntax)root;
var usingDirective = SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(includeUsingsOrImports));
// Check if the usings is already present
if (compilationRoot.Usings.Where(n => n != null && n.Alias == null)
.Select(n => n.Name.ToString())
.Any(n => n.Equals(includeUsingsOrImports)))
{
return updatedSolution;
}
// Check if the GFU is triggered from the namespace same as the usings namespace
if (await IsWithinTheImportingNamespaceAsync(document, simpleName.SpanStart, includeUsingsOrImports, cancellationToken).ConfigureAwait(false))
{
return updatedSolution;
}
var placeSystemNamespaceFirst = document.Options.GetOption(OrganizerOptions.PlaceSystemNamespaceFirst);
var addedCompilationRoot = compilationRoot.AddUsingDirectives(new[] { usingDirective }, placeSystemNamespaceFirst, Formatter.Annotation);
updatedSolution = updatedSolution.WithDocumentSyntaxRoot(document.Id, addedCompilationRoot, PreservationMode.PreserveIdentity);
}
return updatedSolution;
}
private ITypeSymbol GetPropertyType(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken)
{
var parentAssignment = propertyName.Parent as AssignmentExpressionSyntax;
if (parentAssignment != null)
{
return typeInference.InferType(
semanticModel, parentAssignment.Left, objectAsDefault: true, cancellationToken: cancellationToken);
}
var isPatternExpression = propertyName.Parent as IsPatternExpressionSyntax;
if (isPatternExpression != null)
{
return typeInference.InferType(
semanticModel, isPatternExpression.Expression, objectAsDefault: true, cancellationToken: cancellationToken);
}
return null;
}
private IPropertySymbol CreatePropertySymbol(
SimpleNameSyntax propertyName, ITypeSymbol propertyType)
{
return CodeGenerationSymbolFactory.CreatePropertySymbol(
attributes: SpecializedCollections.EmptyList<AttributeData>(),
accessibility: Accessibility.Public,
modifiers: new DeclarationModifiers(),
explicitInterfaceSymbol: null,
name: propertyName.Identifier.ValueText,
type: propertyType,
parameters: null,
getMethod: s_accessor,
setMethod: s_accessor,
isIndexer: false);
}
private static readonly IMethodSymbol s_accessor = CodeGenerationSymbolFactory.CreateAccessorSymbol(
attributes: null,
accessibility: Accessibility.Public,
statements: null);
internal override bool TryGenerateProperty(
SimpleNameSyntax propertyName,
SemanticModel semanticModel,
ITypeInferenceService typeInference,
CancellationToken cancellationToken,
out IPropertySymbol property)
{
property = null;
var propertyType = GetPropertyType(propertyName, semanticModel, typeInference, cancellationToken);
if (propertyType == null || propertyType is IErrorTypeSymbol)
{
property = CreatePropertySymbol(propertyName, semanticModel.Compilation.ObjectType);
return property != null;
}
property = CreatePropertySymbol(propertyName, propertyType);
return property != null;
}
internal override IMethodSymbol GetDelegatingConstructor(
SemanticDocument document,
ObjectCreationExpressionSyntax objectCreation,
INamedTypeSymbol namedType,
ISet<IMethodSymbol> candidates,
CancellationToken cancellationToken)
{
var model = document.SemanticModel;
var oldNode = objectCreation
.AncestorsAndSelf(ascendOutOfTrivia: false)
.Where(node => SpeculationAnalyzer.CanSpeculateOnNode(node))
.LastOrDefault();
var typeNameToReplace = objectCreation.Type;
var newTypeName = namedType.GenerateTypeSyntax();
var newObjectCreation = objectCreation.WithType(newTypeName).WithAdditionalAnnotations(s_annotation);
var newNode = oldNode.ReplaceNode(objectCreation, newObjectCreation);
var speculativeModel = SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(oldNode, newNode, model);
if (speculativeModel != null)
{
newObjectCreation = (ObjectCreationExpressionSyntax)newNode.GetAnnotatedNodes(s_annotation).Single();
var symbolInfo = speculativeModel.GetSymbolInfo(newObjectCreation, cancellationToken);
var parameterTypes = newObjectCreation.ArgumentList.Arguments.Select(
a => a.DetermineParameterType(speculativeModel, cancellationToken)).ToList();
return GenerateConstructorHelpers.GetDelegatingConstructor(
document, symbolInfo, candidates, namedType, parameterTypes);
}
return null;
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace System.Net
{
using System.Net.Sockets;
using System.Globalization;
using System.Text;
using Microsoft.SPOT.Net.NetworkInformation;
/// <devdoc>
/// <para>Provides an internet protocol (IP) address.</para>
/// </devdoc>
[Serializable]
public class IPAddress
{
public static readonly IPAddress Any = new IPAddress(0x0000000000000000);
public static readonly IPAddress Loopback = new IPAddress(0x000000000100007F);
internal long m_Address;
public IPAddress(long newAddress)
{
if (newAddress < 0 || newAddress > 0x00000000FFFFFFFF)
{
throw new ArgumentOutOfRangeException();
}
m_Address = newAddress;
}
public IPAddress(byte[] newAddressBytes)
: this(((((newAddressBytes[3] << 0x18) | (newAddressBytes[2] << 0x10)) | (newAddressBytes[1] << 0x08)) | newAddressBytes[0]) & ((long)0xFFFFFFFF))
{
}
public override bool Equals(object obj)
{
IPAddress addr = obj as IPAddress;
if (obj == null) return false;
return this.m_Address == addr.m_Address;
}
public byte[] GetAddressBytes()
{
return new byte[]
{
(byte)(m_Address),
(byte)(m_Address >> 8),
(byte)(m_Address >> 16),
(byte)(m_Address >> 24)
};
}
public static IPAddress Parse(string ipString)
{
if (ipString == null)
throw new ArgumentNullException();
ulong ipAddress = 0L;
int lastIndex = 0;
int shiftIndex = 0;
ulong mask = 0x00000000000000FF;
ulong octet = 0L;
int length = ipString.Length;
for (int i = 0; i < length; ++i)
{
// Parse to '.' or end of IP address
if (ipString[i] == '.' || i == length - 1)
// If the IP starts with a '.'
// or a segment is longer than 3 characters or shiftIndex > last bit position throw.
if (i == 0 || i - lastIndex > 3 || shiftIndex > 24)
{
throw new ArgumentException();
}
else
{
i = i == length - 1 ? ++i : i;
octet = (ulong)(ConvertStringToInt32(ipString.Substring(lastIndex, i - lastIndex)) & 0x00000000000000FF);
ipAddress = ipAddress + (ulong)((octet << shiftIndex) & mask);
lastIndex = i + 1;
shiftIndex = shiftIndex + 8;
mask = (mask << 8);
}
}
return new IPAddress((long)ipAddress);
}
public override string ToString()
{
return ((byte)(m_Address)).ToString() +
"." +
((byte)(m_Address >> 8)).ToString() +
"." +
((byte)(m_Address >> 16)).ToString() +
"." +
((byte)(m_Address >> 24)).ToString();
}
//--//
////////////////////////////////////////////////////////////////////////////////////////
// this method ToInt32 is part of teh Convert class which we will bring over later
// at that time we will get rid of this code
//
/// <summary>
/// Converts the specified System.String representation of a number to an equivalent
/// 32-bit signed integer.
/// </summary>
/// <param name="value">A System.String containing a number to convert.</param>
/// <returns>
/// A 32-bit signed integer equivalent to the value of value.-or- Zero if value
/// is null.
/// </returns>
/// <exception cref="System.OverflowException">
/// Value represents a number less than System.Int32.MinValue or greater than
/// System.Int32.MaxValue.
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// The value parameter is null.
/// </exception>
/// <exception cref="System.FormatException">
/// Value does not consist of an optional sign followed by a sequence of digits
/// (zero through nine).
/// </exception>
private static int ConvertStringToInt32(string value)
{
char[] num = value.ToCharArray();
int result = 0;
bool isNegative = false;
int signIndex = 0;
if (num[0] == '-')
{
isNegative = true;
signIndex = 1;
}
else if (num[0] == '+')
{
signIndex = 1;
}
int exp = 1;
for (int i = num.Length - 1; i >= signIndex; i--)
{
if (num[i] < '0' || num[i] > '9')
{
throw new ArgumentException();
}
result += ((num[i] - '0') * exp);
exp *= 10;
}
return (isNegative) ? (-1 * result) : result;
}
// this method ToInt32 is part of teh Convert class which we will bring over later
////////////////////////////////////////////////////////////////////////////////////////
public static IPAddress GetDefaultLocalAddress()
{
// Special conditions are implemented here because of a ptoblem with GetHostEntry
// on the digi device and NetworkInterface from the emulator.
// In the emulator we must use GetHostEntry.
// On the device and Windows NetworkInterface works and is preferred.
try
{
NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
int cnt = interfaces.Length;
for (int i = 0; i < cnt; i++)
{
NetworkInterface ni = interfaces[i];
if (ni.IPAddress != "0.0.0.0" && ni.SubnetMask != "0.0.0.0")
{
return IPAddress.Parse(ni.IPAddress);
}
}
}
catch
{
}
try
{
IPAddress localAddress = null;
IPHostEntry hostEntry = Dns.GetHostEntry("");
int cnt = hostEntry.AddressList.Length;
for (int i = 0; i < cnt; ++i)
{
if ((localAddress = hostEntry.AddressList[i]) != null)
{
if(localAddress.m_Address != 0)
{
return localAddress;
}
}
}
}
catch
{
}
return IPAddress.Any;
}
} // class IPAddress
} // namespace System.Net
| |
/*
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
*************************************************************************
*/
using System;
using System.Text;
using HANDLE = System.IntPtr;
using i16 = System.Int16;
using sqlite3_int64 = System.Int64;
using u32 = System.UInt32;
namespace CleanSqlite
{
using DbPage = Sqlite3.PgHdr;
using sqlite3_pcache = Sqlite3.PCache1;
using sqlite3_stmt = Sqlite3.Vdbe;
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
public delegate void dxAuth( object pAuthArg, int b, string c, string d, string e, string f );
public delegate int dxBusy( object pBtShared, int iValue );
public delegate void dxFreeAux( object pAuxArg );
public delegate int dxCallback(ref object pCallbackArg, sqlite3_int64 argc, object p2, object p3 );
public delegate void dxalarmCallback( object pNotUsed, sqlite3_int64 iNotUsed, int size );
public delegate void dxCollNeeded( object pCollNeededArg, sqlite3 db, int eTextRep, string collationName );
public delegate int dxCommitCallback( object pCommitArg );
public delegate int dxCompare( object pCompareArg, int size1, string Key1, int size2, string Key2 );
public delegate bool dxCompare4( string Key1, int size1, string Key2, int size2 );
public delegate void dxDel( ref string pDelArg ); // needs ref
public delegate void dxDelCollSeq( ref object pDelArg ); // needs ref
public delegate void dxLog( object pLogArg, int i, string msg );
public delegate void dxLogcallback( object pCallbackArg, int argc, string p2 );
public delegate void dxProfile( object pProfileArg, string msg, sqlite3_int64 time );
public delegate int dxProgress( object pProgressArg );
public delegate void dxRollbackCallback( object pRollbackArg );
public delegate void dxTrace( object pTraceArg, string msg );
public delegate void dxUpdateCallback( object pUpdateArg, int b, string c, string d, sqlite3_int64 e );
public delegate int dxWalCallback( object pWalArg, sqlite3 db, string zDb, int nEntry );
/*
* FUNCTIONS
*
*/
public delegate void dxFunc( sqlite3_context ctx, int intValue, sqlite3_value[] value );
public delegate void dxStep( sqlite3_context ctx, int intValue, sqlite3_value[] value );
public delegate void dxFinal( sqlite3_context ctx );
public delegate void dxFDestroy( object pArg );
//
public delegate string dxColname( sqlite3_value pVal );
public delegate int dxFuncBtree( Btree p );
public delegate int dxExprTreeFunction( ref int pArg, Expr pExpr );
public delegate int dxExprTreeFunction_NC( NameContext pArg, ref Expr pExpr );
public delegate int dxExprTreeFunction_OBJ( object pArg, Expr pExpr );
/*
VFS Delegates
*/
public delegate int dxClose( sqlite3_file File_ID );
public delegate int dxCheckReservedLock( sqlite3_file File_ID, ref int pRes );
public delegate int dxDeviceCharacteristics( sqlite3_file File_ID );
public delegate int dxFileControl( sqlite3_file File_ID, int op, ref sqlite3_int64 pArgs );
public delegate int dxFileSize( sqlite3_file File_ID, ref long size );
public delegate int dxLock( sqlite3_file File_ID, int locktype );
public delegate int dxRead( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset );
public delegate int dxSectorSize( sqlite3_file File_ID );
public delegate int dxSync( sqlite3_file File_ID, int flags );
public delegate int dxTruncate( sqlite3_file File_ID, sqlite3_int64 size );
public delegate int dxUnlock( sqlite3_file File_ID, int locktype );
public delegate int dxWrite( sqlite3_file File_ID, byte[] buffer, int amount, sqlite3_int64 offset );
public delegate int dxShmMap( sqlite3_file File_ID, int iPg, int pgsz, int pInt, out object pvolatile );
public delegate int dxShmLock( sqlite3_file File_ID, int offset, int n, int flags );
public delegate void dxShmBarrier( sqlite3_file File_ID );
public delegate int dxShmUnmap( sqlite3_file File_ID, int deleteFlag );
/*
sqlite_vfs Delegates
*/
public delegate int dxOpen( sqlite3_vfs vfs, string zName, sqlite3_file db, int flags, out int pOutFlags );
public delegate int dxDelete( sqlite3_vfs vfs, string zName, int syncDir );
public delegate int dxAccess( sqlite3_vfs vfs, string zName, int flags, out int pResOut );
public delegate int dxFullPathname( sqlite3_vfs vfs, string zName, int nOut, StringBuilder zOut );
public delegate HANDLE dxDlOpen( sqlite3_vfs vfs, string zFilename );
public delegate int dxDlError( sqlite3_vfs vfs, int nByte, string zErrMsg );
public delegate HANDLE dxDlSym( sqlite3_vfs vfs, HANDLE data, string zSymbol );
public delegate int dxDlClose( sqlite3_vfs vfs, HANDLE data );
public delegate int dxRandomness( sqlite3_vfs vfs, int nByte, byte[] buffer );
public delegate int dxSleep( sqlite3_vfs vfs, int microseconds );
public delegate int dxCurrentTime( sqlite3_vfs vfs, ref double currenttime );
public delegate int dxGetLastError( sqlite3_vfs pVfs, int nBuf, ref string zBuf );
public delegate int dxCurrentTimeInt64( sqlite3_vfs pVfs, ref sqlite3_int64 pTime );
public delegate int dxSetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
public delegate int dxGetSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
public delegate int dxNextSystemCall( sqlite3_vfs pVfs, string zName, sqlite3_int64 sqlite3_syscall_ptr );
/*
* Pager Delegates
*/
public delegate void dxDestructor( DbPage dbPage ); /* Call this routine when freeing pages */
public delegate int dxBusyHandler( object pBusyHandlerArg );
public delegate void dxReiniter( DbPage dbPage ); /* Call this routine when reloading pages */
public delegate void dxFreeSchema( Schema schema );
#if SQLITE_HAS_CODEC
public delegate byte[] dxCodec( codec_ctx pCodec, byte[] D, uint pageNumber, int X ); //void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
public delegate void dxCodecSizeChng( codec_ctx pCodec, int pageSize, i16 nReserve ); //void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
public delegate void dxCodecFree( ref codec_ctx pCodec ); //void (*xCodecFree)(void); /* Destructor for the codec */
#endif
//Module
public delegate void dxDestroy( ref PgHdr pDestroyArg );
public delegate int dxStress( object obj, PgHdr pPhHdr );
//sqlite3_module
public delegate int smdxCreateConnect( sqlite3 db, object pAux, int argc, string[] constargv, out sqlite3_vtab ppVTab, out string pError );
public delegate int smdxBestIndex( sqlite3_vtab pVTab, ref sqlite3_index_info pIndex );
public delegate int smdxDisconnect( ref object pVTab );
public delegate int smdxDestroy(ref object pVTab );
public delegate int smdxOpen( sqlite3_vtab pVTab, out sqlite3_vtab_cursor ppCursor );
public delegate int smdxClose( ref sqlite3_vtab_cursor pCursor );
public delegate int smdxFilter( sqlite3_vtab_cursor pCursor, int idxNum, string idxStr, int argc, sqlite3_value[] argv );
public delegate int smdxNext( sqlite3_vtab_cursor pCursor );
public delegate int smdxEof( sqlite3_vtab_cursor pCursor );
public delegate int smdxColumn( sqlite3_vtab_cursor pCursor, sqlite3_context p2, int p3 );
public delegate int smdxRowid( sqlite3_vtab_cursor pCursor, out sqlite3_int64 pRowid );
public delegate int smdxUpdate( sqlite3_vtab pVTab, int p1, sqlite3_value[] p2, out sqlite3_int64 p3 );
public delegate int smdxFunction ( sqlite3_vtab pVTab );
public delegate int smdxFindFunction( sqlite3_vtab pVtab, int nArg, string zName, ref dxFunc pxFunc, ref object ppArg );
public delegate int smdxRename( sqlite3_vtab pVtab, string zNew );
public delegate int smdxFunctionArg (sqlite3_vtab pVTab, int nArg );
//AutoExtention
public delegate int dxInit( sqlite3 db, ref string zMessage, sqlite3_api_routines sar );
#if !SQLITE_OMIT_VIRTUALTABLE
public delegate int dmxCreate(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
public delegate int dmxConnect(sqlite3 db, object pAux, int argc, string p4, object argv, sqlite3_vtab ppVTab, char p7);
public delegate int dmxBestIndex(sqlite3_vtab pVTab, ref sqlite3_index_info pIndexInfo);
public delegate int dmxDisconnect(sqlite3_vtab pVTab);
public delegate int dmxDestroy(sqlite3_vtab pVTab);
public delegate int dmxOpen(sqlite3_vtab pVTab, sqlite3_vtab_cursor ppCursor);
public delegate int dmxClose(sqlite3_vtab_cursor pCursor);
public delegate int dmxFilter(sqlite3_vtab_cursor pCursor, int idmxNum, string idmxStr, int argc, sqlite3_value argv);
public delegate int dmxNext(sqlite3_vtab_cursor pCursor);
public delegate int dmxEof(sqlite3_vtab_cursor pCursor);
public delegate int dmxColumn(sqlite3_vtab_cursor pCursor, sqlite3_context ctx, int i3);
public delegate int dmxRowid(sqlite3_vtab_cursor pCursor, sqlite3_int64 pRowid);
public delegate int dmxUpdate(sqlite3_vtab pVTab, int i2, sqlite3_value sv3, sqlite3_int64 v4);
public delegate int dmxBegin(sqlite3_vtab pVTab);
public delegate int dmxSync(sqlite3_vtab pVTab);
public delegate int dmxCommit(sqlite3_vtab pVTab);
public delegate int dmxRollback(sqlite3_vtab pVTab);
public delegate int dmxFindFunction(sqlite3_vtab pVtab, int nArg, string zName);
public delegate int dmxRename(sqlite3_vtab pVtab, string zNew);
#endif
//Faults
public delegate void void_function();
//Mem Methods
public delegate int dxMemInit( object o );
public delegate void dxMemShutdown( object o );
public delegate byte[] dxMalloc( int nSize );
public delegate int[] dxMallocInt( int nSize );
public delegate Mem dxMallocMem( Mem pMem );
public delegate void dxFree( ref byte[] pOld );
public delegate void dxFreeInt( ref int[] pOld );
public delegate void dxFreeMem( ref Mem pOld );
public delegate byte[] dxRealloc( byte[] pOld, int nSize );
public delegate int dxSize( byte[] pArray );
public delegate int dxRoundup( int nSize );
//Mutex Methods
public delegate int dxMutexInit();
public delegate int dxMutexEnd();
public delegate sqlite3_mutex dxMutexAlloc( int iNumber );
public delegate void dxMutexFree( sqlite3_mutex sm );
public delegate void dxMutexEnter( sqlite3_mutex sm );
public delegate int dxMutexTry( sqlite3_mutex sm );
public delegate void dxMutexLeave( sqlite3_mutex sm );
public delegate bool dxMutexHeld( sqlite3_mutex sm );
public delegate bool dxMutexNotheld( sqlite3_mutex sm );
public delegate object dxColumn( sqlite3_stmt pStmt, int i );
public delegate int dxColumn_I( sqlite3_stmt pStmt, int i );
// Walker Methods
public delegate int dxExprCallback( Walker W, ref Expr E ); /* Callback for expressions */
public delegate int dxSelectCallback( Walker W, Select S ); /* Callback for SELECTs */
// pcache Methods
public delegate int dxPC_Init( object NotUsed );
public delegate void dxPC_Shutdown( object NotUsed );
public delegate sqlite3_pcache dxPC_Create( int szPage, bool bPurgeable );
public delegate void dxPC_Cachesize( sqlite3_pcache pCache, int nCachesize );
public delegate int dxPC_Pagecount( sqlite3_pcache pCache );
public delegate PgHdr dxPC_Fetch( sqlite3_pcache pCache, u32 key, int createFlag );
public delegate void dxPC_Unpin( sqlite3_pcache pCache, PgHdr p2, bool discard );
public delegate void dxPC_Rekey( sqlite3_pcache pCache, PgHdr p2, u32 oldKey, u32 newKey );
public delegate void dxPC_Truncate( sqlite3_pcache pCache, u32 iLimit );
public delegate void dxPC_Destroy( ref sqlite3_pcache pCache );
public delegate void dxIter( PgHdr p );
#if NET_35 || NET_40
//API Simplifications -- Actions
public static Action<sqlite3_context, String, Int32, dxDel> ResultBlob = sqlite3_result_blob;
public static Action<sqlite3_context, Double> ResultDouble = sqlite3_result_double;
public static Action<sqlite3_context, String, Int32> ResultError = sqlite3_result_error;
public static Action<sqlite3_context, Int32> ResultErrorCode = sqlite3_result_error_code;
public static Action<sqlite3_context> ResultErrorNoMem = sqlite3_result_error_nomem;
public static Action<sqlite3_context> ResultErrorTooBig = sqlite3_result_error_toobig;
public static Action<sqlite3_context, Int32> ResultInt = sqlite3_result_int;
public static Action<sqlite3_context, Int64> ResultInt64 = sqlite3_result_int64;
public static Action<sqlite3_context> ResultNull = sqlite3_result_null;
public static Action<sqlite3_context, String, Int32, dxDel> ResultText = sqlite3_result_text;
public static Action<sqlite3_context, String, Int32, Int32, dxDel> ResultText_Offset = sqlite3_result_text;
public static Action<sqlite3_context, sqlite3_value> ResultValue = sqlite3_result_value;
public static Action<sqlite3_context, Int32> ResultZeroblob = sqlite3_result_zeroblob;
public static Action<sqlite3_context, Int32, String> SetAuxdata = sqlite3_set_auxdata;
//API Simplifications -- Functions
public delegate Int32 FinalizeDelegate( sqlite3_stmt pStmt );
public static FinalizeDelegate Finalize = sqlite3_finalize;
public static Func<sqlite3_stmt, Int32> ClearBindings = sqlite3_clear_bindings;
public static Func<sqlite3_stmt, Int32, Byte[]> ColumnBlob = sqlite3_column_blob;
public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes = sqlite3_column_bytes;
public static Func<sqlite3_stmt, Int32, Int32> ColumnBytes16 = sqlite3_column_bytes16;
public static Func<sqlite3_stmt, Int32> ColumnCount = sqlite3_column_count;
public static Func<sqlite3_stmt, Int32, String> ColumnDecltype = sqlite3_column_decltype;
public static Func<sqlite3_stmt, Int32, Double> ColumnDouble = sqlite3_column_double;
public static Func<sqlite3_stmt, Int32, Int32> ColumnInt = sqlite3_column_int;
public static Func<sqlite3_stmt, Int32, Int64> ColumnInt64 = sqlite3_column_int64;
public static Func<sqlite3_stmt, Int32, String> ColumnName = sqlite3_column_name;
public static Func<sqlite3_stmt, Int32, String> ColumnText = sqlite3_column_text;
public static Func<sqlite3_stmt, Int32, Int32> ColumnType = sqlite3_column_type;
public static Func<sqlite3_stmt, Int32, sqlite3_value> ColumnValue = sqlite3_column_value;
public static Func<sqlite3_stmt, Int32> DataCount = sqlite3_data_count;
public static Func<sqlite3_stmt, Int32> Reset = sqlite3_reset;
public static Func<sqlite3_stmt, Int32> Step = sqlite3_step;
public static Func<sqlite3_stmt, Int32, Byte[], Int32, dxDel, Int32> BindBlob = sqlite3_bind_blob;
public static Func<sqlite3_stmt, Int32, Double, Int32> BindDouble = sqlite3_bind_double;
public static Func<sqlite3_stmt, Int32, Int32, Int32> BindInt = sqlite3_bind_int;
public static Func<sqlite3_stmt, Int32, Int64, Int32> BindInt64 = sqlite3_bind_int64;
public static Func<sqlite3_stmt, Int32, Int32> BindNull = sqlite3_bind_null;
public static Func<sqlite3_stmt, Int32> BindParameterCount = sqlite3_bind_parameter_count;
public static Func<sqlite3_stmt, String, Int32> BindParameterIndex = sqlite3_bind_parameter_index;
public static Func<sqlite3_stmt, Int32, String> BindParameterName = sqlite3_bind_parameter_name;
public static Func<sqlite3_stmt, Int32, String, Int32, dxDel, Int32> BindText = sqlite3_bind_text;
public static Func<sqlite3_stmt, Int32, sqlite3_value, Int32> BindValue = sqlite3_bind_value;
public static Func<sqlite3_stmt, Int32, Int32, Int32> BindZeroblob = sqlite3_bind_zeroblob;
public delegate Int32 OpenDelegate( string zFilename, out sqlite3 ppDb );
public static Func<sqlite3, Int32> Close = sqlite3_close;
public static Func<sqlite3_stmt, sqlite3> DbHandle = sqlite3_db_handle;
public static Func<sqlite3, String> Errmsg = sqlite3_errmsg;
public static OpenDelegate Open = sqlite3_open;
public static Func<sqlite3, sqlite3_stmt, sqlite3_stmt> NextStmt = sqlite3_next_stmt;
public static Func<Int32> Shutdown = sqlite3_shutdown;
public static Func<sqlite3_stmt, Int32, Int32, Int32> StmtStatus = sqlite3_stmt_status;
public delegate Int32 PrepareDelegate( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, ref string pzTail );
public delegate Int32 PrepareDelegateNoTail( sqlite3 db, String zSql, Int32 nBytes, ref sqlite3_stmt ppStmt, Int32 iDummy );
public static PrepareDelegate Prepare = sqlite3_prepare;
public static PrepareDelegate PrepareV2 = sqlite3_prepare_v2;
public static PrepareDelegateNoTail PrepareV2NoTail = sqlite3_prepare_v2;
public static Func<sqlite3_context, Int32, Mem> AggregateContext = sqlite3_aggregate_context;
public static Func<sqlite3_context, Int32, Object> GetAuxdata = sqlite3_get_auxdata;
public static Func<sqlite3_context, sqlite3> ContextDbHandle = sqlite3_context_db_handle;
public static Func<sqlite3_context, Object> UserData = sqlite3_user_data;
public static Func<sqlite3_value, Byte[]> ValueBlob = sqlite3_value_blob;
public static Func<sqlite3_value, Int32> ValueBytes = sqlite3_value_bytes;
public static Func<sqlite3_value, Int32> ValueBytes16 = sqlite3_value_bytes16;
public static Func<sqlite3_value, Double> ValueDouble = sqlite3_value_double;
public static Func<sqlite3_value, Int32> ValueInt = sqlite3_value_int;
public static Func<sqlite3_value, Int64> ValueInt64 = sqlite3_value_int64;
public static Func<sqlite3_value, String> ValueText = sqlite3_value_text;
public static Func<sqlite3_value, Int32> ValueType = sqlite3_value_type;
#endif
}
}
#if( NET_35 && !NET_40) || WINDOWS_PHONE
namespace System
{
// Summary:
// Encapsulates a method that has four parameters and does not return a value.
//
// Parameters:
// arg1:
// The first parameter of the method that this delegate encapsulates.
//
// arg2:
// The second parameter of the method that this delegate encapsulates.
//
// arg3:
// The third parameter of the method that this delegate encapsulates.
//
// arg4:
// The fourth parameter of the method that this delegate encapsulates.
//
// arg5:
// The fifth parameter of the method that this delegate encapsulates.
//
// Type parameters:
// T1:
// The type of the first parameter of the method that this delegate encapsulates.
//
// T2:
// The type of the second parameter of the method that this delegate encapsulates.
//
// T3:
// The type of the third parameter of the method that this delegate encapsulates.
//
// T4:
// The type of the fourth parameter of the method that this delegate encapsulates.
//
// T5:
// The type of the fifth parameter of the method that this delegate encapsulates.
public delegate void Action<T1, T2, T3, T4, T5>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 );
// Summary:
// Encapsulates a method that has three parameters and returns a value of the
// type specified by the TResult parameter.
//
// Parameters:
// arg1:
// The first parameter of the method that this delegate encapsulates.
//
// arg2:
// The second parameter of the method that this delegate encapsulates.
//
// arg3:
// The third parameter of the method that this delegate encapsulates.
//
// arg4:
// The fourth parameter of the method that this delegate encapsulates.
//
// arg5:
// The fifth parameter of the method that this delegate encapsulates.
//
// Type parameters:
// T1:
// The type of the first parameter of the method that this delegate encapsulates.
//
// T2:
// The type of the second parameter of the method that this delegate encapsulates.
//
// T3:
// The type of the third parameter of the method that this delegate encapsulates.
//
// T4:
// The type of the fourth parameter of the method that this delegate encapsulates.
//
// T5:
// The type of the fifth parameter of the method that this delegate encapsulates.
//
// TResult:
// The type of the return value of the method that this delegate encapsulates.
//
// Returns:
// The return value of the method that this delegate encapsulates.
public delegate TResult Func<T1, T2, T3, T4, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4 );
public delegate TResult Func<T1, T2, T3, T4, T5, TResult>( T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5 );
}
#endif
| |
using System;
namespace Lucene.Net.Documents
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/// <summary>
/// Provides support for converting dates to strings and vice-versa.
/// The strings are structured so that lexicographic sorting orders
/// them by date, which makes them suitable for use as field values
/// and search terms.
///
/// <para/>This class also helps you to limit the resolution of your dates. Do not
/// save dates with a finer resolution than you really need, as then
/// <see cref="Search.TermRangeQuery"/> and <see cref="Search.PrefixQuery"/> will require more memory and become slower.
///
/// <para/>
/// Another approach is <see cref="Util.NumericUtils"/>, which provides
/// a sortable binary representation (prefix encoded) of numeric values, which
/// date/time are.
///
/// For indexing a <see cref="DateTime"/>, just get the <see cref="DateTime.Ticks"/> and index
/// this as a numeric value with <see cref="Int64Field"/> and use <see cref="Search.NumericRangeQuery{T}"/>
/// to query it.
/// </summary>
public static class DateTools
{
private static readonly string YEAR_FORMAT = "yyyy";
private static readonly string MONTH_FORMAT = "yyyyMM";
private static readonly string DAY_FORMAT = "yyyyMMdd";
private static readonly string HOUR_FORMAT = "yyyyMMddHH";
private static readonly string MINUTE_FORMAT = "yyyyMMddHHmm";
private static readonly string SECOND_FORMAT = "yyyyMMddHHmmss";
private static readonly string MILLISECOND_FORMAT = "yyyyMMddHHmmssfff";
// LUCENENET - not used
//private static readonly System.Globalization.Calendar calInstance = new System.Globalization.GregorianCalendar();
/// <summary>
/// Converts a <see cref="DateTime"/> to a string suitable for indexing.
/// </summary>
/// <param name="date"> the date to be converted </param>
/// <param name="resolution"> the desired resolution, see
/// <see cref="Round(DateTime, DateTools.Resolution)"/> </param>
/// <returns> a string in format <c>yyyyMMddHHmmssSSS</c> or shorter,
/// depending on <paramref name="resolution"/>; using GMT as timezone </returns>
public static string DateToString(DateTime date, Resolution resolution)
{
return TimeToString(date.Ticks / TimeSpan.TicksPerMillisecond, resolution);
}
/// <summary>
/// Converts a millisecond time to a string suitable for indexing.
/// </summary>
/// <param name="time"> the date expressed as milliseconds since January 1, 1970, 00:00:00 GMT (also known as the "epoch") </param>
/// <param name="resolution"> the desired resolution, see
/// <see cref="Round(long, DateTools.Resolution)"/> </param>
/// <returns> a string in format <c>yyyyMMddHHmmssSSS</c> or shorter,
/// depending on <paramref name="resolution"/>; using GMT as timezone </returns>
public static string TimeToString(long time, Resolution resolution)
{
DateTime date = new DateTime(Round(time, resolution));
if (resolution == Resolution.YEAR)
{
return date.ToString(YEAR_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.MONTH)
{
return date.ToString(MONTH_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.DAY)
{
return date.ToString(DAY_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.HOUR)
{
return date.ToString(HOUR_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.MINUTE)
{
return date.ToString(MINUTE_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.SECOND)
{
return date.ToString(SECOND_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
else if (resolution == Resolution.MILLISECOND)
{
return date.ToString(MILLISECOND_FORMAT, System.Globalization.CultureInfo.InvariantCulture);
}
throw new ArgumentException("unknown resolution " + resolution);
}
/// <summary>
/// Converts a string produced by <see cref="TimeToString(long, Resolution)"/> or
/// <see cref="DateToString(DateTime, Resolution)"/> back to a time, represented as the
/// number of milliseconds since January 1, 1970, 00:00:00 GMT (also known as the "epoch").
/// </summary>
/// <param name="dateString"> the date string to be converted </param>
/// <returns> the number of milliseconds since January 1, 1970, 00:00:00 GMT (also known as the "epoch")</returns>
/// <exception cref="FormatException"> if <paramref name="dateString"/> is not in the
/// expected format </exception>
public static long StringToTime(string dateString)
{
return StringToDate(dateString).Ticks;
}
/// <summary>
/// Converts a string produced by <see cref="TimeToString(long, Resolution)"/> or
/// <see cref="DateToString(DateTime, Resolution)"/> back to a time, represented as a
/// <see cref="DateTime"/> object.
/// </summary>
/// <param name="dateString"> the date string to be converted </param>
/// <returns> the parsed time as a <see cref="DateTime"/> object </returns>
/// <exception cref="FormatException"> if <paramref name="dateString"/> is not in the
/// expected format </exception>
public static DateTime StringToDate(string dateString)
{
DateTime date;
if (dateString.Length == 4)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
1, 1, 0, 0, 0, 0);
}
else if (dateString.Length == 6)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
1, 0, 0, 0, 0);
}
else if (dateString.Length == 8)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
0, 0, 0, 0);
}
else if (dateString.Length == 10)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
0, 0, 0);
}
else if (dateString.Length == 12)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
0, 0);
}
else if (dateString.Length == 14)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
Convert.ToInt16(dateString.Substring(12, 2)),
0);
}
else if (dateString.Length == 17)
{
date = new DateTime(Convert.ToInt16(dateString.Substring(0, 4)),
Convert.ToInt16(dateString.Substring(4, 2)),
Convert.ToInt16(dateString.Substring(6, 2)),
Convert.ToInt16(dateString.Substring(8, 2)),
Convert.ToInt16(dateString.Substring(10, 2)),
Convert.ToInt16(dateString.Substring(12, 2)),
Convert.ToInt16(dateString.Substring(14, 3)));
}
else
{
throw new FormatException("Input is not valid date string: " + dateString);
}
return date;
}
/// <summary>
/// Limit a date's resolution. For example, the date <c>2004-09-21 13:50:11</c>
/// will be changed to <c>2004-09-01 00:00:00</c> when using
/// <see cref="Resolution.MONTH"/>.
/// </summary>
/// <param name="date"> the date to be rounded </param>
/// <param name="resolution"> The desired resolution of the date to be returned </param>
/// <returns> the date with all values more precise than <paramref name="resolution"/>
/// set to 0 or 1 </returns>
public static DateTime Round(DateTime date, Resolution resolution)
{
return new DateTime(Round(date.Ticks / TimeSpan.TicksPerMillisecond, resolution));
}
/// <summary>
/// Limit a date's resolution. For example, the date <c>1095767411000</c>
/// (which represents 2004-09-21 13:50:11) will be changed to
/// <c>1093989600000</c> (2004-09-01 00:00:00) when using
/// <see cref="Resolution.MONTH"/>.
/// </summary>
/// <param name="time"> the time to be rounded </param>
/// <param name="resolution"> The desired resolution of the date to be returned </param>
/// <returns> the date with all values more precise than <paramref name="resolution"/>
/// set to 0 or 1, expressed as milliseconds since January 1, 1970, 00:00:00 GMT
/// (also known as the "epoch")</returns>
public static long Round(long time, Resolution resolution)
{
DateTime dt = new DateTime(time * TimeSpan.TicksPerMillisecond);
if (resolution == Resolution.YEAR)
{
dt = dt.AddMonths(1 - dt.Month);
dt = dt.AddDays(1 - dt.Day);
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MONTH)
{
dt = dt.AddDays(1 - dt.Day);
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.DAY)
{
dt = dt.AddHours(0 - dt.Hour);
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.HOUR)
{
dt = dt.AddMinutes(0 - dt.Minute);
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MINUTE)
{
dt = dt.AddSeconds(0 - dt.Second);
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.SECOND)
{
dt = dt.AddMilliseconds(0 - dt.Millisecond);
}
else if (resolution == Resolution.MILLISECOND)
{
// don't cut off anything
}
else
{
throw new System.ArgumentException("unknown resolution " + resolution);
}
return dt.Ticks;
}
/// <summary>
/// Specifies the time granularity. </summary>
public enum Resolution
{
/// <summary>
/// Limit a date's resolution to year granularity. </summary>
YEAR = 4,
/// <summary>
/// Limit a date's resolution to month granularity. </summary>
MONTH = 6,
/// <summary>
/// Limit a date's resolution to day granularity. </summary>
DAY = 8,
/// <summary>
/// Limit a date's resolution to hour granularity. </summary>
HOUR = 10,
/// <summary>
/// Limit a date's resolution to minute granularity. </summary>
MINUTE = 12,
/// <summary>
/// Limit a date's resolution to second granularity. </summary>
SECOND = 14,
/// <summary>
/// Limit a date's resolution to millisecond granularity. </summary>
MILLISECOND = 17
}
}
}
| |
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if !CLR2
using System.Linq.Expressions;
#else
using Microsoft.Scripting.Ast;
#endif
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using AstUtils = System.Management.Automation.Interpreter.Utils;
#if CORECLR
// Use stub for IRuntimeVariables.
using Microsoft.PowerShell.CoreClr.Stubs;
#endif
namespace System.Management.Automation.Interpreter
{
/// <summary>
/// Visits a LambdaExpression, replacing the constants with direct accesses
/// to their StrongBox fields. This is very similar to what
/// ExpressionQuoter does for LambdaCompiler.
///
/// Also inserts debug information tracking similar to what the interpreter
/// would do.
/// </summary>
internal sealed class LightLambdaClosureVisitor : ExpressionVisitor
{
/// <summary>
/// Local variable mapping.
/// </summary>
private readonly Dictionary<ParameterExpression, LocalVariable> _closureVars;
/// <summary>
/// The variable that holds onto the StrongBox{object}[] closure from
/// the interpreter
/// </summary>
private readonly ParameterExpression _closureArray;
/// <summary>
/// A stack of variables that are defined in nested scopes. We search
/// this first when resolving a variable in case a nested scope shadows
/// one of our variable instances.
/// </summary>
private readonly Stack<HashSet<ParameterExpression>> _shadowedVars = new Stack<HashSet<ParameterExpression>>();
private LightLambdaClosureVisitor(Dictionary<ParameterExpression, LocalVariable> closureVariables, ParameterExpression closureArray)
{
Assert.NotNull(closureVariables, closureArray);
_closureArray = closureArray;
_closureVars = closureVariables;
}
/// <summary>
/// Walks the lambda and produces a higher order function, which can be
/// used to bind the lambda to a closure array from the interpreter.
/// </summary>
/// <param name="lambda">The lambda to bind.</param>
/// <param name="closureVariables">Variables which are being accessed defined in the outer scope.</param>
/// <returns>A delegate that can be called to produce a delegate bound to the passed in closure array.</returns>
internal static Func<StrongBox<object>[], Delegate> BindLambda(LambdaExpression lambda, Dictionary<ParameterExpression, LocalVariable> closureVariables)
{
// 1. Create rewriter
var closure = Expression.Parameter(typeof(StrongBox<object>[]), "closure");
var visitor = new LightLambdaClosureVisitor(closureVariables, closure);
// 2. Visit the lambda
lambda = (LambdaExpression)visitor.Visit(lambda);
// 3. Create a higher-order function which fills in the parameters
var result = Expression.Lambda<Func<StrongBox<object>[], Delegate>>(lambda, closure);
// 4. Compile it
return result.Compile();
}
#region closures
protected override Expression VisitLambda<T>(Expression<T> node)
{
_shadowedVars.Push(new HashSet<ParameterExpression>(node.Parameters));
Expression b = Visit(node.Body);
_shadowedVars.Pop();
if (b == node.Body)
{
return node;
}
return Expression.Lambda<T>(b, node.Name, node.TailCall, node.Parameters);
}
protected override Expression VisitBlock(BlockExpression node)
{
if (node.Variables.Count > 0)
{
_shadowedVars.Push(new HashSet<ParameterExpression>(node.Variables));
}
var b = Visit(node.Expressions);
if (node.Variables.Count > 0)
{
_shadowedVars.Pop();
}
if (b == node.Expressions)
{
return node;
}
return Expression.Block(node.Variables, b);
}
protected override CatchBlock VisitCatchBlock(CatchBlock node)
{
if (node.Variable != null)
{
_shadowedVars.Push(new HashSet<ParameterExpression>(new[] { node.Variable }));
}
Expression b = Visit(node.Body);
Expression f = Visit(node.Filter);
if (node.Variable != null)
{
_shadowedVars.Pop();
}
if (b == node.Body && f == node.Filter)
{
return node;
}
return Expression.MakeCatchBlock(node.Test, node.Variable, b, f);
}
protected override Expression VisitRuntimeVariables(RuntimeVariablesExpression node)
{
int count = node.Variables.Count;
var boxes = new List<Expression>();
var vars = new List<ParameterExpression>();
var indexes = new int[count];
for (int i = 0; i < count; i++)
{
Expression box = GetClosureItem(node.Variables[i], false);
if (box == null)
{
indexes[i] = vars.Count;
vars.Add(node.Variables[i]);
}
else
{
indexes[i] = -1 - boxes.Count;
boxes.Add(box);
}
}
// No variables were rewritten. Just return the original node.
if (boxes.Count == 0)
{
return node;
}
var boxesArray = Expression.NewArrayInit(typeof(IStrongBox), boxes);
// All of them were rewritten. Just return the array, wrapped in a
// read-only collection.
if (vars.Count == 0)
{
return Expression.Invoke(
Expression.Constant((Func<IStrongBox[], IRuntimeVariables>)RuntimeVariables.Create),
boxesArray
);
}
// Otherwise, we need to return an object that merges them
Func<IRuntimeVariables, IRuntimeVariables, int[], IRuntimeVariables> helper = MergedRuntimeVariables.Create;
return Expression.Invoke(AstUtils.Constant(helper), Expression.RuntimeVariables(vars), boxesArray, AstUtils.Constant(indexes));
}
protected override Expression VisitParameter(ParameterExpression node)
{
Expression closureItem = GetClosureItem(node, true);
if (closureItem == null)
{
return node;
}
// Convert can go away if we switch to strongly typed StrongBox
return AstUtils.Convert(closureItem, node.Type);
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (node.NodeType == ExpressionType.Assign &&
node.Left.NodeType == ExpressionType.Parameter)
{
var variable = (ParameterExpression)node.Left;
Expression closureItem = GetClosureItem(variable, true);
if (closureItem != null)
{
// We need to convert to object to store the value in the box.
return Expression.Block(
new[] { variable },
Expression.Assign(variable, Visit(node.Right)),
Expression.Assign(closureItem, AstUtils.Convert(variable, typeof(object))),
variable
);
}
}
return base.VisitBinary(node);
}
private Expression GetClosureItem(ParameterExpression variable, bool unbox)
{
// Skip variables that are shadowed by a nested scope/lambda
foreach (HashSet<ParameterExpression> hidden in _shadowedVars)
{
if (hidden.Contains(variable))
{
return null;
}
}
LocalVariable loc;
if (!_closureVars.TryGetValue(variable, out loc))
{
throw new InvalidOperationException("unbound variable: " + variable.Name);
}
var result = loc.LoadFromArray(null, _closureArray);
return (unbox) ? LightCompiler.Unbox(result) : result;
}
protected override Expression VisitExtension(Expression node)
{
// Reduce extensions now so we can find embedded variables
return Visit(node.ReduceExtensions());
}
#region MergedRuntimeVariables
/// <summary>
/// Provides a list of variables, supporing read/write of the values
/// </summary>
private sealed class MergedRuntimeVariables : IRuntimeVariables
{
private readonly IRuntimeVariables _first;
private readonly IRuntimeVariables _second;
// For reach item, the index into the first or second list
// Positive values mean the first array, negative means the second
private readonly int[] _indexes;
private MergedRuntimeVariables(IRuntimeVariables first, IRuntimeVariables second, int[] indexes)
{
_first = first;
_second = second;
_indexes = indexes;
}
internal static IRuntimeVariables Create(IRuntimeVariables first, IRuntimeVariables second, int[] indexes)
{
return new MergedRuntimeVariables(first, second, indexes);
}
int IRuntimeVariables.Count
{
get { return _indexes.Length; }
}
object IRuntimeVariables.this[int index]
{
get
{
index = _indexes[index];
return (index >= 0) ? _first[index] : _second[-1 - index];
}
set
{
index = _indexes[index];
if (index >= 0)
{
_first[index] = value;
}
else
{
_second[-1 - index] = value;
}
}
}
}
#endregion
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.