context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
namespace Microsoft.Protocols.TestSuites.MS_MEETS
{
using Microsoft.Protocols.TestSuites.Common;
using Microsoft.Protocols.TestTools;
using System;
using System.Net;
using System.Web.Services.Protocols;
/// <summary>
/// MEETSAdapter implementation
/// </summary>
public partial class MS_MEETSAdapter : ManagedAdapterBase, IMS_MEETSAdapter
{
/// <summary>
/// An instance of MeetingsSoap class, use to call the meetings web service.
/// </summary>
private MeetingsSoap service;
/// <summary>
/// Gets or sets the destination Url of web service operation.
/// </summary>
/// <value>Destination Url of web service operation.</value>
public string Url
{
get
{
return this.service.Url;
}
set
{
this.service.Url = value;
}
}
/// <summary>
/// Overrides IAdapter's Initialize().
/// </summary>
/// <param name="testSite">A parameter represents an ITestSite instance.</param>
public override void Initialize(ITestSite testSite)
{
base.Initialize(testSite);
testSite.DefaultProtocolDocShortName = "MS-MEETS";
// Initialize the MeetingSoap.
this.service = Proxy.CreateProxy<MeetingsSoap>(this.Site);
// Load common configuration.
this.LoadCommonConfiguration();
// Load SHOULDMAY configuration
this.LoadCurrentSutSHOULDMAYConfiguration();
this.service.Url = Common.GetConfigurationPropertyValue("TargetServiceUrl", this.Site);
string userName = Common.GetConfigurationPropertyValue("UserName", this.Site);
string password = Common.GetConfigurationPropertyValue("Password", this.Site);
string domain = Common.GetConfigurationPropertyValue("Domain", this.Site);
this.service.Credentials = new NetworkCredential(userName, password, domain);
this.SetSoapVersion(this.service);
// When request Url include HTTPS prefix, avoid closing base connection.
// Local client will accept all certificates after executing this function.
TransportProtocol transport = Common.GetConfigurationPropertyValue<TransportProtocol>("TransportType", this.Site);
if (transport == TransportProtocol.HTTPS)
{
Common.AcceptServerCertificate();
}
// Configure the service timeout.
string soapTimeOut = Common.GetConfigurationPropertyValue("ServiceTimeOut", this.Site);
// 60000 means the configure SOAP Timeout is in milliseconds.
this.service.Timeout = Convert.ToInt32(soapTimeOut) * 60000;
}
/// <summary>
/// Adds a meeting to an existing workspace.
/// </summary>
/// <param name="organizerEmail">The e-mail address of the meeting organizer.</param>
/// <param name="uid">A unique identifier represents this meeting</param>
/// <param name="sequence">The sequence or revision number of this meeting instance. Null if not specified.</param>
/// <param name="utcDateStamp">The time that this meeting instance was created.</param>
/// <param name="title">The subject of this meeting.</param>
/// <param name="location">The physical or virtual location in which this meeting is to take place.</param>
/// <param name="utcDateStart">The time that this meeting begins.</param>
/// <param name="utcDateEnd">The time that this meeting ends.</param>
/// <param name="nonGregorian">Whether the meeting organizer is using the Gregorian calendar. Null if not specified.</param>
/// <returns>The aggregation of AddMeetingResponseAddMeetingResult response or SoapException thrown.</returns>
public SoapResult<AddMeetingResponseAddMeetingResult> AddMeeting(string organizerEmail, string uid, uint? sequence, DateTime? utcDateStamp, string title, string location, DateTime utcDateStart, DateTime utcDateEnd, bool? nonGregorian)
{
AddMeetingResponseAddMeetingResult result = null;
SoapException exception = null;
try
{
// Call AddMeeting method.
result = this.service.AddMeeting(organizerEmail, uid, sequence ?? 0, sequence.HasValue, utcDateStamp ?? default(DateTime), utcDateStamp.HasValue, title, location, utcDateStart, utcDateEnd, nonGregorian ?? false, nonGregorian.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyAddMeetingResponse(result);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<AddMeetingResponseAddMeetingResult>(result, exception);
}
/// <summary>
/// Adds a meeting to an existing workspace based on a calendar object.
/// </summary>
/// <param name="organizerEmail">The e-mail address of the meeting organizer.</param>
/// <param name="icalText">Information about the meeting instance to add.</param>
/// <returns>The aggregation of AddMeetingFromICalResponseAddMeetingFromICalResult response or SoapException thrown.</returns>
public SoapResult<AddMeetingFromICalResponseAddMeetingFromICalResult> AddMeetingFromICal(string organizerEmail, string icalText)
{
AddMeetingFromICalResponseAddMeetingFromICalResult result = null;
SoapException exception = null;
try
{
// Call AddMeetingFromIcal method.
result = this.service.AddMeetingFromICal(organizerEmail, icalText);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyAddMeetingFromICalResponse(result);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<AddMeetingFromICalResponseAddMeetingFromICalResult>(result, exception);
}
/// <summary>
/// Creates a new meeting workspace subsite.
/// </summary>
/// <param name="title">The title of the new meeting workspace.</param>
/// <param name="templateName">The name of the template to use for the new meeting workspace.</param>
/// <param name="lcid">The locale ID for the new workspace. Null if not specified.</param>
/// <param name="timeZoneInformation">The time zone on the system of the meeting organizer.</param>
/// <returns>The aggregation of CreateWorkspaceResponseCreateWorkspaceResult response or SoapException thrown.</returns>
public SoapResult<CreateWorkspaceResponseCreateWorkspaceResult> CreateWorkspace(string title, string templateName, uint? lcid, TimeZoneInf timeZoneInformation)
{
CreateWorkspaceResponseCreateWorkspaceResult result = null;
SoapException exception = null;
try
{
// Call CreateWorkspace method.
result = this.service.CreateWorkspace(title, templateName, lcid ?? 0, lcid.HasValue, timeZoneInformation);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyCreateWorkspaceResponse(result);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<CreateWorkspaceResponseCreateWorkspaceResult>(result, exception);
}
/// <summary>
/// Deletes a workspace.
/// </summary>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> DeleteWorkspace()
{
SoapException exception = null;
try
{
// call DeleteWorkspace method.
this.service.DeleteWorkspace();
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyDeleteWorkspaceResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Queries information from a Web site about meeting workspaces on it or information about a meeting workspace itself.
/// </summary>
/// <param name="requestFlags">Bit flags that specify what information to request from the Web site. Null if not specified.</param>
/// <param name="lcid">The locale ID of the meeting workspace templates to return. Null if not specified.</param>
/// <returns>The aggregation of GetMeetingsInformationResponseGetMeetingsInformationResult response or SoapException thrown.</returns>
public SoapResult<GetMeetingsInformationResponseGetMeetingsInformationResult> GetMeetingsInformation(MeetingInfoTypes? requestFlags, uint? lcid)
{
GetMeetingsInformationResponseGetMeetingsInformationResult result = null;
SoapException exception = null;
try
{
// Call GetMeetingsInformation method.
result = this.service.GetMeetingsInformation((uint)(requestFlags ?? 0), requestFlags.HasValue, lcid ?? 0, lcid.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyGetMeetingsInformationResponse(result, requestFlags);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<GetMeetingsInformationResponseGetMeetingsInformationResult>(result, exception);
}
/// <summary>
/// Gets a list of created meeting workspace subsites from a parent web.
/// </summary>
/// <param name="recurring">Whether the meeting workspaces returned are limited to those that can be associated with a recurring meeting. Null if not specified.</param>
/// <returns>The aggregation of GetMeetingWorkspacesResponseGetMeetingWorkspacesResult response or SoapException thrown.</returns>
public SoapResult<GetMeetingWorkspacesResponseGetMeetingWorkspacesResult> GetMeetingWorkspaces(bool? recurring)
{
GetMeetingWorkspacesResponseGetMeetingWorkspacesResult result = null;
SoapException exception = null;
try
{
// Call GetMeetingWorkspaces method.
result = this.service.GetMeetingWorkspaces(recurring ?? false, recurring.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyGetMeetingWorkspacesResponse(result);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<GetMeetingWorkspacesResponseGetMeetingWorkspacesResult>(result, exception);
}
/// <summary>
/// Deletes a meeting from an existing workspace.
/// </summary>
/// <param name="recurrenceId">The particular instance of a recurring meeting to delete. Null if not specified.</param>
/// <param name="uid">A unique identifier represents the meeting to delete.</param>
/// <param name="sequence">The sequence number of a meeting instance to delete. Null if not specified.</param>
/// <param name="utcDateStamp">The time stamp for when this meeting instance was deleted. Null if not specified.</param>
/// <param name="cancelMeeting">Whether the meeting is being cancelled in addition to being deleted from the workspace. Null if not specified.</param>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> RemoveMeeting(uint? recurrenceId, string uid, uint? sequence, DateTime? utcDateStamp, bool? cancelMeeting)
{
SoapException exception = null;
try
{
// Call RemoveMeeting method.
this.service.RemoveMeeting(recurrenceId ?? 0, recurrenceId.HasValue, uid, sequence ?? 0, sequence.HasValue, utcDateStamp ?? default(DateTime), utcDateStamp.HasValue, cancelMeeting ?? false, cancelMeeting.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyRemoveMeetingResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Restores a previously deleted meeting to a workspace.
/// </summary>
/// <param name="uid">A unique identifier represents the meeting to restore.</param>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> RestoreMeeting(string uid)
{
SoapException exception = null;
try
{
// Call RestoreMeeting method.
this.service.RestoreMeeting(uid);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyRestoreMeetingResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Specifies attendee response to a meeting request in a workspace.
/// </summary>
/// <param name="attendeeEmail">The e-mail address of the attendee responding.</param>
/// <param name="recurrenceId">The particular instance of a recurring meeting associated with the response. Null if not specified.</param>
/// <param name="uid">A unique identifier represents the meeting associated with the response.</param>
/// <param name="sequence">The sequence number of a meeting instance associated with the response. Null if not specified.</param>
/// <param name="utcDateTimeOrganizerCriticalChange">The time stamp at which the attendee responded to the meeting, translated to the time zone of the meeting organizer. Null if not specified.</param>
/// <param name="utcDateTimeAttendeeCriticalChange">The time stamp that contains the time at which the attendee responded to the meeting, translated to the time zone of the attendee. Null if not specified.</param>
/// <param name="response">Attendee acceptance or rejection of the meeting invitation. Null if not specified.</param>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> SetAttendeeResponse(string attendeeEmail, uint? recurrenceId, string uid, uint? sequence, DateTime? utcDateTimeOrganizerCriticalChange, DateTime? utcDateTimeAttendeeCriticalChange, AttendeeResponse? response)
{
SoapException exception = null;
try
{
// Call SetAttendeeResponse method.
this.service.SetAttendeeResponse(
attendeeEmail,
recurrenceId ?? 0,
recurrenceId.HasValue,
uid,
sequence ?? 0,
sequence.HasValue,
utcDateTimeOrganizerCriticalChange ?? default(DateTime),
utcDateTimeOrganizerCriticalChange.HasValue,
utcDateTimeAttendeeCriticalChange ?? default(DateTime),
utcDateTimeAttendeeCriticalChange.HasValue,
response ?? 0,
response.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifySetAttendeeResponseResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Specifies a user friendly name for a workspace.
/// </summary>
/// <param name="title">The new title of the meeting workspace.</param>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> SetWorkspaceTitle(string title)
{
SoapException exception = null;
try
{
// Call SetWorkspaceTitle method.
this.service.SetWorkspaceTitle(title);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifySetWorkspaceTitleResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Updates content of a meeting in a workspace.
/// </summary>
/// <param name="uid">A unique identifier represents the meeting to update.</param>
/// <param name="sequence">The updated sequence number of this meeting. Null if not specified.</param>
/// <param name="utcDateStamp">The time at which the meeting is being updated. Null if not specified.</param>
/// <param name="title">The updated subject of this meeting.</param>
/// <param name="location">The updated physical or virtual location in which this meeting is to take place.</param>
/// <param name="utcDateStart">The updated beginning time of this meeting.</param>
/// <param name="utcDateEnd">The updated end time of this meeting.</param>
/// <param name="nonGregorian">Whether the updated meeting is not in the Gregorian calendar. Null if not specified.</param>
/// <returns>The aggregation of empty response or SoapException thrown.</returns>
public SoapResult<Null> UpdateMeeting(string uid, uint? sequence, DateTime? utcDateStamp, string title, string location, DateTime utcDateStart, DateTime utcDateEnd, bool? nonGregorian)
{
SoapException exception = null;
try
{
// Call UpdateMeeting method.
this.service.UpdateMeeting(
uid,
sequence ?? 0,
sequence.HasValue,
utcDateStamp ?? default(DateTime),
utcDateStamp.HasValue,
title,
location,
utcDateStart,
utcDateEnd,
nonGregorian ?? false,
nonGregorian.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyUpdateMeetingResponse();
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<Null>(Null.Value, exception);
}
/// <summary>
/// Updates content of a meeting in a workspace base on a calendar object.
/// </summary>
/// <param name="icalText">Updated information about the meeting instance.</param>
/// <param name="ignoreAttendees">Whether this is a scheduling-only update, or an update that affects attendees. Null if not specified.</param>
/// <returns>The aggregation of UpdateMeetingFromICalResponseUpdateMeetingFromICalResultUpdateMeetingFromICal response or SoapException thrown.</returns>
public SoapResult<UpdateMeetingFromICalResponseUpdateMeetingFromICalResult> UpdateMeetingFromICal(string icalText, bool? ignoreAttendees)
{
UpdateMeetingFromICalResponseUpdateMeetingFromICalResult result = null;
SoapException exception = null;
try
{
// Call UpdateMeetingFromICal method.
result = this.service.UpdateMeetingFromICal(icalText, ignoreAttendees ?? false, ignoreAttendees.HasValue);
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
this.ValidateAndCaptureCommonMessageSyntax();
this.VerifyUpdateMeetingFromICalResponse(result);
}
catch (SoapException ex)
{
exception = ex;
// As response successfully returned, the transport related requirements can be captured.
this.CaptureTransportRelatedRequirements();
// Validate soap fault message structure and capture related requirements.
this.ValidateAndCaptureSoapFaultRequirements(exception);
}
return new SoapResult<UpdateMeetingFromICalResponseUpdateMeetingFromICalResult>(result, exception);
}
/// <summary>
/// A method used to load Common Configuration
/// </summary>
private void LoadCommonConfiguration()
{
// Merge the common configuration into local configuration
string conmmonConfigFileName = Common.GetConfigurationPropertyValue("CommonConfigurationFileName", this.Site);
// Execute the merge the common configuration
Common.MergeGlobalConfig(conmmonConfigFileName, this.Site);
Common.CheckCommonProperties(this.Site, true);
}
/// <summary>
/// A method used to load SHOULDMAY Configuration according to the current SUT version
/// </summary>
private void LoadCurrentSutSHOULDMAYConfiguration()
{
Common.MergeSHOULDMAYConfig(this.Site);
}
/// <summary>
/// Set the SOAP version according to the SoapVersion property.
/// </summary>
/// <param name="meetingProxy">set meeting proxy</param>
private void SetSoapVersion(MeetingsSoap meetingProxy)
{
SoapVersion soapVersion = Common.GetConfigurationPropertyValue<SoapVersion>("SoapVersion", this.Site);
switch (soapVersion)
{
case SoapVersion.SOAP11:
{
meetingProxy.SoapVersion = SoapProtocolVersion.Soap11;
break;
}
default:
{
meetingProxy.SoapVersion = SoapProtocolVersion.Soap12;
break;
}
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// ReSharper disable UnusedMember.Global
// ReSharper disable RedundantCast
namespace System.Management.Automation
{
internal static class Boxed
{
internal static object True = (object)true;
internal static object False = (object)false;
}
internal static class IntOps
{
internal static object Add(int lhs, int rhs)
{
long result = (long)lhs + (long)rhs;
if (result <= int.MaxValue && result >= int.MinValue)
{
return (int)result;
}
return (double)result;
}
internal static object Sub(int lhs, int rhs)
{
long result = (long)lhs - (long)rhs;
if (result <= int.MaxValue && result >= int.MinValue)
{
return (int)result;
}
return (double)result;
}
internal static object Multiply(int lhs, int rhs)
{
long result = (long)lhs * (long)rhs;
if (result <= int.MaxValue && result >= int.MinValue)
{
return (int)result;
}
return (double)result;
}
internal static object Divide(int lhs, int rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
if (lhs == int.MinValue && rhs == -1)
{
// The result of this operation can't fit in an int, so promote.
return (double)lhs / (double)rhs;
}
// If the remainder is 0, stay with integer division, otherwise use doubles.
if ((lhs % rhs) == 0)
{
return lhs / rhs;
}
return (double)lhs / (double)rhs;
}
internal static object Remainder(int lhs, int rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
if (lhs == int.MinValue && rhs == -1)
{
// The CLR raises an overflow exception for these values. PowerShell typically
// promotes whenever things overflow, so we just hard code the result value.
return 0;
}
return lhs % rhs;
}
internal static object CompareEq(int lhs, int rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(int lhs, int rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(int lhs, int rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(int lhs, int rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(int lhs, int rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(int lhs, int rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
internal static object[] Range(int lower, int upper)
{
int absRange = Math.Abs(checked(upper - lower));
object[] ra = new object[absRange + 1];
if (lower > upper)
{
// 3 .. 1 => 3 2 1
for (int offset = 0; offset < ra.Length; offset++)
ra[offset] = lower--;
}
else
{
// 1 .. 3 => 1 2 3
for (int offset = 0; offset < ra.Length; offset++)
ra[offset] = lower++;
}
return ra;
}
}
internal static class UIntOps
{
internal static object Add(uint lhs, uint rhs)
{
ulong result = (ulong)lhs + (ulong)rhs;
if (result <= uint.MaxValue)
{
return (uint)result;
}
return (double)result;
}
internal static object Sub(uint lhs, uint rhs)
{
long result = (long)lhs - (long)rhs;
if (result >= uint.MinValue)
{
return (uint)result;
}
return (double)result;
}
internal static object Multiply(uint lhs, uint rhs)
{
ulong result = (ulong)lhs * (ulong)rhs;
if (result <= uint.MaxValue)
{
return (uint)result;
}
return (double)result;
}
internal static object Divide(uint lhs, uint rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
// If the remainder is 0, stay with integer division, otherwise use doubles.
if ((lhs % rhs) == 0)
{
return lhs / rhs;
}
return (double)lhs / (double)rhs;
}
internal static object Remainder(uint lhs, uint rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
return lhs % rhs;
}
internal static object CompareEq(uint lhs, uint rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(uint lhs, uint rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(uint lhs, uint rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(uint lhs, uint rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(uint lhs, uint rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(uint lhs, uint rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
}
internal static class LongOps
{
internal static object Add(long lhs, long rhs)
{
decimal result = (decimal)lhs + (decimal)rhs;
if (result <= long.MaxValue && result >= long.MinValue)
{
return (long)result;
}
return (double)result;
}
internal static object Sub(long lhs, long rhs)
{
decimal result = (decimal)lhs - (decimal)rhs;
if (result <= long.MaxValue && result >= long.MinValue)
{
return (long)result;
}
return (double)result;
}
internal static object Multiply(long lhs, long rhs)
{
System.Numerics.BigInteger biLhs = lhs;
System.Numerics.BigInteger biRhs = rhs;
System.Numerics.BigInteger biResult = biLhs * biRhs;
if (biResult <= long.MaxValue && biResult >= long.MinValue)
{
return (long)biResult;
}
return (double)biResult;
}
internal static object Divide(long lhs, long rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
// Special case.
// This changes the sign of the min value, causing an integer overflow.
if (lhs == long.MinValue && rhs == -1)
{
return (double)lhs / (double)rhs;
}
// If the remainder is 0, stay with integer division, otherwise use doubles.
if ((lhs % rhs) == 0)
{
return lhs / rhs;
}
return (double)lhs / (double)rhs;
}
internal static object Remainder(long lhs, long rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
if (lhs == long.MinValue && rhs == -1)
{
// The CLR raises an overflow exception for these values. PowerShell typically
// promotes whenever things overflow, so we just hard code the result value.
return 0L;
}
return lhs % rhs;
}
internal static object CompareEq(long lhs, long rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(long lhs, long rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(long lhs, long rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(long lhs, long rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(long lhs, long rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(long lhs, long rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
}
internal static class ULongOps
{
internal static object Add(ulong lhs, ulong rhs)
{
decimal result = (decimal)lhs + (decimal)rhs;
if (result <= ulong.MaxValue)
{
return (ulong)result;
}
return (double)result;
}
internal static object Sub(ulong lhs, ulong rhs)
{
decimal result = (decimal)lhs - (decimal)rhs;
if (result >= ulong.MinValue)
{
return (ulong)result;
}
return (double)result;
}
internal static object Multiply(ulong lhs, ulong rhs)
{
System.Numerics.BigInteger biLhs = lhs;
System.Numerics.BigInteger biRhs = rhs;
System.Numerics.BigInteger biResult = biLhs * biRhs;
if (biResult <= ulong.MaxValue)
{
return (ulong)biResult;
}
return (double)biResult;
}
internal static object Divide(ulong lhs, ulong rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
// If the remainder is 0, stay with integer division, otherwise use doubles.
if ((lhs % rhs) == 0)
{
return lhs / rhs;
}
return (double)lhs / (double)rhs;
}
internal static object Remainder(ulong lhs, ulong rhs)
{
// TBD: is it better to cover the special cases explicitly, or
// alternatively guard with try/catch?
if (rhs == 0)
{
DivideByZeroException dbze = new DivideByZeroException();
throw new RuntimeException(dbze.Message, dbze);
}
return lhs % rhs;
}
internal static object CompareEq(ulong lhs, ulong rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(ulong lhs, ulong rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(ulong lhs, ulong rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(ulong lhs, ulong rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(ulong lhs, ulong rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(ulong lhs, ulong rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
}
internal static class DecimalOps
{
internal static object Add(decimal lhs, decimal rhs)
{
try
{
return checked(lhs + rhs);
}
catch (OverflowException oe)
{
throw new RuntimeException(oe.Message, oe);
}
}
internal static object Sub(decimal lhs, decimal rhs)
{
try
{
return checked(lhs - rhs);
}
catch (OverflowException oe)
{
throw new RuntimeException(oe.Message, oe);
}
}
internal static object Multiply(decimal lhs, decimal rhs)
{
try
{
return checked(lhs * rhs);
}
catch (OverflowException oe)
{
throw new RuntimeException(oe.Message, oe);
}
}
internal static object Divide(decimal lhs, decimal rhs)
{
try
{
return checked(lhs / rhs);
}
catch (OverflowException oe)
{
throw new RuntimeException(oe.Message, oe);
}
catch (DivideByZeroException dbze)
{
throw new RuntimeException(dbze.Message, dbze);
}
}
internal static object Remainder(decimal lhs, decimal rhs)
{
try
{
return checked(lhs % rhs);
}
catch (OverflowException oe)
{
throw new RuntimeException(oe.Message, oe);
}
catch (DivideByZeroException dbze)
{
throw new RuntimeException(dbze.Message, dbze);
}
}
internal static object BNot(decimal val)
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return unchecked(~LanguagePrimitives.ConvertTo<int>(val));
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return unchecked(~LanguagePrimitives.ConvertTo<uint>(val));
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return unchecked(~LanguagePrimitives.ConvertTo<long>(val));
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return unchecked(~LanguagePrimitives.ConvertTo<ulong>(val));
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(int));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object BOr(decimal lhs, decimal rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l | r);
}
}
return l | r;
}
internal static object BXor(decimal lhs, decimal rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l ^ r);
}
}
return l ^ r;
}
internal static object BAnd(decimal lhs, decimal rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l & r);
}
}
return l & r;
}
// This had to be done because if we try to cast a negative decimal number to unsigned, we get an OverFlowException
// We had to cast them to long (if they are negative) and then promote everything to ULong.
// While returning the result, we can return either signed or unsigned depending on the input.
private static ulong ConvertToUlong(decimal val)
{
if (val < 0)
{
long lValue = LanguagePrimitives.ConvertTo<long>(val);
return unchecked((ulong)lValue);
}
return LanguagePrimitives.ConvertTo<ulong>(val);
}
internal static object LeftShift(decimal val, int count)
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<int>(val) << count);
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<uint>(val) << count);
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<long>(val) << count);
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<ulong>(val) << count);
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(int));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object RightShift(decimal val, int count)
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<int>(val) >> count);
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<uint>(val) >> count);
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<long>(val) >> count);
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return unchecked(LanguagePrimitives.ConvertTo<ulong>(val) >> count);
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(int));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object CompareEq(decimal lhs, decimal rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(decimal lhs, decimal rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(decimal lhs, decimal rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(decimal lhs, decimal rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(decimal lhs, decimal rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(decimal lhs, decimal rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
private static object CompareWithDouble(decimal left, double right,
Func<double, double, object> doubleComparer,
Func<decimal, decimal, object> decimalComparer)
{
decimal rightAsDecimal;
try
{
rightAsDecimal = (decimal)right;
}
catch (OverflowException)
{
return doubleComparer((double)left, right);
}
return decimalComparer(left, rightAsDecimal);
}
private static object CompareWithDouble(double left, decimal right,
Func<double, double, object> doubleComparer,
Func<decimal, decimal, object> decimalComparer)
{
decimal leftAsDecimal;
try
{
leftAsDecimal = (decimal)left;
}
catch (OverflowException)
{
return doubleComparer(left, (double)right);
}
return decimalComparer(leftAsDecimal, right);
}
internal static object CompareEq1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); }
internal static object CompareNe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); }
internal static object CompareLt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); }
internal static object CompareLe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); }
internal static object CompareGt1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); }
internal static object CompareGe1(double lhs, decimal rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); }
internal static object CompareEq2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareEq, CompareEq); }
internal static object CompareNe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareNe, CompareNe); }
internal static object CompareLt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLt, CompareLt); }
internal static object CompareLe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareLe, CompareLe); }
internal static object CompareGt2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGt, CompareGt); }
internal static object CompareGe2(decimal lhs, double rhs) { return CompareWithDouble(lhs, rhs, DoubleOps.CompareGe, CompareGe); }
}
internal static class DoubleOps
{
internal static object Add(double lhs, double rhs)
{
return lhs + rhs;
}
internal static object Sub(double lhs, double rhs)
{
return lhs - rhs;
}
internal static object Multiply(double lhs, double rhs)
{
return lhs * rhs;
}
internal static object Divide(double lhs, double rhs)
{
return lhs / rhs;
}
internal static object Remainder(double lhs, double rhs)
{
return lhs % rhs;
}
internal static object BNot(double val)
{
try
{
checked
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return ~LanguagePrimitives.ConvertTo<int>(val);
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return ~LanguagePrimitives.ConvertTo<uint>(val);
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return ~LanguagePrimitives.ConvertTo<long>(val);
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return ~LanguagePrimitives.ConvertTo<ulong>(val);
}
}
}
catch (OverflowException)
{
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object BOr(double lhs, double rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l | r);
}
}
return l | r;
}
internal static object BXor(double lhs, double rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l ^ r);
}
}
return l ^ r;
}
internal static object BAnd(double lhs, double rhs)
{
ulong l = ConvertToUlong(lhs);
ulong r = ConvertToUlong(rhs);
// If either operand is signed, return signed result
if (lhs < 0 || rhs < 0)
{
unchecked
{
return (long)(l & r);
}
}
return l & r;
}
// This had to be done because if we try to cast a negative double number to unsigned, we get an OverFlowException
// We had to cast them to long (if they are negative) and then promote everything to ULong.
// While returning the result, we can return either signed or unsigned depending on the input.
private static ulong ConvertToUlong(double val)
{
if (val < 0)
{
long lValue = LanguagePrimitives.ConvertTo<long>(val);
return unchecked((ulong)lValue);
}
return LanguagePrimitives.ConvertTo<ulong>(val);
}
internal static object LeftShift(double val, int count)
{
checked
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return LanguagePrimitives.ConvertTo<int>(val) << count;
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return LanguagePrimitives.ConvertTo<uint>(val) << count;
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return LanguagePrimitives.ConvertTo<long>(val) << count;
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return LanguagePrimitives.ConvertTo<ulong>(val) << count;
}
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object RightShift(double val, int count)
{
checked
{
if (val <= int.MaxValue && val >= int.MinValue)
{
return LanguagePrimitives.ConvertTo<int>(val) >> count;
}
if (val <= uint.MaxValue && val >= uint.MinValue)
{
return LanguagePrimitives.ConvertTo<uint>(val) >> count;
}
if (val <= long.MaxValue && val >= long.MinValue)
{
return LanguagePrimitives.ConvertTo<long>(val) >> count;
}
if (val <= ulong.MaxValue && val >= ulong.MinValue)
{
return LanguagePrimitives.ConvertTo<ulong>(val) >> count;
}
}
LanguagePrimitives.ThrowInvalidCastException(val, typeof(ulong));
Diagnostics.Assert(false, "an exception is raised by LanguagePrimitives.ThrowInvalidCastException.");
return null;
}
internal static object CompareEq(double lhs, double rhs) { return (lhs == rhs) ? Boxed.True : Boxed.False; }
internal static object CompareNe(double lhs, double rhs) { return (lhs != rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLt(double lhs, double rhs) { return (lhs < rhs) ? Boxed.True : Boxed.False; }
internal static object CompareLe(double lhs, double rhs) { return (lhs <= rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGt(double lhs, double rhs) { return (lhs > rhs) ? Boxed.True : Boxed.False; }
internal static object CompareGe(double lhs, double rhs) { return (lhs >= rhs) ? Boxed.True : Boxed.False; }
}
internal static class CharOps
{
internal static object CompareStringIeq(char lhs, string rhs)
{
if (rhs.Length != 1)
{
return Boxed.False;
}
return CompareIeq(lhs, rhs[0]);
}
internal static object CompareStringIne(char lhs, string rhs)
{
if (rhs.Length != 1)
{
return Boxed.True;
}
return CompareIne(lhs, rhs[0]);
}
internal static object CompareIeq(char lhs, char rhs)
{
char firstAsUpper = char.ToUpperInvariant(lhs);
char secondAsUpper = char.ToUpperInvariant(rhs);
return firstAsUpper == secondAsUpper ? Boxed.True : Boxed.False;
}
internal static object CompareIne(char lhs, char rhs)
{
char firstAsUpper = char.ToUpperInvariant(lhs);
char secondAsUpper = char.ToUpperInvariant(rhs);
return firstAsUpper != secondAsUpper ? Boxed.True : Boxed.False;
}
internal static object[] Range(char start, char end)
{
int lower = (int)start;
int upper = (int)end;
int absRange = Math.Abs(checked(upper - lower));
object[] ra = new object[absRange + 1];
if (lower > upper)
{
// 3 .. 1 => 3 2 1
for (int offset = 0; offset < ra.Length; offset++)
ra[offset] = (char)lower--;
}
else
{
// 1 .. 3 => 1 2 3
for (int offset = 0; offset < ra.Length; offset++)
ra[offset] = (char)lower++;
}
return ra;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Windows.Forms;
using OpenPop.Mime;
using OpenPop.Mime.Header;
using OpenPop.Pop3;
using OpenPop.Pop3.Exceptions;
using OpenPop.Common.Logging;
using Message = OpenPop.Mime.Message;
namespace OpenPop.TestApplication
{
/// <summary>
/// This class is a form which makes it possible to download all messages
/// from a pop3 mailbox in a simply way.
/// </summary>
public class TestForm : Form
{
private readonly Dictionary<int, Message> messages = new Dictionary<int, Message>();
private readonly Pop3Client pop3Client;
private Button connectAndRetrieveButton;
private Button uidlButton;
private Panel attachmentPanel;
private ContextMenu contextMenuMessages;
private DataGrid gridHeaders;
private Label labelServerAddress;
private Label labelServerPort;
private Label labelAttachments;
private Label labelMessageBody;
private Label labelMessageNumber;
private Label labelTotalMessages;
private Label labelPassword;
private Label labelUsername;
private TreeView listAttachments;
private TreeView listMessages;
private MenuItem menuDeleteMessage;
private MenuItem menuViewSource;
private Panel panelTop;
private Panel panelProperties;
private Panel panelMiddle;
private Panel panelMessageBody;
private Panel panelMessagesView;
private SaveFileDialog saveFile;
private TextBox loginTextBox;
private TextBox messageTextBox;
private TextBox popServerTextBox;
private TextBox passwordTextBox;
private TextBox portTextBox;
private TextBox totalMessagesTextBox;
private ProgressBar progressBar;
private CheckBox useSslCheckBox;
private TestForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// User defined stuff here
//
// This is how you would override the default logger type
// Here we want to log to a file
DefaultLogger.SetLog(new FileLogger());
// Enable file logging and include verbose information
FileLogger.Enabled = true;
FileLogger.Verbose = true;
pop3Client = new Pop3Client();
// This is only for faster debugging purposes
// We will try to load in default values for the hostname, port, ssl, username and password from a file
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string file = Path.Combine(myDocs, "OpenPopLogin.txt");
if (File.Exists(file))
{
using (StreamReader reader = new StreamReader(File.OpenRead(file)))
{
// This describes how the OpenPOPLogin.txt file should look like
popServerTextBox.Text = reader.ReadLine(); // Hostname
portTextBox.Text = reader.ReadLine(); // Port
useSslCheckBox.Checked = bool.Parse(reader.ReadLine() ?? "true"); // Whether to use SSL or not
loginTextBox.Text = reader.ReadLine(); // Username
passwordTextBox.Text = reader.ReadLine(); // Password
}
}
}
#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(TestForm));
this.panelTop = new System.Windows.Forms.Panel();
this.useSslCheckBox = new System.Windows.Forms.CheckBox();
this.uidlButton = new System.Windows.Forms.Button();
this.totalMessagesTextBox = new System.Windows.Forms.TextBox();
this.labelTotalMessages = new System.Windows.Forms.Label();
this.labelPassword = new System.Windows.Forms.Label();
this.passwordTextBox = new System.Windows.Forms.TextBox();
this.labelUsername = new System.Windows.Forms.Label();
this.loginTextBox = new System.Windows.Forms.TextBox();
this.connectAndRetrieveButton = new System.Windows.Forms.Button();
this.labelServerPort = new System.Windows.Forms.Label();
this.portTextBox = new System.Windows.Forms.TextBox();
this.labelServerAddress = new System.Windows.Forms.Label();
this.popServerTextBox = new System.Windows.Forms.TextBox();
this.panelProperties = new System.Windows.Forms.Panel();
this.gridHeaders = new System.Windows.Forms.DataGrid();
this.panelMiddle = new System.Windows.Forms.Panel();
this.panelMessageBody = new System.Windows.Forms.Panel();
this.progressBar = new System.Windows.Forms.ProgressBar();
this.messageTextBox = new System.Windows.Forms.TextBox();
this.labelMessageBody = new System.Windows.Forms.Label();
this.panelMessagesView = new System.Windows.Forms.Panel();
this.listMessages = new System.Windows.Forms.TreeView();
this.contextMenuMessages = new System.Windows.Forms.ContextMenu();
this.menuDeleteMessage = new System.Windows.Forms.MenuItem();
this.menuViewSource = new System.Windows.Forms.MenuItem();
this.labelMessageNumber = new System.Windows.Forms.Label();
this.attachmentPanel = new System.Windows.Forms.Panel();
this.listAttachments = new System.Windows.Forms.TreeView();
this.labelAttachments = new System.Windows.Forms.Label();
this.saveFile = new System.Windows.Forms.SaveFileDialog();
this.panelTop.SuspendLayout();
this.panelProperties.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.gridHeaders)).BeginInit();
this.panelMiddle.SuspendLayout();
this.panelMessageBody.SuspendLayout();
this.panelMessagesView.SuspendLayout();
this.attachmentPanel.SuspendLayout();
this.SuspendLayout();
//
// panelTop
//
this.panelTop.Controls.Add(this.useSslCheckBox);
this.panelTop.Controls.Add(this.uidlButton);
this.panelTop.Controls.Add(this.totalMessagesTextBox);
this.panelTop.Controls.Add(this.labelTotalMessages);
this.panelTop.Controls.Add(this.labelPassword);
this.panelTop.Controls.Add(this.passwordTextBox);
this.panelTop.Controls.Add(this.labelUsername);
this.panelTop.Controls.Add(this.loginTextBox);
this.panelTop.Controls.Add(this.connectAndRetrieveButton);
this.panelTop.Controls.Add(this.labelServerPort);
this.panelTop.Controls.Add(this.portTextBox);
this.panelTop.Controls.Add(this.labelServerAddress);
this.panelTop.Controls.Add(this.popServerTextBox);
this.panelTop.Dock = System.Windows.Forms.DockStyle.Top;
this.panelTop.Location = new System.Drawing.Point(0, 0);
this.panelTop.Name = "panelTop";
this.panelTop.Size = new System.Drawing.Size(865, 64);
this.panelTop.TabIndex = 0;
//
// useSslCheckBox
//
this.useSslCheckBox.AutoSize = true;
this.useSslCheckBox.Checked = true;
this.useSslCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
this.useSslCheckBox.Location = new System.Drawing.Point(19, 38);
this.useSslCheckBox.Name = "useSslCheckBox";
this.useSslCheckBox.Size = new System.Drawing.Size(68, 17);
this.useSslCheckBox.TabIndex = 4;
this.useSslCheckBox.Text = "Use SSL";
this.useSslCheckBox.UseVisualStyleBackColor = true;
//
// uidlButton
//
this.uidlButton.Enabled = false;
this.uidlButton.Location = new System.Drawing.Point(460, 42);
this.uidlButton.Name = "uidlButton";
this.uidlButton.Size = new System.Drawing.Size(82, 21);
this.uidlButton.TabIndex = 6;
this.uidlButton.Text = "UIDL";
this.uidlButton.Click += new System.EventHandler(this.UidlButtonClick);
//
// totalMessagesTextBox
//
this.totalMessagesTextBox.Location = new System.Drawing.Point(553, 30);
this.totalMessagesTextBox.Name = "totalMessagesTextBox";
this.totalMessagesTextBox.Size = new System.Drawing.Size(100, 20);
this.totalMessagesTextBox.TabIndex = 7;
//
// labelTotalMessages
//
this.labelTotalMessages.Location = new System.Drawing.Point(553, 7);
this.labelTotalMessages.Name = "labelTotalMessages";
this.labelTotalMessages.Size = new System.Drawing.Size(100, 23);
this.labelTotalMessages.TabIndex = 9;
this.labelTotalMessages.Text = "Total Messages";
//
// labelPassword
//
this.labelPassword.Location = new System.Drawing.Point(264, 36);
this.labelPassword.Name = "labelPassword";
this.labelPassword.Size = new System.Drawing.Size(64, 23);
this.labelPassword.TabIndex = 8;
this.labelPassword.Text = "Password";
//
// passwordTextBox
//
this.passwordTextBox.Location = new System.Drawing.Point(328, 36);
this.passwordTextBox.Name = "passwordTextBox";
this.passwordTextBox.PasswordChar = '*';
this.passwordTextBox.Size = new System.Drawing.Size(128, 20);
this.passwordTextBox.TabIndex = 2;
//
// labelUsername
//
this.labelUsername.Location = new System.Drawing.Point(264, 5);
this.labelUsername.Name = "labelUsername";
this.labelUsername.Size = new System.Drawing.Size(64, 23);
this.labelUsername.TabIndex = 6;
this.labelUsername.Text = "Username";
//
// loginTextBox
//
this.loginTextBox.Location = new System.Drawing.Point(328, 5);
this.loginTextBox.Name = "loginTextBox";
this.loginTextBox.Size = new System.Drawing.Size(128, 20);
this.loginTextBox.TabIndex = 1;
//
// connectAndRetrieveButton
//
this.connectAndRetrieveButton.Location = new System.Drawing.Point(460, 0);
this.connectAndRetrieveButton.Name = "connectAndRetrieveButton";
this.connectAndRetrieveButton.Size = new System.Drawing.Size(82, 39);
this.connectAndRetrieveButton.TabIndex = 5;
this.connectAndRetrieveButton.Text = "Connect and Retreive";
this.connectAndRetrieveButton.Click += new System.EventHandler(this.ConnectAndRetrieveButtonClick);
//
// labelServerPort
//
this.labelServerPort.Location = new System.Drawing.Point(97, 39);
this.labelServerPort.Name = "labelServerPort";
this.labelServerPort.Size = new System.Drawing.Size(31, 23);
this.labelServerPort.TabIndex = 3;
this.labelServerPort.Text = "Port";
//
// portTextBox
//
this.portTextBox.Location = new System.Drawing.Point(128, 39);
this.portTextBox.Name = "portTextBox";
this.portTextBox.Size = new System.Drawing.Size(128, 20);
this.portTextBox.TabIndex = 3;
this.portTextBox.Text = "110";
//
// labelServerAddress
//
this.labelServerAddress.Location = new System.Drawing.Point(16, 8);
this.labelServerAddress.Name = "labelServerAddress";
this.labelServerAddress.Size = new System.Drawing.Size(112, 23);
this.labelServerAddress.TabIndex = 1;
this.labelServerAddress.Text = "POP Server Address";
//
// popServerTextBox
//
this.popServerTextBox.Location = new System.Drawing.Point(128, 8);
this.popServerTextBox.Name = "popServerTextBox";
this.popServerTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Horizontal;
this.popServerTextBox.Size = new System.Drawing.Size(128, 20);
this.popServerTextBox.TabIndex = 0;
//
// panelProperties
//
this.panelProperties.Controls.Add(this.gridHeaders);
this.panelProperties.Dock = System.Windows.Forms.DockStyle.Bottom;
this.panelProperties.Location = new System.Drawing.Point(0, 260);
this.panelProperties.Name = "panelProperties";
this.panelProperties.Size = new System.Drawing.Size(865, 184);
this.panelProperties.TabIndex = 1;
//
// gridHeaders
//
this.gridHeaders.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.gridHeaders.DataMember = "";
this.gridHeaders.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.gridHeaders.Location = new System.Drawing.Point(0, 0);
this.gridHeaders.Name = "gridHeaders";
this.gridHeaders.PreferredColumnWidth = 400;
this.gridHeaders.ReadOnly = true;
this.gridHeaders.Size = new System.Drawing.Size(865, 188);
this.gridHeaders.TabIndex = 3;
//
// panelMiddle
//
this.panelMiddle.Controls.Add(this.panelMessageBody);
this.panelMiddle.Controls.Add(this.panelMessagesView);
this.panelMiddle.Controls.Add(this.attachmentPanel);
this.panelMiddle.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMiddle.Location = new System.Drawing.Point(0, 64);
this.panelMiddle.Name = "panelMiddle";
this.panelMiddle.Size = new System.Drawing.Size(865, 196);
this.panelMiddle.TabIndex = 2;
//
// panelMessageBody
//
this.panelMessageBody.Controls.Add(this.progressBar);
this.panelMessageBody.Controls.Add(this.messageTextBox);
this.panelMessageBody.Controls.Add(this.labelMessageBody);
this.panelMessageBody.Dock = System.Windows.Forms.DockStyle.Fill;
this.panelMessageBody.Location = new System.Drawing.Point(175, 0);
this.panelMessageBody.Name = "panelMessageBody";
this.panelMessageBody.Size = new System.Drawing.Size(376, 196);
this.panelMessageBody.TabIndex = 6;
//
// progressBar
//
this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.progressBar.Location = new System.Drawing.Point(7, 172);
this.progressBar.Name = "progressBar";
this.progressBar.Size = new System.Drawing.Size(360, 12);
this.progressBar.TabIndex = 10;
//
// messageTextBox
//
this.messageTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.messageTextBox.Location = new System.Drawing.Point(7, 22);
this.messageTextBox.MaxLength = 999999999;
this.messageTextBox.Multiline = true;
this.messageTextBox.Name = "messageTextBox";
this.messageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Both;
this.messageTextBox.Size = new System.Drawing.Size(360, 143);
this.messageTextBox.TabIndex = 9;
//
// labelMessageBody
//
this.labelMessageBody.Location = new System.Drawing.Point(8, 8);
this.labelMessageBody.Name = "labelMessageBody";
this.labelMessageBody.Size = new System.Drawing.Size(136, 16);
this.labelMessageBody.TabIndex = 5;
this.labelMessageBody.Text = "Message Body";
//
// panelMessagesView
//
this.panelMessagesView.Controls.Add(this.listMessages);
this.panelMessagesView.Controls.Add(this.labelMessageNumber);
this.panelMessagesView.Dock = System.Windows.Forms.DockStyle.Left;
this.panelMessagesView.Location = new System.Drawing.Point(0, 0);
this.panelMessagesView.Name = "panelMessagesView";
this.panelMessagesView.Size = new System.Drawing.Size(281, 196);
this.panelMessagesView.TabIndex = 5;
//
// listMessages
//
this.listMessages.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listMessages.ContextMenu = this.contextMenuMessages;
this.listMessages.Location = new System.Drawing.Point(8, 24);
this.listMessages.Name = "listMessages";
this.listMessages.Size = new System.Drawing.Size(266, 160);
this.listMessages.TabIndex = 8;
this.listMessages.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.ListMessagesMessageSelected);
//
// contextMenuMessages
//
this.contextMenuMessages.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuDeleteMessage,
this.menuViewSource});
//
// menuDeleteMessage
//
this.menuDeleteMessage.Index = 0;
this.menuDeleteMessage.Text = "Delete Mail";
this.menuDeleteMessage.Click += new System.EventHandler(this.MenuDeleteMessageClick);
//
// menuViewSource
//
this.menuViewSource.Index = 1;
this.menuViewSource.Text = "View source";
this.menuViewSource.Click += new System.EventHandler(this.MenuViewSourceClick);
//
// labelMessageNumber
//
this.labelMessageNumber.Location = new System.Drawing.Point(8, 8);
this.labelMessageNumber.Name = "labelMessageNumber";
this.labelMessageNumber.Size = new System.Drawing.Size(136, 16);
this.labelMessageNumber.TabIndex = 1;
this.labelMessageNumber.Text = "Messages";
//
// attachmentPanel
//
this.attachmentPanel.Controls.Add(this.listAttachments);
this.attachmentPanel.Controls.Add(this.labelAttachments);
this.attachmentPanel.Dock = System.Windows.Forms.DockStyle.Right;
this.attachmentPanel.Location = new System.Drawing.Point(667, 0);
this.attachmentPanel.Name = "attachmentPanel";
this.attachmentPanel.Size = new System.Drawing.Size(208, 196);
this.attachmentPanel.TabIndex = 4;
this.attachmentPanel.Visible = false;
//
// listAttachments
//
this.listAttachments.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.listAttachments.Location = new System.Drawing.Point(8, 24);
this.listAttachments.Name = "listAttachments";
this.listAttachments.ShowLines = false;
this.listAttachments.ShowRootLines = false;
this.listAttachments.Size = new System.Drawing.Size(192, 160);
this.listAttachments.TabIndex = 10;
this.listAttachments.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.ListAttachmentsAttachmentSelected);
//
// labelAttachments
//
this.labelAttachments.Location = new System.Drawing.Point(12, 8);
this.labelAttachments.Name = "labelAttachments";
this.labelAttachments.Size = new System.Drawing.Size(136, 16);
this.labelAttachments.TabIndex = 3;
this.labelAttachments.Text = "Attachments";
//
// saveFile
//
this.saveFile.Title = "Save Attachment";
//
// TestForm
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(865, 444);
this.Controls.Add(this.panelMiddle);
this.Controls.Add(this.panelProperties);
this.Controls.Add(this.panelTop);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "TestForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "OpenPOP.NET Test Application";
this.WindowState = System.Windows.Forms.FormWindowState.Maximized;
this.panelTop.ResumeLayout(false);
this.panelTop.PerformLayout();
this.panelProperties.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.gridHeaders)).EndInit();
this.panelMiddle.ResumeLayout(false);
this.panelMessageBody.ResumeLayout(false);
this.panelMessageBody.PerformLayout();
this.panelMessagesView.ResumeLayout(false);
this.attachmentPanel.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
private static void Main()
{
Application.Run(new TestForm());
}
private void ReceiveMails()
{
// Disable buttons while working
connectAndRetrieveButton.Enabled = false;
uidlButton.Enabled = false;
progressBar.Value = 0;
try
{
if (pop3Client.Connected)
pop3Client.Disconnect();
pop3Client.Connect(popServerTextBox.Text, int.Parse(portTextBox.Text), useSslCheckBox.Checked);
pop3Client.Authenticate(loginTextBox.Text, passwordTextBox.Text);
int count = pop3Client.GetMessageCount();
totalMessagesTextBox.Text = count.ToString();
messageTextBox.Text = "";
messages.Clear();
listMessages.Nodes.Clear();
listAttachments.Nodes.Clear();
int success = 0;
int fail = 0;
for (int i = count; i >= 1; i -= 1)
{
// Check if the form is closed while we are working. If so, abort
if (IsDisposed)
return;
// Refresh the form while fetching emails
// This will fix the "Application is not responding" problem
Application.DoEvents();
try
{
Message message = pop3Client.GetMessage(i);
// Add the message to the dictionary from the messageNumber to the Message
messages.Add(i, message);
// Create a TreeNode tree that mimics the Message hierarchy
TreeNode node = new TreeNodeBuilder().VisitMessage(message);
// Set the Tag property to the messageNumber
// We can use this to find the Message again later
node.Tag = i;
// Show the built node in our list of messages
listMessages.Nodes.Add(node);
success++;
} catch (Exception e)
{
DefaultLogger.Log.LogError(
"TestForm: Message fetching failed: " + e.Message + "\r\n"+
"Stack trace:\r\n" +
e.StackTrace);
fail++;
}
progressBar.Value = (int)(((double)(count-i)/count) * 100);
}
MessageBox.Show(this, "Mail received!\nSuccesses: " + success + "\nFailed: " + fail, "Message fetching done");
if(fail > 0)
{
MessageBox.Show(this,
"Since some of the emails were not parsed correctly (exceptions were thrown)\r\n" +
"please consider sending your log file to the developer for fixing.\r\n" +
"If you are able to include any extra information, please do so.",
"Help improve OpenPop!");
}
} catch (InvalidLoginException)
{
MessageBox.Show(this, "The server did not accept the user credentials!", "POP3 Server Authentication");
} catch (PopServerNotFoundException)
{
MessageBox.Show(this, "The server could not be found", "POP3 Retrieval");
} catch(PopServerLockedException)
{
MessageBox.Show(this, "The mailbox is locked. It might be in use or under maintenance. Are you connected elsewhere?", "POP3 Account Locked");
} catch (LoginDelayException)
{
MessageBox.Show(this, "Login not allowed. Server enforces delay between logins. Have you connected recently?", "POP3 Account Login Delay");
} catch (Exception e)
{
MessageBox.Show(this, "Error occurred retrieving mail. " + e.Message, "POP3 Retrieval");
} finally
{
// Enable the buttons again
connectAndRetrieveButton.Enabled = true;
uidlButton.Enabled = true;
progressBar.Value = 100;
}
}
private void ConnectAndRetrieveButtonClick(object sender, EventArgs e)
{
ReceiveMails();
}
private void ListMessagesMessageSelected(object sender, TreeViewEventArgs e)
{
// Fetch out the selected message
Message message = messages[GetMessageNumberFromSelectedNode(listMessages.SelectedNode)];
// If the selected node contains a MessagePart and we can display the contents - display them
if (listMessages.SelectedNode.Tag is MessagePart)
{
MessagePart selectedMessagePart = (MessagePart)listMessages.SelectedNode.Tag;
if (selectedMessagePart.IsText)
{
// We can show text MessageParts
messageTextBox.Text = selectedMessagePart.GetBodyAsText();
}
else
{
// We are not able to show non-text MessageParts (MultiPart messages, images, pdf's ...)
messageTextBox.Text = "<<OpenPop>> Cannot show this part of the email. It is not text <<OpenPop>>";
}
}
else
{
// If the selected node is not a subnode and therefore does not
// have a MessagePart in it's Tag property, we genericly find some content to show
// Find the first text/plain version
MessagePart plainTextPart = message.FindFirstPlainTextVersion();
if (plainTextPart != null)
{
// The message had a text/plain version - show that one
messageTextBox.Text = plainTextPart.GetBodyAsText();
} else
{
// Try to find a body to show in some of the other text versions
List<MessagePart> textVersions = message.FindAllTextVersions();
if (textVersions.Count >= 1)
messageTextBox.Text = textVersions[0].GetBodyAsText();
else
messageTextBox.Text = "<<OpenPop>> Cannot find a text version body in this message to show <<OpenPop>>";
}
}
// Clear the attachment list from any previus shown attachments
listAttachments.Nodes.Clear();
// Build up the attachment list
List<MessagePart> attachments = message.FindAllAttachments();
foreach (MessagePart attachment in attachments)
{
// Add the attachment to the list of attachments
TreeNode addedNode = listAttachments.Nodes.Add((attachment.FileName));
// Keep a reference to the attachment in the Tag property
addedNode.Tag = attachment;
}
// Only show that attachmentPanel if there is attachments in the message
bool hadAttachments = attachments.Count > 0;
attachmentPanel.Visible = hadAttachments;
// Generate header table
DataSet dataSet = new DataSet();
DataTable table = dataSet.Tables.Add("Headers");
table.Columns.Add("Header");
table.Columns.Add("Value");
DataRowCollection rows = table.Rows;
// Add all known headers
rows.Add(new object[] {"Content-Description", message.Headers.ContentDescription});
rows.Add(new object[] {"Content-Id", message.Headers.ContentId});
foreach (string keyword in message.Headers.Keywords) rows.Add(new object[] {"Keyword", keyword});
foreach (RfcMailAddress dispositionNotificationTo in message.Headers.DispositionNotificationTo) rows.Add(new object[] {"Disposition-Notification-To", dispositionNotificationTo});
foreach (Received received in message.Headers.Received) rows.Add(new object[] {"Received", received.Raw});
rows.Add(new object[] {"Importance", message.Headers.Importance});
rows.Add(new object[] {"Content-Transfer-Encoding", message.Headers.ContentTransferEncoding});
foreach (RfcMailAddress cc in message.Headers.Cc) rows.Add(new object[] {"Cc", cc});
foreach (RfcMailAddress bcc in message.Headers.Bcc) rows.Add(new object[] {"Bcc", bcc});
foreach (RfcMailAddress to in message.Headers.To) rows.Add(new object[] { "To", to });
rows.Add(new object[] {"From", message.Headers.From});
rows.Add(new object[] {"Reply-To", message.Headers.ReplyTo});
foreach (string inReplyTo in message.Headers.InReplyTo) rows.Add(new object[] {"In-Reply-To", inReplyTo});
foreach (string reference in message.Headers.References) rows.Add(new object[] { "References", reference });
rows.Add(new object[] {"Sender", message.Headers.Sender});
rows.Add(new object[] {"Content-Type", message.Headers.ContentType});
rows.Add(new object[] {"Content-Disposition", message.Headers.ContentDisposition});
rows.Add(new object[] {"Date", message.Headers.Date});
rows.Add(new object[] {"Date", message.Headers.DateSent});
rows.Add(new object[] {"Message-Id", message.Headers.MessageId});
rows.Add(new object[] {"Mime-Version", message.Headers.MimeVersion});
rows.Add(new object[] {"Return-Path", message.Headers.ReturnPath});
rows.Add(new object[] {"Subject", message.Headers.Subject});
// Add all unknown headers
foreach (string key in message.Headers.UnknownHeaders)
{
string[] values = message.Headers.UnknownHeaders.GetValues(key);
if (values != null)
foreach (string value in values)
{
rows.Add(new object[] {key, value});
}
}
// Now set the headers displayed on the GUI to the header table we just generated
gridHeaders.DataMember = table.TableName;
gridHeaders.DataSource = dataSet;
}
/// <summary>
/// Finds the MessageNumber of a Message given a <see cref="TreeNode"/> to search in.
/// The root of this <see cref="TreeNode"/> should have the Tag property set to a int, which
/// points into the <see cref="messages"/> dictionary.
/// </summary>
/// <param name="node">The <see cref="TreeNode"/> to look in. Cannot be <see langword="null"/>.</param>
/// <returns>The found int</returns>
private static int GetMessageNumberFromSelectedNode(TreeNode node)
{
if (node == null)
throw new ArgumentNullException("node");
// Check if we are at the root, by seeing if it has the Tag property set to an int
if(node.Tag is int)
{
return (int) node.Tag;
}
// Otherwise we are not at the root, move up the tree
return GetMessageNumberFromSelectedNode(node.Parent);
}
private void ListAttachmentsAttachmentSelected(object sender, TreeViewEventArgs args)
{
// Fetch the attachment part which is currently selected
MessagePart attachment = (MessagePart)listAttachments.SelectedNode.Tag;
if (attachment != null)
{
saveFile.FileName = attachment.FileName;
DialogResult result = saveFile.ShowDialog();
if (result != DialogResult.OK)
return;
// Now we want to save the attachment
FileInfo file = new FileInfo(saveFile.FileName);
// Check if the file already exists
if(file.Exists)
{
// User was asked when he chose the file, if he wanted to overwrite it
// Therefore, when we get to here, it is okay to delete the file
file.Delete();
}
// Lets try to save to the file
try
{
attachment.Save(file);
MessageBox.Show(this, "Attachment saved successfully");
} catch (Exception e)
{
MessageBox.Show(this, "Attachment saving failed. Exception message: " + e.Message);
}
}
else
{
MessageBox.Show(this, "Attachment object was null!");
}
}
private void MenuDeleteMessageClick(object sender, EventArgs e)
{
if (listMessages.SelectedNode != null)
{
DialogResult drRet = MessageBox.Show(this, "Are you sure to delete the email?", "Delete email", MessageBoxButtons.YesNo);
if (drRet == DialogResult.Yes)
{
int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
pop3Client.DeleteMessage(messageNumber);
listMessages.Nodes[messageNumber].Remove();
drRet = MessageBox.Show(this, "Do you want to receive email again (this will commit your changes)?", "Receive email", MessageBoxButtons.YesNo);
if (drRet == DialogResult.Yes)
ReceiveMails();
}
}
}
private void UidlButtonClick(object sender, EventArgs e)
{
List<string> uids = pop3Client.GetMessageUids();
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.Append("UIDL:");
stringBuilder.Append("\r\n");
foreach (string uid in uids)
{
stringBuilder.Append(uid);
stringBuilder.Append("\r\n");
}
messageTextBox.Text = stringBuilder.ToString();
}
private void MenuViewSourceClick(object sender, EventArgs e)
{
if (listMessages.SelectedNode != null)
{
int messageNumber = GetMessageNumberFromSelectedNode(listMessages.SelectedNode);
Message m = messages[messageNumber];
// We do not know the encoding of the full message - and the parts could be differently
// encoded. Therefore we take a choice of simply using US-ASCII encoding on the raw bytes
// to get the source code for the message. Any bytes not in th US-ASCII encoding, will then be
// turned into question marks "?"
ShowSourceForm sourceForm = new ShowSourceForm(Encoding.ASCII.GetString(m.RawMessage));
sourceForm.ShowDialog();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.IO;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Threading;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace System.IO
{
/// <summary>
/// An <code>wrapper</code> for a managed stream that implements all WinRT stream operations.
/// This class must not implement any WinRT stream interfaces directly.
/// We never create instances of this class directly; instead we use classes defined in
/// the region Interface adapters to implement WinRT ifaces and create instances of those types.
/// See comment in that region for technical details.
/// </summary>
internal abstract class NetFxToWinRtStreamAdapter : IDisposable
{
#region Construction
#region Interface adapters
// Instances of private types defined in this section will be returned from NetFxToWinRtStreamAdapter.Create(..).
// Depending on the capabilities of the .NET stream for which we need to construct the adapter, we need to return
// an object that can be QIed (COM speak for "cast") to a well-defined set of ifaces.
// E.g, if the specified stream CanRead, but not CanSeek and not CanWrite, then we *must* return an object that
// can be QIed to IInputStream, but *not* IRandomAccessStream and *not* IOutputStream.
// There are two ways to do that:
// - We could explicitly implement ICustomQueryInterface and respond to QI requests by analyzing the stream capabilities
// - We can use the runtime's ability to do that for us, based on the ifaces the concrete class implements (or does not).
// The latter is much more elegant, and likely also faster.
private class InputStream : NetFxToWinRtStreamAdapter, IInputStream, IDisposable
{
internal InputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class OutputStream : NetFxToWinRtStreamAdapter, IOutputStream, IDisposable
{
internal OutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class RandomAccessStream : NetFxToWinRtStreamAdapter, IRandomAccessStream, IInputStream, IOutputStream, IDisposable
{
internal RandomAccessStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
private class InputOutputStream : NetFxToWinRtStreamAdapter, IInputStream, IOutputStream, IDisposable
{
internal InputOutputStream(Stream stream, StreamReadOperationOptimization readOptimization)
: base(stream, readOptimization)
{
}
}
#endregion Interface adapters
// We may want to define different behaviour for different types of streams.
// For instance, ReadAsync treats MemoryStream special for performance reasons.
// The enum 'StreamReadOperationOptimization' describes the read optimization to employ for a
// given NetFxToWinRtStreamAdapter instance. In future, we might define other enums to follow a
// similar pattern, e.g. 'StreamWriteOperationOptimization' or 'StreamFlushOperationOptimization'.
private enum StreamReadOperationOptimization
{
AbstractStream = 0, MemoryStream
}
internal static NetFxToWinRtStreamAdapter Create(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
StreamReadOperationOptimization readOptimization = StreamReadOperationOptimization.AbstractStream;
if (stream.CanRead)
readOptimization = DetermineStreamReadOptimization(stream);
NetFxToWinRtStreamAdapter adapter;
if (stream.CanSeek)
adapter = new RandomAccessStream(stream, readOptimization);
else if (stream.CanRead && stream.CanWrite)
adapter = new InputOutputStream(stream, readOptimization);
else if (stream.CanRead)
adapter = new InputStream(stream, readOptimization);
else if (stream.CanWrite)
adapter = new OutputStream(stream, readOptimization);
else
throw new ArgumentException(SR.Argument_NotSufficientCapabilitiesToConvertToWinRtStream);
return adapter;
}
private static StreamReadOperationOptimization DetermineStreamReadOptimization(Stream stream)
{
Debug.Assert(stream != null);
if (CanApplyReadMemoryStreamOptimization(stream))
return StreamReadOperationOptimization.MemoryStream;
return StreamReadOperationOptimization.AbstractStream;
}
private static bool CanApplyReadMemoryStreamOptimization(Stream stream)
{
MemoryStream memStream = stream as MemoryStream;
if (memStream == null)
return false;
ArraySegment<byte> arrSeg;
return memStream.TryGetBuffer(out arrSeg);
}
private NetFxToWinRtStreamAdapter(Stream stream, StreamReadOperationOptimization readOptimization)
{
Debug.Assert(stream != null);
Debug.Assert(stream.CanRead || stream.CanWrite || stream.CanSeek);
Contract.EndContractBlock();
Debug.Assert(!stream.CanRead || (stream.CanRead && this is IInputStream));
Debug.Assert(!stream.CanWrite || (stream.CanWrite && this is IOutputStream));
Debug.Assert(!stream.CanSeek || (stream.CanSeek && this is IRandomAccessStream));
_readOptimization = readOptimization;
_managedStream = stream;
}
#endregion Construction
#region Instance variables
private Stream _managedStream = null;
private bool _leaveUnderlyingStreamOpen = true;
private readonly StreamReadOperationOptimization _readOptimization;
#endregion Instance variables
#region Tools and Helpers
/// <summary>
/// We keep tables for mappings between managed and WinRT streams to make sure to always return the same adapter for a given underlying stream.
/// However, in order to avoid global locks on those tables, several instances of this type may be created and then can race to be entered
/// into the appropriate map table. All except for the winning instances will be thrown away. However, we must ensure that when the losers are
/// finalized, they do not dispose the underlying stream. To ensure that, we must call this method on the winner to notify it that it is safe to
/// dispose the underlying stream.
/// </summary>
internal void SetWonInitializationRace()
{
_leaveUnderlyingStreamOpen = false;
}
public Stream GetManagedStream()
{
return _managedStream;
}
private Stream EnsureNotDisposed()
{
Stream str = _managedStream;
if (str == null)
{
ObjectDisposedException ex = new ObjectDisposedException(SR.ObjectDisposed_CannotPerformOperation);
ex.SetErrorCode(__HResults.RO_E_CLOSED);
throw ex;
}
return str;
}
#endregion Tools and Helpers
#region Common public interface
/// <summary>Implements IDisposable.Dispose (IClosable.Close in WinRT)</summary>
void IDisposable.Dispose()
{
Stream str = _managedStream;
if (str == null)
return;
_managedStream = null;
if (!_leaveUnderlyingStreamOpen)
str.Dispose();
}
#endregion Common public interface
#region IInputStream public interface
public IAsyncOperationWithProgress<IBuffer, UInt32> ReadAsync(IBuffer buffer, UInt32 count, InputStreamOptions options)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0 || Int32.MaxValue < count)
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(count));
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
if (buffer.Capacity < count)
{
ArgumentException ex = new ArgumentException(SR.Argument_InsufficientBufferCapacity);
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
if (!(options == InputStreamOptions.None || options == InputStreamOptions.Partial || options == InputStreamOptions.ReadAhead))
{
ArgumentOutOfRangeException ex = new ArgumentOutOfRangeException(nameof(options),
SR.ArgumentOutOfRange_InvalidInputStreamOptionsEnumValue);
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<IBuffer, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
IAsyncOperationWithProgress<IBuffer, UInt32> readAsyncOperation;
switch (_readOptimization)
{
case StreamReadOperationOptimization.MemoryStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_MemoryStream(str, buffer, count);
break;
case StreamReadOperationOptimization.AbstractStream:
readAsyncOperation = StreamOperationsImplementation.ReadAsync_AbstractStream(str, buffer, count, options);
break;
// Use this pattern to add more optimisation options if necessary:
//case StreamReadOperationOptimization.XxxxStream:
// readAsyncOperation = StreamOperationsImplementation.ReadAsync_XxxxStream(str, buffer, count, options);
// break;
default:
Debug.Assert(false, "We should never get here. Someone forgot to handle an input stream optimisation option.");
readAsyncOperation = null;
break;
}
return readAsyncOperation;
}
#endregion IInputStream public interface
#region IOutputStream public interface
public IAsyncOperationWithProgress<UInt32, UInt32> WriteAsync(IBuffer buffer)
{
if (buffer == null)
{
// Mapped to E_POINTER.
throw new ArgumentNullException(nameof(buffer));
}
if (buffer.Capacity < buffer.Length)
{
ArgumentException ex = new ArgumentException(SR.Argument_BufferLengthExceedsCapacity);
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.Ensures(Contract.Result<IAsyncOperationWithProgress<UInt32, UInt32>>() != null);
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.WriteAsync_AbstractStream(str, buffer);
}
public IAsyncOperation<Boolean> FlushAsync()
{
Contract.Ensures(Contract.Result<IAsyncOperation<Boolean>>() != null);
Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
return StreamOperationsImplementation.FlushAsync_AbstractStream(str);
}
#endregion IOutputStream public interface
#region IRandomAccessStream public interface
#region IRandomAccessStream public interface: Not cloning related
public void Seek(UInt64 position)
{
if (position > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSeekBeyondInt64MaxValue);
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
Int64 pos = unchecked((Int64)position);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= pos, "Unexpected pos=" + pos + ".");
str.Seek(pos, SeekOrigin.Begin);
}
public bool CanRead
{
get
{
Stream str = EnsureNotDisposed();
return str.CanRead;
}
}
public bool CanWrite
{
get
{
Stream str = EnsureNotDisposed();
return str.CanWrite;
}
}
public UInt64 Position
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Position;
}
}
public UInt64 Size
{
get
{
Contract.Ensures(Contract.Result<UInt64>() >= 0);
Stream str = EnsureNotDisposed();
return (UInt64)str.Length;
}
set
{
if (value > Int64.MaxValue)
{
ArgumentException ex = new ArgumentException(SR.IO_CannotSetSizeBeyondInt64MaxValue);
ex.SetErrorCode(__HResults.E_INVALIDARG);
throw ex;
}
// Commented due to a reported CCRewrite bug. Should uncomment when fixed:
//Contract.EndContractBlock();
Stream str = EnsureNotDisposed();
if (!str.CanWrite)
{
InvalidOperationException ex = new InvalidOperationException(SR.InvalidOperation_CannotSetStreamSizeCannotWrite);
ex.SetErrorCode(__HResults.E_ILLEGAL_METHOD_CALL);
throw ex;
}
Int64 val = unchecked((Int64)value);
Debug.Assert(str != null);
Debug.Assert(str.CanSeek, "The underlying str is expected to support Seek, but it does not.");
Debug.Assert(0 <= val, "Unexpected val=" + val + ".");
str.SetLength(val);
}
}
#endregion IRandomAccessStream public interface: Not cloning related
#region IRandomAccessStream public interface: Cloning related
// We do not want to support the cloning-related operation for now.
// They appear to mainly target corner-case scenarios in Windows itself,
// and are (mainly) a historical artefact of abandoned early designs
// for IRandonAccessStream.
// Cloning can be added in future, however, it would be quite complex
// to support it correctly for generic streams.
private static void ThrowCloningNotSupported(String methodName)
{
NotSupportedException nse = new NotSupportedException(SR.Format(SR.NotSupported_CloningNotSupported, methodName));
nse.SetErrorCode(__HResults.E_NOTIMPL);
throw nse;
}
public IRandomAccessStream CloneStream()
{
ThrowCloningNotSupported("CloneStream");
return null;
}
public IInputStream GetInputStreamAt(UInt64 position)
{
ThrowCloningNotSupported("GetInputStreamAt");
return null;
}
public IOutputStream GetOutputStreamAt(UInt64 position)
{
ThrowCloningNotSupported("GetOutputStreamAt");
return null;
}
#endregion IRandomAccessStream public interface: Cloning related
#endregion IRandomAccessStream public interface
} // class NetFxToWinRtStreamAdapter
} // namespace
// NetFxToWinRtStreamAdapter.cs
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
#if CLUSTERING_ADONET
namespace Orleans.Clustering.AdoNet.Storage
#elif PERSISTENCE_ADONET
namespace Orleans.Persistence.AdoNet.Storage
#elif REMINDERS_ADONET
namespace Orleans.Reminders.AdoNet.Storage
#elif TESTER_SQLUTILS
namespace Orleans.Tests.SqlUtils
#else
// No default namespace intentionally to cause compile errors if something is not defined
#endif
{
/// <summary>
/// Convenience functions to work with objects of type <see cref="IRelationalStorage"/>.
/// </summary>
internal static class RelationalStorageExtensions
{
/// <summary>
/// Used to format .NET objects suitable to relational database format.
/// </summary>
private static readonly AdoNetFormatProvider adoNetFormatProvider = new AdoNetFormatProvider();
/// <summary>
/// This is a template to produce query parameters that are indexed.
/// </summary>
private static readonly string indexedParameterTemplate = "@p{0}";
/// <summary>
/// Executes a multi-record insert query clause with <em>SELECT UNION ALL</em>.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="storage">The storage to use.</param>
/// <param name="tableName">The table name to against which to execute the query.</param>
/// <param name="parameters">The parameters to insert.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <param name="nameMap">If provided, maps property names from <typeparamref name="T"/> to ones provided in the map.</param>
/// <param name="onlyOnceColumns">If given, SQL parameter values for the given <typeparamref name="T"/> property types are generated only once. Effective only when <paramref name="useSqlParams"/> is <em>TRUE</em>.</param>
/// <param name="useSqlParams"><em>TRUE</em> if the query should be in parameterized form. <em>FALSE</em> otherwise.</param>
/// <returns>The rows affected.</returns>
public static Task<int> ExecuteMultipleInsertIntoAsync<T>(this IRelationalStorage storage, string tableName, IEnumerable<T> parameters, CancellationToken cancellationToken = default(CancellationToken), IReadOnlyDictionary<string, string> nameMap = null, IEnumerable<string> onlyOnceColumns = null, bool useSqlParams = true)
{
if(string.IsNullOrWhiteSpace(tableName))
{
throw new ArgumentException("The name must be a legal SQL table name", "tableName");
}
if(parameters == null)
{
throw new ArgumentNullException("parameters");
}
var storageConsts = DbConstantsStore.GetDbConstants(storage.InvariantName);
var startEscapeIndicator = storageConsts.StartEscapeIndicator;
var endEscapeIndicator = storageConsts.EndEscapeIndicator;
//SqlParameters map is needed in case the query needs to be parameterized in order to avoid two
//reflection passes as first a query needs to be constructed and after that when a database
//command object has been created, parameters need to be provided to them.
var sqlParameters = new Dictionary<string, object>();
const string insertIntoValuesTemplate = "INSERT INTO {0} ({1}) SELECT {2};";
var columns = string.Empty;
var values = new List<string>();
if(parameters.Any())
{
//Type and property information are the same for all of the objects.
//The following assumes the property names will be retrieved in the same
//order as is the index iteration done.
var onlyOnceRow = new List<string>();
var properties = parameters.First().GetType().GetProperties();
columns = string.Join(",", nameMap == null ? properties.Select(pn => string.Format("{0}{1}{2}", startEscapeIndicator, pn.Name, endEscapeIndicator)) : properties.Select(pn => string.Format("{0}{1}{2}", startEscapeIndicator, (nameMap.ContainsKey(pn.Name) ? nameMap[pn.Name] : pn.Name), endEscapeIndicator)));
if(onlyOnceColumns != null && onlyOnceColumns.Any())
{
var onlyOnceProperties = properties.Where(pn => onlyOnceColumns.Contains(pn.Name)).Select(pn => pn).ToArray();
var onlyOnceData = parameters.First();
for(int i = 0; i < onlyOnceProperties.Length; ++i)
{
var currentProperty = onlyOnceProperties[i];
var parameterValue = currentProperty.GetValue(onlyOnceData, null);
if(useSqlParams)
{
var parameterName = string.Format("@{0}", (nameMap.ContainsKey(onlyOnceProperties[i].Name) ? nameMap[onlyOnceProperties[i].Name] : onlyOnceProperties[i].Name));
onlyOnceRow.Add(parameterName);
sqlParameters.Add(parameterName, parameterValue);
}
else
{
onlyOnceRow.Add(string.Format(adoNetFormatProvider, "{0}", parameterValue));
}
}
}
var dataRows = new List<string>();
var multiProperties = onlyOnceColumns == null ? properties : properties.Where(pn => !onlyOnceColumns.Contains(pn.Name)).Select(pn => pn).ToArray();
int parameterCount = 0;
foreach(var row in parameters)
{
for(int i = 0; i < multiProperties.Length; ++i)
{
var currentProperty = multiProperties[i];
var parameterValue = currentProperty.GetValue(row, null);
if(useSqlParams)
{
var parameterName = string.Format(indexedParameterTemplate, parameterCount);
dataRows.Add(parameterName);
sqlParameters.Add(parameterName, parameterValue);
++parameterCount;
}
else
{
dataRows.Add(string.Format(adoNetFormatProvider, "{0}", parameterValue));
}
}
values.Add(string.Format("{0}", string.Join(",", onlyOnceRow.Concat(dataRows))));
dataRows.Clear();
}
}
var query = string.Format(insertIntoValuesTemplate, tableName, columns, string.Join(storageConsts.UnionAllSelectTemplate, values));
return storage.ExecuteAsync(query, command =>
{
if(useSqlParams)
{
foreach(var sp in sqlParameters)
{
var p = command.CreateParameter();
p.ParameterName = sp.Key;
p.Value = sp.Value ?? DBNull.Value;
p.Direction = ParameterDirection.Input;
command.Parameters.Add(p);
}
}
}, cancellationToken);
}
/// <summary>
/// A simplified version of <see cref="IRelationalStorage.ReadAsync{TResult}"/>
/// </summary>
/// <param name="storage"></param>
/// <param name="query"></param>
/// <param name="selector"></param>
/// <param name="parameterProvider"></param>
/// <typeparam name="TResult"></typeparam>
/// <returns></returns>
public static Task<IEnumerable<TResult>> ReadAsync<TResult>(this IRelationalStorage storage, string query, Func<IDataRecord, TResult> selector, Action<IDbCommand> parameterProvider)
{
return storage.ReadAsync(query, parameterProvider, (record, i, cancellationToken) => Task.FromResult(selector(record)));
}
/// <summary>
/// Uses <see cref="IRelationalStorage"/> with <see cref="DbExtensions.ReflectionParameterProvider{T}(IDbCommand, T, IReadOnlyDictionary{string, string})"/>.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="storage">The storage to use.</param>
/// <param name="query">Executes a given statement. Especially intended to use with <em>SELECT</em> statement, but works with other queries too.</param>
/// <param name="parameters">Adds parameters to the query. Parameter names must match those defined in the query.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of objects as a result of the <see paramref="query"/>.</returns>
/// <example>This uses reflection to read results and match the parameters.
/// <code>
/// //This struct holds the return value in this example.
/// public struct Information
/// {
/// public string TABLE_CATALOG { get; set; }
/// public string TABLE_NAME { get; set; }
/// }
///
/// //Here reflection (<seealso cref="DbExtensions.ReflectionParameterProvider{T}(IDbCommand, T, IReadOnlyDictionary{string, string})"/>)
/// is used to match parameter names as well as to read back the results (<seealso cref="DbExtensions.ReflectionSelector{TResult}(IDataRecord)"/>).
/// var query = "SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tname;";
/// IEnumerable<Information> informationData = await db.ReadAsync<Information>(query, new { tname = 200000 });
/// </code>
/// </example>
public static Task<IEnumerable<TResult>> ReadAsync<TResult>(this IRelationalStorage storage, string query, object parameters, CancellationToken cancellationToken = default(CancellationToken))
{
return storage.ReadAsync(query, command =>
{
if(parameters != null)
{
command.ReflectionParameterProvider(parameters);
}
}, (selector, resultSetCount, token) => Task.FromResult(selector.ReflectionSelector<TResult>()), cancellationToken);
}
/// <summary>
/// Uses <see cref="IRelationalStorage"/> with <see cref="DbExtensions.ReflectionParameterProvider{T}(System.Data.IDbCommand, T, IReadOnlyDictionary{string, string})">DbExtensions.ReflectionParameterProvider</see>.
/// </summary>
/// <typeparam name="TResult">The type of the result.</typeparam>
/// <param name="storage">The storage to use.</param>
/// <param name="query">Executes a given statement. Especially intended to use with <em>SELECT</em> statement, but works with other queries too.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of objects as a result of the <see paramref="query"/>.</returns>
public static Task<IEnumerable<TResult>> ReadAsync<TResult>(this IRelationalStorage storage, string query, CancellationToken cancellationToken = default(CancellationToken))
{
return ReadAsync<TResult>(storage, query, null, cancellationToken);
}
/// <summary>
/// Uses <see cref="IRelationalStorage"/> with <see cref="DbExtensions.ReflectionSelector{TResult}(System.Data.IDataRecord)"/>.
/// </summary>
/// <param name="storage">The storage to use.</param>
/// <param name="query">Executes a given statement. Especially intended to use with <em>INSERT</em>, <em>UPDATE</em>, <em>DELETE</em> or <em>DDL</em> queries.</param>
/// <param name="parameters">Adds parameters to the query. Parameter names must match those defined in the query.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>Affected rows count.</returns>
/// <example>This uses reflection to provide parameters to an execute
/// query that reads only affected rows count if available.
/// <code>
/// //Here reflection (<seealso cref="DbExtensions.ReflectionParameterProvider{T}(IDbCommand, T, IReadOnlyDictionary{string, string})"/>)
/// is used to match parameter names as well as to read back the results (<seealso cref="DbExtensions.ReflectionSelector{TResult}(IDataRecord)"/>).
/// var query = "IF NOT EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @tname) CREATE TABLE Test(Id INT PRIMARY KEY IDENTITY(1, 1) NOT NULL);"
/// await db.ExecuteAsync(query, new { tname = "test_table" });
/// </code>
/// </example>
public static Task<int> ExecuteAsync(this IRelationalStorage storage, string query, object parameters, CancellationToken cancellationToken = default(CancellationToken))
{
return storage.ExecuteAsync(query, command =>
{
if(parameters != null)
{
command.ReflectionParameterProvider(parameters);
}
}, cancellationToken);
}
/// <summary>
/// Uses <see cref="IRelationalStorage"/> with <see cref="DbExtensions.ReflectionSelector{TResult}(System.Data.IDataRecord)"/>.
/// </summary>
/// <param name="storage">The storage to use.</param>
/// <param name="query">Executes a given statement. Especially intended to use with <em>INSERT</em>, <em>UPDATE</em>, <em>DELETE</em> or <em>DDL</em> queries.</param>
/// <param name="cancellationToken">The cancellation token. Defaults to <see cref="CancellationToken.None"/>.</param>
/// <returns>Affected rows count.</returns>
public static Task<int> ExecuteAsync(this IRelationalStorage storage, string query, CancellationToken cancellationToken = default(CancellationToken))
{
return ExecuteAsync(storage, query, null, cancellationToken);
}
/// <summary>
/// Returns a native implementation of <see cref="DbDataReader.GetStream(int)"/> for those providers
/// which support it. Otherwise returns a chunked read using <see cref="DbDataReader.GetBytes(int, long, byte[], int, int)"/>.
/// </summary>
/// <param name="reader">The reader from which to return the stream.</param>
/// <param name="ordinal">The ordinal column for which to return the stream.</param>
/// <param name="storage">The storage that gives the invariant.</param>
/// <returns></returns>
public static Stream GetStream(this DbDataReader reader, int ordinal, IRelationalStorage storage)
{
if(storage.SupportsStreamNatively())
{
return reader.GetStream(ordinal);
}
return new OrleansRelationalDownloadStream(reader, ordinal);
}
}
}
| |
// 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.Globalization;
using System.Text;
using Microsoft.CSharp.RuntimeBinder.Semantics;
using Microsoft.CSharp.RuntimeBinder.Syntax;
namespace Microsoft.CSharp.RuntimeBinder.Errors
{
internal sealed class UserStringBuilder
{
private bool m_buildingInProgress;
private GlobalSymbolContext m_globalSymbols;
private StringBuilder m_strBuilder;
public UserStringBuilder(
GlobalSymbolContext globalSymbols)
{
Debug.Assert(globalSymbols != null);
m_buildingInProgress = false;
m_globalSymbols = globalSymbols;
}
private void BeginString()
{
Debug.Assert(!m_buildingInProgress);
m_buildingInProgress = true;
m_strBuilder = new StringBuilder();
}
private void EndString(out string s)
{
Debug.Assert(m_buildingInProgress);
m_buildingInProgress = false;
s = m_strBuilder.ToString();
m_strBuilder = null;
}
private void ErrSK(out string psz, SYMKIND sk)
{
MessageID id;
switch (sk)
{
case SYMKIND.SK_MethodSymbol:
id = MessageID.SK_METHOD;
break;
case SYMKIND.SK_AggregateSymbol:
id = MessageID.SK_CLASS;
break;
case SYMKIND.SK_NamespaceSymbol:
id = MessageID.SK_NAMESPACE;
break;
case SYMKIND.SK_FieldSymbol:
id = MessageID.SK_FIELD;
break;
case SYMKIND.SK_LocalVariableSymbol:
id = MessageID.SK_VARIABLE;
break;
case SYMKIND.SK_PropertySymbol:
id = MessageID.SK_PROPERTY;
break;
case SYMKIND.SK_EventSymbol:
id = MessageID.SK_EVENT;
break;
case SYMKIND.SK_TypeParameterSymbol:
id = MessageID.SK_TYVAR;
break;
default:
Debug.Assert(false, "impossible sk");
id = MessageID.SK_UNKNOWN;
break;
}
ErrId(out psz, id);
}
/*
* Create a fill-in string describing a parameter list.
* Does NOT include ()
*/
private void ErrAppendParamList(TypeArray @params, bool isVarargs, bool isParamArray)
{
if (null == @params)
return;
for (int i = 0; i < @params.Count; i++)
{
if (i > 0)
{
ErrAppendString(", ");
}
if (isParamArray && i == @params.Count - 1)
{
ErrAppendString("params ");
}
// parameter type name
ErrAppendType(@params[i], null);
}
if (isVarargs)
{
if (@params.Count != 0)
{
ErrAppendString(", ");
}
ErrAppendString("...");
}
}
private void ErrAppendString(string str)
{
m_strBuilder.Append(str);
}
private void ErrAppendChar(char ch)
{
m_strBuilder.Append(ch);
}
private void ErrAppendPrintf(string format, params object[] args)
{
ErrAppendString(string.Format(CultureInfo.InvariantCulture, format, args));
}
private void ErrAppendName(Name name)
{
if (name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
ErrAppendString("this");
}
else
{
ErrAppendString(name.Text);
}
}
private void ErrAppendMethodParentSym(MethodSymbol sym, SubstContext pcxt, out TypeArray substMethTyParams)
{
substMethTyParams = null;
ErrAppendParentSym(sym, pcxt);
}
private void ErrAppendParentSym(Symbol sym, SubstContext pctx)
{
ErrAppendParentCore(sym.parent, pctx);
}
private void ErrAppendParentCore(Symbol parent, SubstContext pctx)
{
if (null == parent)
return;
if (parent == getBSymmgr().GetRootNS())
return;
if (pctx != null && !pctx.FNop() && parent is AggregateSymbol agg && 0 != agg.GetTypeVarsAll().Count)
{
CType pType = GetTypeManager().SubstType(agg.getThisType(), pctx);
ErrAppendType(pType, null);
}
else
{
ErrAppendSym(parent, null);
}
ErrAppendChar('.');
}
private void ErrAppendTypeParameters(TypeArray @params, SubstContext pctx, bool forClass)
{
if (@params != null && @params.Count != 0)
{
ErrAppendChar('<');
ErrAppendType(@params[0], pctx);
for (int i = 1; i < @params.Count; i++)
{
ErrAppendString(",");
ErrAppendType(@params[i], pctx);
}
ErrAppendChar('>');
}
}
private void ErrAppendMethod(MethodSymbol meth, SubstContext pctx, bool fArgs)
{
if (meth.IsExpImpl() && meth.swtSlot)
{
ErrAppendParentSym(meth, pctx);
// Get the type args from the explicit impl type and substitute using pctx (if there is one).
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(meth.swtSlot.GetType(), pctx) as AggregateType);
ErrAppendSym(meth.swtSlot.Sym, ctx, fArgs);
// args already added
return;
}
if (meth.isPropertyAccessor())
{
PropertySymbol prop = meth.getProperty();
// this includes the parent class
ErrAppendSym(prop, pctx);
// add accessor name
if (prop.GetterMethod == meth)
{
ErrAppendString(".get");
}
else
{
Debug.Assert(meth == prop.SetterMethod);
ErrAppendString(".set");
}
// args already added
return;
}
if (meth.isEventAccessor())
{
EventSymbol @event = meth.getEvent();
// this includes the parent class
ErrAppendSym(@event, pctx);
// add accessor name
if (@event.methAdd == meth)
{
ErrAppendString(".add");
}
else
{
Debug.Assert(meth == @event.methRemove);
ErrAppendString(".remove");
}
// args already added
return;
}
TypeArray replacementTypeArray = null;
ErrAppendMethodParentSym(meth, pctx, out replacementTypeArray);
if (meth.IsConstructor())
{
// Use the name of the parent class instead of the name "<ctor>".
ErrAppendName(meth.getClass().name);
}
else if (meth.IsDestructor())
{
// Use the name of the parent class instead of the name "Finalize".
ErrAppendChar('~');
ErrAppendName(meth.getClass().name);
}
else if (meth.isConversionOperator())
{
// implicit/explicit
ErrAppendString(meth.isImplicit() ? "implicit" : "explicit");
ErrAppendString(" operator ");
// destination type name
ErrAppendType(meth.RetType, pctx);
}
else if (meth.isOperator)
{
// handle user defined operators
// map from CLS predefined names to "operator <X>"
ErrAppendString("operator ");
ErrAppendString(Operators.OperatorOfMethodName(meth.name));
}
else if (meth.IsExpImpl())
{
if (meth.errExpImpl != null)
ErrAppendType(meth.errExpImpl, pctx, fArgs);
}
else
{
// regular method
ErrAppendName(meth.name);
}
if (null == replacementTypeArray)
{
ErrAppendTypeParameters(meth.typeVars, pctx, false);
}
if (fArgs)
{
// append argument types
ErrAppendChar('(');
ErrAppendParamList(GetTypeManager().SubstTypeArray(meth.Params, pctx), meth.isVarargs, meth.isParamArray);
ErrAppendChar(')');
}
}
private void ErrAppendIndexer(IndexerSymbol indexer, SubstContext pctx)
{
ErrAppendString("this[");
ErrAppendParamList(GetTypeManager().SubstTypeArray(indexer.Params, pctx), false, indexer.isParamArray);
ErrAppendChar(']');
}
private void ErrAppendProperty(PropertySymbol prop, SubstContext pctx)
{
ErrAppendParentSym(prop, pctx);
if (prop.IsExpImpl() && prop.swtSlot.Sym != null)
{
SubstContext ctx = new SubstContext(GetTypeManager().SubstType(prop.swtSlot.GetType(), pctx) as AggregateType);
ErrAppendSym(prop.swtSlot.Sym, ctx);
}
else if (prop.IsExpImpl())
{
if (prop.errExpImpl != null)
ErrAppendType(prop.errExpImpl, pctx, false);
if (prop is IndexerSymbol indexer)
{
ErrAppendChar('.');
ErrAppendIndexer(indexer, pctx);
}
}
else if (prop is IndexerSymbol indexer)
{
ErrAppendIndexer(indexer, pctx);
}
else
{
ErrAppendName(prop.name);
}
}
private void ErrAppendEvent(EventSymbol @event, SubstContext pctx)
{
}
private void ErrAppendId(MessageID id)
{
string str;
ErrId(out str, id);
ErrAppendString(str);
}
/*
* Create a fill-in string describing a symbol.
*/
private void ErrAppendSym(Symbol sym, SubstContext pctx)
{
ErrAppendSym(sym, pctx, true);
}
private void ErrAppendSym(Symbol sym, SubstContext pctx, bool fArgs)
{
switch (sym.getKind())
{
case SYMKIND.SK_AggregateDeclaration:
ErrAppendSym(((AggregateDeclaration)sym).Agg(), pctx);
break;
case SYMKIND.SK_AggregateSymbol:
{
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(sym as AggregateSymbol);
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else
{
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
ErrAppendTypeParameters(((AggregateSymbol)sym).GetTypeVars(), pctx, true);
}
break;
}
case SYMKIND.SK_MethodSymbol:
ErrAppendMethod((MethodSymbol)sym, pctx, fArgs);
break;
case SYMKIND.SK_PropertySymbol:
ErrAppendProperty((PropertySymbol)sym, pctx);
break;
case SYMKIND.SK_EventSymbol:
ErrAppendEvent((EventSymbol)sym, pctx);
break;
case SYMKIND.SK_AssemblyQualifiedNamespaceSymbol:
case SYMKIND.SK_NamespaceSymbol:
if (sym == getBSymmgr().GetRootNS())
{
ErrAppendId(MessageID.GlobalNamespace);
}
else
{
ErrAppendParentSym(sym, null);
ErrAppendName(sym.name);
}
break;
case SYMKIND.SK_FieldSymbol:
ErrAppendParentSym(sym, pctx);
ErrAppendName(sym.name);
break;
case SYMKIND.SK_TypeParameterSymbol:
if (null == sym.name)
{
var parSym = (TypeParameterSymbol)sym;
// It's a standard type variable.
if (parSym.IsMethodTypeParameter())
ErrAppendChar('!');
ErrAppendChar('!');
ErrAppendPrintf("{0}", parSym.GetIndexInTotalParameters());
}
else
ErrAppendName(sym.name);
break;
case SYMKIND.SK_LocalVariableSymbol:
// Generate symbol name.
ErrAppendName(sym.name);
break;
default:
// Shouldn't happen.
Debug.Assert(false, $"Bad symbol kind: {sym.getKind()}");
break;
}
}
private void ErrAppendType(CType pType, SubstContext pCtx)
{
ErrAppendType(pType, pCtx, true);
}
private void ErrAppendType(CType pType, SubstContext pctx, bool fArgs)
{
if (pctx != null)
{
if (!pctx.FNop())
{
pType = GetTypeManager().SubstType(pType, pctx);
}
// We shouldn't use the SubstContext again so set it to NULL.
pctx = null;
}
switch (pType.GetTypeKind())
{
case TypeKind.TK_AggregateType:
{
AggregateType pAggType = (AggregateType)pType;
// Check for a predefined class with a special "nice" name for
// error reported.
string text = PredefinedTypes.GetNiceName(pAggType.getAggregate());
if (text != null)
{
// Found a nice name.
ErrAppendString(text);
}
else
{
if (pAggType.outerType != null)
{
ErrAppendType(pAggType.outerType, pctx);
ErrAppendChar('.');
}
else
{
// In a namespace.
ErrAppendParentSym(pAggType.getAggregate(), pctx);
}
ErrAppendName(pAggType.getAggregate().name);
}
ErrAppendTypeParameters(pAggType.GetTypeArgsThis(), pctx, true);
break;
}
case TypeKind.TK_TypeParameterType:
if (null == pType.GetName())
{
var tpType = (TypeParameterType)pType;
// It's a standard type variable.
if (tpType.IsMethodTypeParameter())
{
ErrAppendChar('!');
}
ErrAppendChar('!');
ErrAppendPrintf("{0}", tpType.GetIndexInTotalParameters());
}
else
{
ErrAppendName(pType.GetName());
}
break;
case TypeKind.TK_ErrorType:
ErrorType err = (ErrorType)pType;
if (err.HasParent)
{
Debug.Assert(err.nameText != null && err.typeArgs != null);
ErrAppendName(err.nameText);
ErrAppendTypeParameters(err.typeArgs, pctx, true);
}
else
{
// Load the string "<error>".
Debug.Assert(null == err.typeArgs);
ErrAppendId(MessageID.ERRORSYM);
}
break;
case TypeKind.TK_NullType:
// Load the string "<null>".
ErrAppendId(MessageID.NULL);
break;
case TypeKind.TK_MethodGroupType:
ErrAppendId(MessageID.MethodGroup);
break;
case TypeKind.TK_ArgumentListType:
ErrAppendString(TokenFacts.GetText(TokenKind.ArgList));
break;
case TypeKind.TK_ArrayType:
{
CType elementType = ((ArrayType)pType).GetBaseElementType();
if (null == elementType)
{
Debug.Assert(false, "No element type");
break;
}
ErrAppendType(elementType, pctx);
for (elementType = pType;
elementType is ArrayType arrType;
elementType = arrType.GetElementType())
{
int rank = arrType.rank;
// Add [] with (rank-1) commas inside
ErrAppendChar('[');
// known rank.
if (rank == 1)
{
if (!arrType.IsSZArray)
{
ErrAppendChar('*');
}
}
else
{
for (int i = rank; i > 1; --i)
{
ErrAppendChar(',');
}
}
ErrAppendChar(']');
}
break;
}
case TypeKind.TK_VoidType:
ErrAppendName(GetNameManager().Lookup(TokenFacts.GetText(TokenKind.Void)));
break;
case TypeKind.TK_ParameterModifierType:
ParameterModifierType mod = (ParameterModifierType)pType;
// add ref or out
ErrAppendString(mod.isOut ? "out " : "ref ");
// add base type name
ErrAppendType(mod.GetParameterType(), pctx);
break;
case TypeKind.TK_PointerType:
// Generate the base type.
ErrAppendType(((PointerType)pType).GetReferentType(), pctx);
{
// add the trailing *
ErrAppendChar('*');
}
break;
case TypeKind.TK_NullableType:
ErrAppendType(((NullableType)pType).GetUnderlyingType(), pctx);
ErrAppendChar('?');
break;
default:
// Shouldn't happen.
Debug.Assert(false, "Bad type kind");
break;
}
}
// Returns true if the argument could be converted to a string.
public bool ErrArgToString(out string psz, ErrArg parg, out bool fUserStrings)
{
fUserStrings = false;
psz = null;
bool result = true;
switch (parg.eak)
{
case ErrArgKind.Ids:
ErrId(out psz, parg.ids);
break;
case ErrArgKind.SymKind:
ErrSK(out psz, parg.sk);
break;
case ErrArgKind.Type:
BeginString();
ErrAppendType(parg.pType, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Sym:
BeginString();
ErrAppendSym(parg.sym, null);
EndString(out psz);
fUserStrings = true;
break;
case ErrArgKind.Name:
if (parg.name == NameManager.GetPredefinedName(PredefinedName.PN_INDEXERINTERNAL))
{
psz = "this";
}
else
{
psz = parg.name.Text;
}
break;
case ErrArgKind.Str:
psz = parg.psz;
break;
case ErrArgKind.SymWithType:
{
SubstContext ctx = new SubstContext(parg.swtMemo.ats, null);
BeginString();
ErrAppendSym(parg.swtMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
case ErrArgKind.MethWithInst:
{
SubstContext ctx = new SubstContext(parg.mpwiMemo.ats, parg.mpwiMemo.typeArgs);
BeginString();
ErrAppendSym(parg.mpwiMemo.sym, ctx, true);
EndString(out psz);
fUserStrings = true;
break;
}
default:
result = false;
break;
}
return result;
}
private NameManager GetNameManager()
{
return m_globalSymbols.GetNameManager();
}
private TypeManager GetTypeManager()
{
return m_globalSymbols.GetTypes();
}
private BSYMMGR getBSymmgr()
{
return m_globalSymbols.GetGlobalSymbols();
}
private int GetTypeID(CType type)
{
return 0;
}
private void ErrId(out string s, MessageID id)
{
s = ErrorFacts.GetMessage(id);
}
}
}
| |
// ============================================================
// Name: UMABonePoseMixerWindow
// Author: Eli Curtz
// Copyright: (c) 2013 Eli Curtz
// ============================================================
#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.Text;
using System.Collections.Generic;
namespace UMA.PoseTools
{
public class UMABonePoseMixerWindow : EditorWindow
{
public Transform skeleton = null;
public UnityEngine.Object poseFolder = null;
public UMABonePose newComponent = null;
public string poseName = "";
private Dictionary<UMABonePose, float> poseComponents = new Dictionary<UMABonePose, float>();
private Dictionary<string, float> boneComponents = new Dictionary<string, float>();
public void EnforceFolder(ref UnityEngine.Object folderObject)
{
if (folderObject != null)
{
string destpath = AssetDatabase.GetAssetPath(folderObject);
if (string.IsNullOrEmpty(destpath))
{
folderObject = null;
}
else if (!System.IO.Directory.Exists(destpath))
{
destpath = destpath.Substring(0, destpath.LastIndexOf('/'));
folderObject = AssetDatabase.LoadMainAssetAtPath(destpath);
}
}
}
void OnGUI()
{
EditorGUIUtility.LookLikeControls();
Transform newSkeleton = EditorGUILayout.ObjectField("Rig Prefab", skeleton, typeof(Transform), true) as Transform;
if (skeleton != newSkeleton)
{
skeleton = newSkeleton;
boneComponents = new Dictionary<string, float>();
Transform[] transforms = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (Transform bone in transforms)
{
boneComponents.Add(bone.name, 1f);
}
}
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Poses");
EditorGUI.indentLevel++;
UMABonePose changedPose = null;
UMABonePose deletedPose = null;
float sliderVal = 0;
List<string> activeBones = new List<string>();
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
GUILayout.BeginHorizontal();
sliderVal = EditorGUILayout.Slider(entry.Key.name, entry.Value, 0f, 2f);
if (sliderVal != entry.Value)
{
changedPose = entry.Key;
}
if (GUILayout.Button("-", GUILayout.Width(20f)))
{
deletedPose = entry.Key;
}
else
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (!activeBones.Contains(pose.bone))
{
activeBones.Add(pose.bone);
}
}
}
GUILayout.EndHorizontal();
}
if (changedPose != null)
{
poseComponents[changedPose] = sliderVal;
}
if (deletedPose != null)
{
poseComponents.Remove(deletedPose);
}
GUILayout.BeginHorizontal();
newComponent = EditorGUILayout.ObjectField(newComponent, typeof(UMABonePose), false) as UMABonePose;
GUI.enabled = (newComponent != null);
if (GUILayout.Button("+", GUILayout.Width(30f)))
{
poseComponents.Add(newComponent, 1f);
newComponent = null;
}
GUI.enabled = true;
GUILayout.EndHorizontal();
EditorGUI.indentLevel--;
EditorGUILayout.Space();
EditorGUILayout.LabelField("Component Bones");
EditorGUI.indentLevel++;
foreach (string bone in activeBones)
{
GUILayout.BeginHorizontal();
if (boneComponents.ContainsKey(bone))
{
boneComponents[bone] = EditorGUILayout.Slider(bone, boneComponents[bone], 0f, 2f);
}
GUILayout.EndHorizontal();
}
EditorGUI.indentLevel--;
GUILayout.BeginHorizontal();
if (GUILayout.Button("Left"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 1f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 0f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Right"))
{
foreach (string bone in activeBones)
{
if (bone.Contains("Left") || bone.Contains("left"))
{
boneComponents[bone] = 0f;
}
else if (bone.Contains("Right") || bone.Contains("right"))
{
boneComponents[bone] = 1f;
}
else
{
boneComponents[bone] = 0.5f;
}
}
}
if (GUILayout.Button("Mirror"))
{
foreach (string bone in activeBones)
{
boneComponents[bone] = Mathf.Max(1f - boneComponents[bone], 0f);
}
if (poseName.EndsWith("_L"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "R";
}
else if (poseName.EndsWith("_R"))
{
poseName = poseName.Substring(0, poseName.Length - 1) + "L";
}
}
GUILayout.EndHorizontal();
EditorGUILayout.Space();
poseFolder = EditorGUILayout.ObjectField("Pose Folder", poseFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object;
EnforceFolder(ref poseFolder);
GUILayout.BeginHorizontal();
poseName = EditorGUILayout.TextField("New Pose", poseName);
if ((skeleton == null) || (poseFolder == null) || (poseComponents.Count < 1) || (poseName.Length < 1))
{
GUI.enabled = false;
}
if (GUILayout.Button("Build", GUILayout.Width(60f)))
{
string folderPath = AssetDatabase.GetAssetPath(poseFolder);
UMABonePose newPose = CreatePoseAsset(folderPath, poseName);
Transform[] sourceBones = UMABonePose.GetTransformsInPrefab(skeleton);
foreach (string bone in activeBones)
{
Transform source = System.Array.Find<Transform>(sourceBones, entry => entry.name == bone);
if (source != null)
{
Vector3 position = source.localPosition;
Quaternion rotation = source.localRotation;
Vector3 scale = source.localScale;
bool include = false;
foreach (KeyValuePair<UMABonePose, float> entry in poseComponents)
{
float strength = entry.Value * boneComponents[bone];
if (strength > 0f)
{
foreach (UMABonePose.PoseBone pose in entry.Key.poses)
{
if (pose.bone == bone)
{
position += pose.position * strength;
Quaternion posedRotation = rotation * pose.rotation;
rotation = Quaternion.Slerp(rotation, posedRotation, strength);
scale = Vector3.Slerp(scale, pose.scale, strength);
}
}
include = true;
}
}
if (include)
{
newPose.AddBone(source, position, rotation, scale);
}
}
else
{
Debug.LogWarning("Bone not found in skeleton: " + bone);
}
}
EditorUtility.SetDirty(newPose);
AssetDatabase.SaveAssets();
}
GUI.enabled = true;
GUILayout.EndHorizontal();
}
public static UMABonePose CreatePoseAsset(string assetFolder, string assetName)
{
if (!System.IO.Directory.Exists(assetFolder))
{
System.IO.Directory.CreateDirectory(assetFolder);
}
UMABonePose asset = ScriptableObject.CreateInstance<UMABonePose>();
AssetDatabase.CreateAsset(asset, assetFolder + "/" + assetName + ".asset");
return asset;
}
[MenuItem("UMA/Pose Tools/UMA Bone Pose Mixer")]
public static void OpenUMABonePoseBuildWindow()
{
EditorWindow win = EditorWindow.GetWindow(typeof(UMABonePoseMixerWindow));
#if !UNITY_4_6 && !UNITY_5_0
win.titleContent.text = "Pose Mixer";
#else
win.title = "Pose Mixer";
#endif
}
}
}
#endif
| |
// 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.Globalization;
using System.IO;
using System.Text;
namespace System.Net.Http.Headers
{
public class WarningHeaderValue : ICloneable
{
private int _code;
private string _agent;
private string _text;
private DateTimeOffset? _date;
public int Code
{
get { return _code; }
}
public string Agent
{
get { return _agent; }
}
public string Text
{
get { return _text; }
}
public DateTimeOffset? Date
{
get { return _date; }
}
public WarningHeaderValue(int code, string agent, string text)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, nameof(text));
_code = code;
_agent = agent;
_text = text;
}
public WarningHeaderValue(int code, string agent, string text, DateTimeOffset date)
{
CheckCode(code);
CheckAgent(agent);
HeaderUtilities.CheckValidQuotedString(text, nameof(text));
_code = code;
_agent = agent;
_text = text;
_date = date;
}
private WarningHeaderValue()
{
}
private WarningHeaderValue(WarningHeaderValue source)
{
Debug.Assert(source != null);
_code = source._code;
_agent = source._agent;
_text = source._text;
_date = source._date;
}
public override string ToString()
{
StringBuilder sb = StringBuilderCache.Acquire();
// Warning codes are always 3 digits according to RFC2616
sb.Append(_code.ToString("000", NumberFormatInfo.InvariantInfo));
sb.Append(' ');
sb.Append(_agent);
sb.Append(' ');
sb.Append(_text);
if (_date.HasValue)
{
sb.Append(" \"");
sb.Append(HttpRuleParser.DateToString(_date.Value));
sb.Append('\"');
}
return StringBuilderCache.GetStringAndRelease(sb);
}
public override bool Equals(object obj)
{
WarningHeaderValue other = obj as WarningHeaderValue;
if (other == null)
{
return false;
}
// 'agent' is a host/token, i.e. use case-insensitive comparison. Use case-sensitive comparison for 'text'
// since it is a quoted string.
if ((_code != other._code) || (!string.Equals(_agent, other._agent, StringComparison.OrdinalIgnoreCase)) ||
(!string.Equals(_text, other._text, StringComparison.Ordinal)))
{
return false;
}
// We have a date set. Verify 'other' has also a date that matches our value.
if (_date.HasValue)
{
return other._date.HasValue && (_date.Value == other._date.Value);
}
// We don't have a date. If 'other' has a date, we're not equal.
return !other._date.HasValue;
}
public override int GetHashCode()
{
int result = _code.GetHashCode() ^
StringComparer.OrdinalIgnoreCase.GetHashCode(_agent) ^
_text.GetHashCode();
if (_date.HasValue)
{
result = result ^ _date.Value.GetHashCode();
}
return result;
}
public static WarningHeaderValue Parse(string input)
{
int index = 0;
return (WarningHeaderValue)GenericHeaderParser.SingleValueWarningParser.ParseValue(input, null, ref index);
}
public static bool TryParse(string input, out WarningHeaderValue parsedValue)
{
int index = 0;
object output;
parsedValue = null;
if (GenericHeaderParser.SingleValueWarningParser.TryParseValue(input, null, ref index, out output))
{
parsedValue = (WarningHeaderValue)output;
return true;
}
return false;
}
internal static int GetWarningLength(string input, int startIndex, out object parsedValue)
{
Debug.Assert(startIndex >= 0);
parsedValue = null;
if (string.IsNullOrEmpty(input) || (startIndex >= input.Length))
{
return 0;
}
// Read <code> in '<code> <agent> <text> ["<date>"]'
int code;
int current = startIndex;
if (!TryReadCode(input, ref current, out code))
{
return 0;
}
// Read <agent> in '<code> <agent> <text> ["<date>"]'
string agent;
if (!TryReadAgent(input, current, ref current, out agent))
{
return 0;
}
// Read <text> in '<code> <agent> <text> ["<date>"]'
int textLength = 0;
int textStartIndex = current;
if (HttpRuleParser.GetQuotedStringLength(input, current, out textLength) != HttpParseResult.Parsed)
{
return 0;
}
current = current + textLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
DateTimeOffset? date = null;
if (!TryReadDate(input, ref current, out date))
{
return 0;
}
WarningHeaderValue result = new WarningHeaderValue();
result._code = code;
result._agent = agent;
result._text = input.Substring(textStartIndex, textLength);
result._date = date;
parsedValue = result;
return current - startIndex;
}
private static bool TryReadAgent(string input, int startIndex, ref int current, out string agent)
{
agent = null;
int agentLength = HttpRuleParser.GetHostLength(input, startIndex, true, out agent);
if (agentLength == 0)
{
return false;
}
current = current + agentLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// At least one whitespace required after <agent>. Also make sure we have characters left for <text>
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadCode(string input, ref int current, out int code)
{
code = 0;
int codeLength = HttpRuleParser.GetNumberLength(input, current, false);
// code must be a 3 digit value. We accept less digits, but we don't accept more.
if ((codeLength == 0) || (codeLength > 3))
{
return false;
}
if (!HeaderUtilities.TryParseInt32(input, current, codeLength, out code))
{
Debug.Assert(false, "Unable to parse value even though it was parsed as <=3 digits string. Input: '" +
input + "', Current: " + current + ", CodeLength: " + codeLength);
return false;
}
current = current + codeLength;
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Make sure the number is followed by at least one whitespace and that we have characters left to parse.
if ((whitespaceLength == 0) || (current == input.Length))
{
return false;
}
return true;
}
private static bool TryReadDate(string input, ref int current, out DateTimeOffset? date)
{
date = null;
// Make sure we have at least one whitespace between <text> and <date> (if we have <date>)
int whitespaceLength = HttpRuleParser.GetWhitespaceLength(input, current);
current = current + whitespaceLength;
// Read <date> in '<code> <agent> <text> ["<date>"]'
if ((current < input.Length) && (input[current] == '"'))
{
if (whitespaceLength == 0)
{
return false; // we have characters after <text> but they were not separated by a whitespace
}
current++; // skip opening '"'
// Find the closing '"'
int dateStartIndex = current;
while (current < input.Length)
{
if (input[current] == '"')
{
break;
}
current++;
}
if ((current == input.Length) || (current == dateStartIndex))
{
return false; // we couldn't find the closing '"' or we have an empty quoted string.
}
DateTimeOffset temp;
if (!HttpRuleParser.TryStringToDate(input.Substring(dateStartIndex, current - dateStartIndex), out temp))
{
return false;
}
date = temp;
current++; // skip closing '"'
current = current + HttpRuleParser.GetWhitespaceLength(input, current);
}
return true;
}
object ICloneable.Clone()
{
return new WarningHeaderValue(this);
}
private static void CheckCode(int code)
{
if ((code < 0) || (code > 999))
{
throw new ArgumentOutOfRangeException(nameof(code));
}
}
private static void CheckAgent(string agent)
{
if (string.IsNullOrEmpty(agent))
{
throw new ArgumentException(SR.net_http_argument_empty_string, nameof(agent));
}
// 'receivedBy' can either be a host or a token. Since a token is a valid host, we only verify if the value
// is a valid host.
string host = null;
if (HttpRuleParser.GetHostLength(agent, 0, true, out host) != agent.Length)
{
throw new FormatException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, agent));
}
}
}
}
| |
using UnityEngine;
using System.Collections;
/// <summary>
/// This script wraps photons connect functionality and defines several of the callbacks Photon invokes
/// </summary>
public class MultiplayerConnector : MonoBehaviour
{
public static bool IsHost = false;
public static bool QuitOnLogout = false;
public static bool IsConnected
{
get
{
return PhotonNetwork.offlineMode == false && PhotonNetwork.connectionState == ConnectionState.Connected;
}
}
static TypedLobby m_Lobby;
public static TypedLobby Lobby
{
get
{
if( m_Lobby == null )
{
m_Lobby = new TypedLobby( "SkyArenaLobby", LobbyType.SqlLobby );
}
return m_Lobby;
}
}
void Start()
{
DontDestroyOnLoad( gameObject );
}
/// <summary>
/// Call this to start the connection process to the Photon Cloud
/// </summary>
public void Connect()
{
//If we are in any other state than disconnected, that means we are either already
//connected, or in the process of connecting. So we don't want to do it again
if( PhotonNetwork.connectionState != ConnectionState.Disconnected )
{
return;
}
//This tells Photon to make sure all players - which are in the same room - always load the same scene
PhotonNetwork.automaticallySyncScene = true;
//Don't join the default lobby on start, we do this ourselves in OnConnectedToMaster()
PhotonNetwork.autoJoinLobby = false;
try
{
PhotonNetwork.ConnectUsingSettings( "1.0" );
}
catch
{
Debug.LogWarning( "Couldn't connect to server" );
}
}
/// <summary>
/// For when you are done with Photon
/// </summary>
public void Disconnect()
{
if( PhotonNetwork.connected == false )
{
return;
}
PhotonNetwork.Disconnect();
}
/// <summary>
/// Called when we are connected to Photon
/// </summary>
void OnConnectedToPhoton()
{
if( IsHost == true )
{
return;
}
PhotonNetwork.playerName = "Keiran";
}
/// <summary>
/// Called when we are connected to Photons Master Server
/// </summary>
void OnConnectedToMaster()
{
PhotonNetwork.JoinLobby( Lobby );
}
/// <summary>
/// When we joined the lobby after connecting to Photon, we want to immediately join the demo room, or create it if it doesn't exist
/// </summary>
void OnJoinedLobby()
{
if( IsHost == true )
{
return;
}
if( QuitOnLogout == true )
{
Application.Quit();
return;
}
}
void OnPhotonCreateRoomFailed()
{
if( IsHost == true )
{
return;
}
}
void OnPhotonJoinRoomFailed()
{
if( IsHost == true )
{
return;
}
}
/// <summary>
/// Called when we created a Photon room.
/// </summary>
void OnCreatedRoom()
{
Debug.Log( "OnCreatedRoom" );
}
/// <summary>
/// Called when we successfully joined a room. It is also called if we created the room.
/// </summary>
void OnJoinedRoom()
{
if (PhotonNetwork.isMasterClient)
{
MapQueueEntry currentMap = MapQueue.GetCurrentMap();
Debug.Log("OnJoinedRoom. Loading map: " + currentMap);
if (currentMap.Equals(MapQueueEntry.None))
{
PhotonNetwork.LeaveRoom();
return;
}
//Pause the message queue. While unity is loading a new level, updates from Photon are skipped.
//So we have to tell Photon to wait until we resume the queue again after the level is loaded. See MultiplayerConnector.OnLevelWasLoaded
//PhotonNetwork.isMessageQueueRunning = false;
// PhotonNetwork.LoadLevel will internally handle isMessageQueueRunning.
// It will also load the correct scene on all clients automatically, so this call is only needed by the Master Client.
PhotonNetwork.LoadLevel(currentMap.Name);
}
else
{
Debug.Log("OnJoinedRoom. LoadedLevel: " + Application.loadedLevelName);
}
}
/// <summary>
/// Called by Unity after Application.LoadLevel is completed
/// </summary>
/// <param name="level">The index of the level that was loaded</param>
void OnLevelWasLoaded( int level )
{
Debug.Log( "OnLevelWasLoaded: " + Application.loadedLevelName );
//Resume the Photon message queue so we get all the updates.
//All updates that were sent during the level load were cached and are dispatched now so we can handle them properly.
PhotonNetwork.isMessageQueueRunning = true;
//Time is frozen at the end of a round, so make sure that we resume it when we load a new level
Time.timeScale = 1f;
}
void OnDisconnectedFromPhoton()
{
Application.LoadLevel(0);
}
void OnFailedToConnectToPhoton( DisconnectCause cause )
{
if( IsHost == true )
{
return;
}
Debug.LogWarning( "OnFailedToConnectToPhoton: " + cause );
}
void OnConnectionFail( DisconnectCause cause )
{
if( IsHost == true )
{
return;
}
Debug.LogWarning( "OnConnectionFail: " + cause );
}
void OnLeftRoom()
{
Debug.Log( "OnLeftRoom" );
if( IsHost == true )
{
return;
}
Application.LoadLevel(0);
}
public static MultiplayerConnector instance;
public static MultiplayerConnector Instance
{
get
{
if( instance == null )
{
CreateInstance();
}
return instance;
}
}
public static void CreateInstance()
{
if( instance == null )
{
GameObject connectorObject = GameObject.Find( "MultiplayerConnector" );
if( connectorObject == null )
{
connectorObject = new GameObject( "MultiplayerConnector" );
connectorObject.AddComponent<MultiplayerConnector>();
}
instance = connectorObject.GetComponent<MultiplayerConnector>();
}
}
}
| |
#region Copyright notice and license
// Copyright 2015-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Grpc.Core.Logging;
using Grpc.Core.Utils;
namespace Grpc.Core.Internal
{
/// <summary>
/// Provides access to all native methods provided by <c>NativeExtension</c>.
/// An extra level of indirection is added to P/Invoke calls to allow intelligent loading
/// of the right configuration of the native extension based on current platform, architecture etc.
/// </summary>
internal class NativeMethods
{
#region Native methods
public readonly Delegates.grpcsharp_init_delegate grpcsharp_init;
public readonly Delegates.grpcsharp_shutdown_delegate grpcsharp_shutdown;
public readonly Delegates.grpcsharp_version_string_delegate grpcsharp_version_string;
public readonly Delegates.grpcsharp_batch_context_create_delegate grpcsharp_batch_context_create;
public readonly Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate grpcsharp_batch_context_recv_initial_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_message_length_delegate grpcsharp_batch_context_recv_message_length;
public readonly Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate grpcsharp_batch_context_recv_message_to_buffer;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate grpcsharp_batch_context_recv_status_on_client_status;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate grpcsharp_batch_context_recv_status_on_client_details;
public readonly Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate grpcsharp_batch_context_server_rpc_new_call;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate grpcsharp_batch_context_server_rpc_new_method;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate grpcsharp_batch_context_server_rpc_new_host;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate grpcsharp_batch_context_server_rpc_new_deadline;
public readonly Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate grpcsharp_batch_context_server_rpc_new_request_metadata;
public readonly Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate grpcsharp_batch_context_recv_close_on_server_cancelled;
public readonly Delegates.grpcsharp_batch_context_destroy_delegate grpcsharp_batch_context_destroy;
public readonly Delegates.grpcsharp_composite_call_credentials_create_delegate grpcsharp_composite_call_credentials_create;
public readonly Delegates.grpcsharp_call_credentials_release_delegate grpcsharp_call_credentials_release;
public readonly Delegates.grpcsharp_call_cancel_delegate grpcsharp_call_cancel;
public readonly Delegates.grpcsharp_call_cancel_with_status_delegate grpcsharp_call_cancel_with_status;
public readonly Delegates.grpcsharp_call_start_unary_delegate grpcsharp_call_start_unary;
public readonly Delegates.grpcsharp_call_start_client_streaming_delegate grpcsharp_call_start_client_streaming;
public readonly Delegates.grpcsharp_call_start_server_streaming_delegate grpcsharp_call_start_server_streaming;
public readonly Delegates.grpcsharp_call_start_duplex_streaming_delegate grpcsharp_call_start_duplex_streaming;
public readonly Delegates.grpcsharp_call_send_message_delegate grpcsharp_call_send_message;
public readonly Delegates.grpcsharp_call_send_close_from_client_delegate grpcsharp_call_send_close_from_client;
public readonly Delegates.grpcsharp_call_send_status_from_server_delegate grpcsharp_call_send_status_from_server;
public readonly Delegates.grpcsharp_call_recv_message_delegate grpcsharp_call_recv_message;
public readonly Delegates.grpcsharp_call_recv_initial_metadata_delegate grpcsharp_call_recv_initial_metadata;
public readonly Delegates.grpcsharp_call_start_serverside_delegate grpcsharp_call_start_serverside;
public readonly Delegates.grpcsharp_call_send_initial_metadata_delegate grpcsharp_call_send_initial_metadata;
public readonly Delegates.grpcsharp_call_set_credentials_delegate grpcsharp_call_set_credentials;
public readonly Delegates.grpcsharp_call_get_peer_delegate grpcsharp_call_get_peer;
public readonly Delegates.grpcsharp_call_destroy_delegate grpcsharp_call_destroy;
public readonly Delegates.grpcsharp_channel_args_create_delegate grpcsharp_channel_args_create;
public readonly Delegates.grpcsharp_channel_args_set_string_delegate grpcsharp_channel_args_set_string;
public readonly Delegates.grpcsharp_channel_args_set_integer_delegate grpcsharp_channel_args_set_integer;
public readonly Delegates.grpcsharp_channel_args_destroy_delegate grpcsharp_channel_args_destroy;
public readonly Delegates.grpcsharp_ssl_credentials_create_delegate grpcsharp_ssl_credentials_create;
public readonly Delegates.grpcsharp_composite_channel_credentials_create_delegate grpcsharp_composite_channel_credentials_create;
public readonly Delegates.grpcsharp_channel_credentials_release_delegate grpcsharp_channel_credentials_release;
public readonly Delegates.grpcsharp_insecure_channel_create_delegate grpcsharp_insecure_channel_create;
public readonly Delegates.grpcsharp_secure_channel_create_delegate grpcsharp_secure_channel_create;
public readonly Delegates.grpcsharp_channel_create_call_delegate grpcsharp_channel_create_call;
public readonly Delegates.grpcsharp_channel_check_connectivity_state_delegate grpcsharp_channel_check_connectivity_state;
public readonly Delegates.grpcsharp_channel_watch_connectivity_state_delegate grpcsharp_channel_watch_connectivity_state;
public readonly Delegates.grpcsharp_channel_get_target_delegate grpcsharp_channel_get_target;
public readonly Delegates.grpcsharp_channel_destroy_delegate grpcsharp_channel_destroy;
public readonly Delegates.grpcsharp_sizeof_grpc_event_delegate grpcsharp_sizeof_grpc_event;
public readonly Delegates.grpcsharp_completion_queue_create_delegate grpcsharp_completion_queue_create;
public readonly Delegates.grpcsharp_completion_queue_shutdown_delegate grpcsharp_completion_queue_shutdown;
public readonly Delegates.grpcsharp_completion_queue_next_delegate grpcsharp_completion_queue_next;
public readonly Delegates.grpcsharp_completion_queue_pluck_delegate grpcsharp_completion_queue_pluck;
public readonly Delegates.grpcsharp_completion_queue_destroy_delegate grpcsharp_completion_queue_destroy;
public readonly Delegates.gprsharp_free_delegate gprsharp_free;
public readonly Delegates.grpcsharp_metadata_array_create_delegate grpcsharp_metadata_array_create;
public readonly Delegates.grpcsharp_metadata_array_add_delegate grpcsharp_metadata_array_add;
public readonly Delegates.grpcsharp_metadata_array_count_delegate grpcsharp_metadata_array_count;
public readonly Delegates.grpcsharp_metadata_array_get_key_delegate grpcsharp_metadata_array_get_key;
public readonly Delegates.grpcsharp_metadata_array_get_value_delegate grpcsharp_metadata_array_get_value;
public readonly Delegates.grpcsharp_metadata_array_get_value_length_delegate grpcsharp_metadata_array_get_value_length;
public readonly Delegates.grpcsharp_metadata_array_destroy_full_delegate grpcsharp_metadata_array_destroy_full;
public readonly Delegates.grpcsharp_redirect_log_delegate grpcsharp_redirect_log;
public readonly Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate grpcsharp_metadata_credentials_create_from_plugin;
public readonly Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate grpcsharp_metadata_credentials_notify_from_plugin;
public readonly Delegates.grpcsharp_ssl_server_credentials_create_delegate grpcsharp_ssl_server_credentials_create;
public readonly Delegates.grpcsharp_server_credentials_release_delegate grpcsharp_server_credentials_release;
public readonly Delegates.grpcsharp_server_create_delegate grpcsharp_server_create;
public readonly Delegates.grpcsharp_server_add_insecure_http2_port_delegate grpcsharp_server_add_insecure_http2_port;
public readonly Delegates.grpcsharp_server_add_secure_http2_port_delegate grpcsharp_server_add_secure_http2_port;
public readonly Delegates.grpcsharp_server_start_delegate grpcsharp_server_start;
public readonly Delegates.grpcsharp_server_request_call_delegate grpcsharp_server_request_call;
public readonly Delegates.grpcsharp_server_cancel_all_calls_delegate grpcsharp_server_cancel_all_calls;
public readonly Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate grpcsharp_server_shutdown_and_notify_callback;
public readonly Delegates.grpcsharp_server_destroy_delegate grpcsharp_server_destroy;
public readonly Delegates.gprsharp_now_delegate gprsharp_now;
public readonly Delegates.gprsharp_inf_future_delegate gprsharp_inf_future;
public readonly Delegates.gprsharp_inf_past_delegate gprsharp_inf_past;
public readonly Delegates.gprsharp_convert_clock_type_delegate gprsharp_convert_clock_type;
public readonly Delegates.gprsharp_sizeof_timespec_delegate gprsharp_sizeof_timespec;
public readonly Delegates.grpcsharp_test_callback_delegate grpcsharp_test_callback;
public readonly Delegates.grpcsharp_test_nop_delegate grpcsharp_test_nop;
#endregion
public NativeMethods(UnmanagedLibrary library)
{
if (PlatformApis.IsLinux || PlatformApis.IsMacOSX)
{
this.grpcsharp_init = GetMethodDelegate<Delegates.grpcsharp_init_delegate>(library);
this.grpcsharp_shutdown = GetMethodDelegate<Delegates.grpcsharp_shutdown_delegate>(library);
this.grpcsharp_version_string = GetMethodDelegate<Delegates.grpcsharp_version_string_delegate>(library);
this.grpcsharp_batch_context_create = GetMethodDelegate<Delegates.grpcsharp_batch_context_create_delegate>(library);
this.grpcsharp_batch_context_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_initial_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_message_length = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_length_delegate>(library);
this.grpcsharp_batch_context_recv_message_to_buffer = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_message_to_buffer_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_status = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_status_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_details = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_details_delegate>(library);
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_call = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_call_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_method = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_method_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_host = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_host_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_deadline = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_deadline_delegate>(library);
this.grpcsharp_batch_context_server_rpc_new_request_metadata = GetMethodDelegate<Delegates.grpcsharp_batch_context_server_rpc_new_request_metadata_delegate>(library);
this.grpcsharp_batch_context_recv_close_on_server_cancelled = GetMethodDelegate<Delegates.grpcsharp_batch_context_recv_close_on_server_cancelled_delegate>(library);
this.grpcsharp_batch_context_destroy = GetMethodDelegate<Delegates.grpcsharp_batch_context_destroy_delegate>(library);
this.grpcsharp_composite_call_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_call_credentials_create_delegate>(library);
this.grpcsharp_call_credentials_release = GetMethodDelegate<Delegates.grpcsharp_call_credentials_release_delegate>(library);
this.grpcsharp_call_cancel = GetMethodDelegate<Delegates.grpcsharp_call_cancel_delegate>(library);
this.grpcsharp_call_cancel_with_status = GetMethodDelegate<Delegates.grpcsharp_call_cancel_with_status_delegate>(library);
this.grpcsharp_call_start_unary = GetMethodDelegate<Delegates.grpcsharp_call_start_unary_delegate>(library);
this.grpcsharp_call_start_client_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_client_streaming_delegate>(library);
this.grpcsharp_call_start_server_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_server_streaming_delegate>(library);
this.grpcsharp_call_start_duplex_streaming = GetMethodDelegate<Delegates.grpcsharp_call_start_duplex_streaming_delegate>(library);
this.grpcsharp_call_send_message = GetMethodDelegate<Delegates.grpcsharp_call_send_message_delegate>(library);
this.grpcsharp_call_send_close_from_client = GetMethodDelegate<Delegates.grpcsharp_call_send_close_from_client_delegate>(library);
this.grpcsharp_call_send_status_from_server = GetMethodDelegate<Delegates.grpcsharp_call_send_status_from_server_delegate>(library);
this.grpcsharp_call_recv_message = GetMethodDelegate<Delegates.grpcsharp_call_recv_message_delegate>(library);
this.grpcsharp_call_recv_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_recv_initial_metadata_delegate>(library);
this.grpcsharp_call_start_serverside = GetMethodDelegate<Delegates.grpcsharp_call_start_serverside_delegate>(library);
this.grpcsharp_call_send_initial_metadata = GetMethodDelegate<Delegates.grpcsharp_call_send_initial_metadata_delegate>(library);
this.grpcsharp_call_set_credentials = GetMethodDelegate<Delegates.grpcsharp_call_set_credentials_delegate>(library);
this.grpcsharp_call_get_peer = GetMethodDelegate<Delegates.grpcsharp_call_get_peer_delegate>(library);
this.grpcsharp_call_destroy = GetMethodDelegate<Delegates.grpcsharp_call_destroy_delegate>(library);
this.grpcsharp_channel_args_create = GetMethodDelegate<Delegates.grpcsharp_channel_args_create_delegate>(library);
this.grpcsharp_channel_args_set_string = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_string_delegate>(library);
this.grpcsharp_channel_args_set_integer = GetMethodDelegate<Delegates.grpcsharp_channel_args_set_integer_delegate>(library);
this.grpcsharp_channel_args_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_args_destroy_delegate>(library);
this.grpcsharp_ssl_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_credentials_create_delegate>(library);
this.grpcsharp_composite_channel_credentials_create = GetMethodDelegate<Delegates.grpcsharp_composite_channel_credentials_create_delegate>(library);
this.grpcsharp_channel_credentials_release = GetMethodDelegate<Delegates.grpcsharp_channel_credentials_release_delegate>(library);
this.grpcsharp_insecure_channel_create = GetMethodDelegate<Delegates.grpcsharp_insecure_channel_create_delegate>(library);
this.grpcsharp_secure_channel_create = GetMethodDelegate<Delegates.grpcsharp_secure_channel_create_delegate>(library);
this.grpcsharp_channel_create_call = GetMethodDelegate<Delegates.grpcsharp_channel_create_call_delegate>(library);
this.grpcsharp_channel_check_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_check_connectivity_state_delegate>(library);
this.grpcsharp_channel_watch_connectivity_state = GetMethodDelegate<Delegates.grpcsharp_channel_watch_connectivity_state_delegate>(library);
this.grpcsharp_channel_get_target = GetMethodDelegate<Delegates.grpcsharp_channel_get_target_delegate>(library);
this.grpcsharp_channel_destroy = GetMethodDelegate<Delegates.grpcsharp_channel_destroy_delegate>(library);
this.grpcsharp_sizeof_grpc_event = GetMethodDelegate<Delegates.grpcsharp_sizeof_grpc_event_delegate>(library);
this.grpcsharp_completion_queue_create = GetMethodDelegate<Delegates.grpcsharp_completion_queue_create_delegate>(library);
this.grpcsharp_completion_queue_shutdown = GetMethodDelegate<Delegates.grpcsharp_completion_queue_shutdown_delegate>(library);
this.grpcsharp_completion_queue_next = GetMethodDelegate<Delegates.grpcsharp_completion_queue_next_delegate>(library);
this.grpcsharp_completion_queue_pluck = GetMethodDelegate<Delegates.grpcsharp_completion_queue_pluck_delegate>(library);
this.grpcsharp_completion_queue_destroy = GetMethodDelegate<Delegates.grpcsharp_completion_queue_destroy_delegate>(library);
this.gprsharp_free = GetMethodDelegate<Delegates.gprsharp_free_delegate>(library);
this.grpcsharp_metadata_array_create = GetMethodDelegate<Delegates.grpcsharp_metadata_array_create_delegate>(library);
this.grpcsharp_metadata_array_add = GetMethodDelegate<Delegates.grpcsharp_metadata_array_add_delegate>(library);
this.grpcsharp_metadata_array_count = GetMethodDelegate<Delegates.grpcsharp_metadata_array_count_delegate>(library);
this.grpcsharp_metadata_array_get_key = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_key_delegate>(library);
this.grpcsharp_metadata_array_get_value = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_delegate>(library);
this.grpcsharp_metadata_array_get_value_length = GetMethodDelegate<Delegates.grpcsharp_metadata_array_get_value_length_delegate>(library);
this.grpcsharp_metadata_array_destroy_full = GetMethodDelegate<Delegates.grpcsharp_metadata_array_destroy_full_delegate>(library);
this.grpcsharp_redirect_log = GetMethodDelegate<Delegates.grpcsharp_redirect_log_delegate>(library);
this.grpcsharp_metadata_credentials_create_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_create_from_plugin_delegate>(library);
this.grpcsharp_metadata_credentials_notify_from_plugin = GetMethodDelegate<Delegates.grpcsharp_metadata_credentials_notify_from_plugin_delegate>(library);
this.grpcsharp_ssl_server_credentials_create = GetMethodDelegate<Delegates.grpcsharp_ssl_server_credentials_create_delegate>(library);
this.grpcsharp_server_credentials_release = GetMethodDelegate<Delegates.grpcsharp_server_credentials_release_delegate>(library);
this.grpcsharp_server_create = GetMethodDelegate<Delegates.grpcsharp_server_create_delegate>(library);
this.grpcsharp_server_add_insecure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_insecure_http2_port_delegate>(library);
this.grpcsharp_server_add_secure_http2_port = GetMethodDelegate<Delegates.grpcsharp_server_add_secure_http2_port_delegate>(library);
this.grpcsharp_server_start = GetMethodDelegate<Delegates.grpcsharp_server_start_delegate>(library);
this.grpcsharp_server_request_call = GetMethodDelegate<Delegates.grpcsharp_server_request_call_delegate>(library);
this.grpcsharp_server_cancel_all_calls = GetMethodDelegate<Delegates.grpcsharp_server_cancel_all_calls_delegate>(library);
this.grpcsharp_server_shutdown_and_notify_callback = GetMethodDelegate<Delegates.grpcsharp_server_shutdown_and_notify_callback_delegate>(library);
this.grpcsharp_server_destroy = GetMethodDelegate<Delegates.grpcsharp_server_destroy_delegate>(library);
this.gprsharp_now = GetMethodDelegate<Delegates.gprsharp_now_delegate>(library);
this.gprsharp_inf_future = GetMethodDelegate<Delegates.gprsharp_inf_future_delegate>(library);
this.gprsharp_inf_past = GetMethodDelegate<Delegates.gprsharp_inf_past_delegate>(library);
this.gprsharp_convert_clock_type = GetMethodDelegate<Delegates.gprsharp_convert_clock_type_delegate>(library);
this.gprsharp_sizeof_timespec = GetMethodDelegate<Delegates.gprsharp_sizeof_timespec_delegate>(library);
this.grpcsharp_test_callback = GetMethodDelegate<Delegates.grpcsharp_test_callback_delegate>(library);
this.grpcsharp_test_nop = GetMethodDelegate<Delegates.grpcsharp_test_nop_delegate>(library);
}
else
{
// Windows or fallback
this.grpcsharp_init = PInvokeMethods.grpcsharp_init;
this.grpcsharp_shutdown = PInvokeMethods.grpcsharp_shutdown;
this.grpcsharp_version_string = PInvokeMethods.grpcsharp_version_string;
this.grpcsharp_batch_context_create = PInvokeMethods.grpcsharp_batch_context_create;
this.grpcsharp_batch_context_recv_initial_metadata = PInvokeMethods.grpcsharp_batch_context_recv_initial_metadata;
this.grpcsharp_batch_context_recv_message_length = PInvokeMethods.grpcsharp_batch_context_recv_message_length;
this.grpcsharp_batch_context_recv_message_to_buffer = PInvokeMethods.grpcsharp_batch_context_recv_message_to_buffer;
this.grpcsharp_batch_context_recv_status_on_client_status = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_status;
this.grpcsharp_batch_context_recv_status_on_client_details = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_details;
this.grpcsharp_batch_context_recv_status_on_client_trailing_metadata = PInvokeMethods.grpcsharp_batch_context_recv_status_on_client_trailing_metadata;
this.grpcsharp_batch_context_server_rpc_new_call = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_call;
this.grpcsharp_batch_context_server_rpc_new_method = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_method;
this.grpcsharp_batch_context_server_rpc_new_host = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_host;
this.grpcsharp_batch_context_server_rpc_new_deadline = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_deadline;
this.grpcsharp_batch_context_server_rpc_new_request_metadata = PInvokeMethods.grpcsharp_batch_context_server_rpc_new_request_metadata;
this.grpcsharp_batch_context_recv_close_on_server_cancelled = PInvokeMethods.grpcsharp_batch_context_recv_close_on_server_cancelled;
this.grpcsharp_batch_context_destroy = PInvokeMethods.grpcsharp_batch_context_destroy;
this.grpcsharp_composite_call_credentials_create = PInvokeMethods.grpcsharp_composite_call_credentials_create;
this.grpcsharp_call_credentials_release = PInvokeMethods.grpcsharp_call_credentials_release;
this.grpcsharp_call_cancel = PInvokeMethods.grpcsharp_call_cancel;
this.grpcsharp_call_cancel_with_status = PInvokeMethods.grpcsharp_call_cancel_with_status;
this.grpcsharp_call_start_unary = PInvokeMethods.grpcsharp_call_start_unary;
this.grpcsharp_call_start_client_streaming = PInvokeMethods.grpcsharp_call_start_client_streaming;
this.grpcsharp_call_start_server_streaming = PInvokeMethods.grpcsharp_call_start_server_streaming;
this.grpcsharp_call_start_duplex_streaming = PInvokeMethods.grpcsharp_call_start_duplex_streaming;
this.grpcsharp_call_send_message = PInvokeMethods.grpcsharp_call_send_message;
this.grpcsharp_call_send_close_from_client = PInvokeMethods.grpcsharp_call_send_close_from_client;
this.grpcsharp_call_send_status_from_server = PInvokeMethods.grpcsharp_call_send_status_from_server;
this.grpcsharp_call_recv_message = PInvokeMethods.grpcsharp_call_recv_message;
this.grpcsharp_call_recv_initial_metadata = PInvokeMethods.grpcsharp_call_recv_initial_metadata;
this.grpcsharp_call_start_serverside = PInvokeMethods.grpcsharp_call_start_serverside;
this.grpcsharp_call_send_initial_metadata = PInvokeMethods.grpcsharp_call_send_initial_metadata;
this.grpcsharp_call_set_credentials = PInvokeMethods.grpcsharp_call_set_credentials;
this.grpcsharp_call_get_peer = PInvokeMethods.grpcsharp_call_get_peer;
this.grpcsharp_call_destroy = PInvokeMethods.grpcsharp_call_destroy;
this.grpcsharp_channel_args_create = PInvokeMethods.grpcsharp_channel_args_create;
this.grpcsharp_channel_args_set_string = PInvokeMethods.grpcsharp_channel_args_set_string;
this.grpcsharp_channel_args_set_integer = PInvokeMethods.grpcsharp_channel_args_set_integer;
this.grpcsharp_channel_args_destroy = PInvokeMethods.grpcsharp_channel_args_destroy;
this.grpcsharp_ssl_credentials_create = PInvokeMethods.grpcsharp_ssl_credentials_create;
this.grpcsharp_composite_channel_credentials_create = PInvokeMethods.grpcsharp_composite_channel_credentials_create;
this.grpcsharp_channel_credentials_release = PInvokeMethods.grpcsharp_channel_credentials_release;
this.grpcsharp_insecure_channel_create = PInvokeMethods.grpcsharp_insecure_channel_create;
this.grpcsharp_secure_channel_create = PInvokeMethods.grpcsharp_secure_channel_create;
this.grpcsharp_channel_create_call = PInvokeMethods.grpcsharp_channel_create_call;
this.grpcsharp_channel_check_connectivity_state = PInvokeMethods.grpcsharp_channel_check_connectivity_state;
this.grpcsharp_channel_watch_connectivity_state = PInvokeMethods.grpcsharp_channel_watch_connectivity_state;
this.grpcsharp_channel_get_target = PInvokeMethods.grpcsharp_channel_get_target;
this.grpcsharp_channel_destroy = PInvokeMethods.grpcsharp_channel_destroy;
this.grpcsharp_sizeof_grpc_event = PInvokeMethods.grpcsharp_sizeof_grpc_event;
this.grpcsharp_completion_queue_create = PInvokeMethods.grpcsharp_completion_queue_create;
this.grpcsharp_completion_queue_shutdown = PInvokeMethods.grpcsharp_completion_queue_shutdown;
this.grpcsharp_completion_queue_next = PInvokeMethods.grpcsharp_completion_queue_next;
this.grpcsharp_completion_queue_pluck = PInvokeMethods.grpcsharp_completion_queue_pluck;
this.grpcsharp_completion_queue_destroy = PInvokeMethods.grpcsharp_completion_queue_destroy;
this.gprsharp_free = PInvokeMethods.gprsharp_free;
this.grpcsharp_metadata_array_create = PInvokeMethods.grpcsharp_metadata_array_create;
this.grpcsharp_metadata_array_add = PInvokeMethods.grpcsharp_metadata_array_add;
this.grpcsharp_metadata_array_count = PInvokeMethods.grpcsharp_metadata_array_count;
this.grpcsharp_metadata_array_get_key = PInvokeMethods.grpcsharp_metadata_array_get_key;
this.grpcsharp_metadata_array_get_value = PInvokeMethods.grpcsharp_metadata_array_get_value;
this.grpcsharp_metadata_array_get_value_length = PInvokeMethods.grpcsharp_metadata_array_get_value_length;
this.grpcsharp_metadata_array_destroy_full = PInvokeMethods.grpcsharp_metadata_array_destroy_full;
this.grpcsharp_redirect_log = PInvokeMethods.grpcsharp_redirect_log;
this.grpcsharp_metadata_credentials_create_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_create_from_plugin;
this.grpcsharp_metadata_credentials_notify_from_plugin = PInvokeMethods.grpcsharp_metadata_credentials_notify_from_plugin;
this.grpcsharp_ssl_server_credentials_create = PInvokeMethods.grpcsharp_ssl_server_credentials_create;
this.grpcsharp_server_credentials_release = PInvokeMethods.grpcsharp_server_credentials_release;
this.grpcsharp_server_create = PInvokeMethods.grpcsharp_server_create;
this.grpcsharp_server_add_insecure_http2_port = PInvokeMethods.grpcsharp_server_add_insecure_http2_port;
this.grpcsharp_server_add_secure_http2_port = PInvokeMethods.grpcsharp_server_add_secure_http2_port;
this.grpcsharp_server_start = PInvokeMethods.grpcsharp_server_start;
this.grpcsharp_server_request_call = PInvokeMethods.grpcsharp_server_request_call;
this.grpcsharp_server_cancel_all_calls = PInvokeMethods.grpcsharp_server_cancel_all_calls;
this.grpcsharp_server_shutdown_and_notify_callback = PInvokeMethods.grpcsharp_server_shutdown_and_notify_callback;
this.grpcsharp_server_destroy = PInvokeMethods.grpcsharp_server_destroy;
this.gprsharp_now = PInvokeMethods.gprsharp_now;
this.gprsharp_inf_future = PInvokeMethods.gprsharp_inf_future;
this.gprsharp_inf_past = PInvokeMethods.gprsharp_inf_past;
this.gprsharp_convert_clock_type = PInvokeMethods.gprsharp_convert_clock_type;
this.gprsharp_sizeof_timespec = PInvokeMethods.gprsharp_sizeof_timespec;
this.grpcsharp_test_callback = PInvokeMethods.grpcsharp_test_callback;
this.grpcsharp_test_nop = PInvokeMethods.grpcsharp_test_nop;
}
}
/// <summary>
/// Gets singleton instance of this class.
/// </summary>
public static NativeMethods Get()
{
return NativeExtension.Get().NativeMethods;
}
static T GetMethodDelegate<T>(UnmanagedLibrary library)
where T : class
{
var methodName = RemoveStringSuffix(typeof(T).Name, "_delegate");
return library.GetNativeMethodDelegate<T>(methodName);
}
static string RemoveStringSuffix(string str, string toRemove)
{
if (!str.EndsWith(toRemove))
{
return str;
}
return str.Substring(0, str.Length - toRemove.Length);
}
/// <summary>
/// Delegate types for all published native methods. Declared under inner class to prevent scope pollution.
/// </summary>
public class Delegates
{
public delegate void grpcsharp_init_delegate();
public delegate void grpcsharp_shutdown_delegate();
public delegate IntPtr grpcsharp_version_string_delegate(); // returns not-owned const char*
public delegate BatchContextSafeHandle grpcsharp_batch_context_create_delegate();
public delegate IntPtr grpcsharp_batch_context_recv_initial_metadata_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_message_length_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_recv_message_to_buffer_delegate(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
public delegate StatusCode grpcsharp_batch_context_recv_status_on_client_status_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_details_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata_delegate(BatchContextSafeHandle ctx);
public delegate CallSafeHandle grpcsharp_batch_context_server_rpc_new_call_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_method_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_host_delegate(BatchContextSafeHandle ctx); // returns const char*
public delegate Timespec grpcsharp_batch_context_server_rpc_new_deadline_delegate(BatchContextSafeHandle ctx);
public delegate IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata_delegate(BatchContextSafeHandle ctx);
public delegate int grpcsharp_batch_context_recv_close_on_server_cancelled_delegate(BatchContextSafeHandle ctx);
public delegate void grpcsharp_batch_context_destroy_delegate(IntPtr ctx);
public delegate CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create_delegate(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
public delegate void grpcsharp_call_credentials_release_delegate(IntPtr credentials);
public delegate GRPCCallError grpcsharp_call_cancel_delegate(CallSafeHandle call);
public delegate GRPCCallError grpcsharp_call_cancel_with_status_delegate(CallSafeHandle call, StatusCode status, string description);
public delegate GRPCCallError grpcsharp_call_start_unary_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate GRPCCallError grpcsharp_call_start_client_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_start_server_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
public delegate GRPCCallError grpcsharp_call_start_duplex_streaming_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_send_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
public delegate GRPCCallError grpcsharp_call_send_close_from_client_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_send_status_from_server_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata);
public delegate GRPCCallError grpcsharp_call_recv_message_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_recv_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_start_serverside_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx);
public delegate GRPCCallError grpcsharp_call_send_initial_metadata_delegate(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
public delegate GRPCCallError grpcsharp_call_set_credentials_delegate(CallSafeHandle call, CallCredentialsSafeHandle credentials);
public delegate CStringSafeHandle grpcsharp_call_get_peer_delegate(CallSafeHandle call);
public delegate void grpcsharp_call_destroy_delegate(IntPtr call);
public delegate ChannelArgsSafeHandle grpcsharp_channel_args_create_delegate(UIntPtr numArgs);
public delegate void grpcsharp_channel_args_set_string_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
public delegate void grpcsharp_channel_args_set_integer_delegate(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
public delegate void grpcsharp_channel_args_destroy_delegate(IntPtr args);
public delegate ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create_delegate(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
public delegate ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create_delegate(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
public delegate void grpcsharp_channel_credentials_release_delegate(IntPtr credentials);
public delegate ChannelSafeHandle grpcsharp_insecure_channel_create_delegate(string target, ChannelArgsSafeHandle channelArgs);
public delegate ChannelSafeHandle grpcsharp_secure_channel_create_delegate(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
public delegate CallSafeHandle grpcsharp_channel_create_call_delegate(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
public delegate ChannelState grpcsharp_channel_check_connectivity_state_delegate(ChannelSafeHandle channel, int tryToConnect);
public delegate void grpcsharp_channel_watch_connectivity_state_delegate(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate CStringSafeHandle grpcsharp_channel_get_target_delegate(ChannelSafeHandle call);
public delegate void grpcsharp_channel_destroy_delegate(IntPtr channel);
public delegate int grpcsharp_sizeof_grpc_event_delegate();
public delegate CompletionQueueSafeHandle grpcsharp_completion_queue_create_delegate();
public delegate void grpcsharp_completion_queue_shutdown_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_next_delegate(CompletionQueueSafeHandle cq);
public delegate CompletionQueueEvent grpcsharp_completion_queue_pluck_delegate(CompletionQueueSafeHandle cq, IntPtr tag);
public delegate void grpcsharp_completion_queue_destroy_delegate(IntPtr cq);
public delegate void gprsharp_free_delegate(IntPtr ptr);
public delegate MetadataArraySafeHandle grpcsharp_metadata_array_create_delegate(UIntPtr capacity);
public delegate void grpcsharp_metadata_array_add_delegate(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
public delegate UIntPtr grpcsharp_metadata_array_count_delegate(IntPtr metadataArray);
public delegate IntPtr grpcsharp_metadata_array_get_key_delegate(IntPtr metadataArray, UIntPtr index);
public delegate IntPtr grpcsharp_metadata_array_get_value_delegate(IntPtr metadataArray, UIntPtr index);
public delegate UIntPtr grpcsharp_metadata_array_get_value_length_delegate(IntPtr metadataArray, UIntPtr index);
public delegate void grpcsharp_metadata_array_destroy_full_delegate(IntPtr array);
public delegate void grpcsharp_redirect_log_delegate(GprLogDelegate callback);
public delegate CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin_delegate(NativeMetadataInterceptor interceptor);
public delegate void grpcsharp_metadata_credentials_notify_from_plugin_delegate(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
public delegate ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create_delegate(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
public delegate void grpcsharp_server_credentials_release_delegate(IntPtr credentials);
public delegate ServerSafeHandle grpcsharp_server_create_delegate(CompletionQueueSafeHandle cq, ChannelArgsSafeHandle args);
public delegate int grpcsharp_server_add_insecure_http2_port_delegate(ServerSafeHandle server, string addr);
public delegate int grpcsharp_server_add_secure_http2_port_delegate(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
public delegate void grpcsharp_server_start_delegate(ServerSafeHandle server);
public delegate GRPCCallError grpcsharp_server_request_call_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_cancel_all_calls_delegate(ServerSafeHandle server);
public delegate void grpcsharp_server_shutdown_and_notify_callback_delegate(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
public delegate void grpcsharp_server_destroy_delegate(IntPtr server);
public delegate Timespec gprsharp_now_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_inf_future_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_inf_past_delegate(GPRClockType clockType);
public delegate Timespec gprsharp_convert_clock_type_delegate(Timespec t, GPRClockType targetClock);
public delegate int gprsharp_sizeof_timespec_delegate();
public delegate GRPCCallError grpcsharp_test_callback_delegate([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
public delegate IntPtr grpcsharp_test_nop_delegate(IntPtr ptr);
}
/// <summary>
/// Default PInvoke bindings for native methods that are used on Windows.
/// Alternatively, they can also be used as a fallback on Mono
/// (if libgrpc_csharp_ext is installed on your system, or is made accessible through e.g. LD_LIBRARY_PATH environment variable
/// or using Mono's dllMap feature).
/// </summary>
private class PInvokeMethods
{
// Environment
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_init();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_shutdown();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_version_string(); // returns not-owned const char*
// BatchContextSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern BatchContextSafeHandle grpcsharp_batch_context_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_initial_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_message_length(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_recv_message_to_buffer(BatchContextSafeHandle ctx, byte[] buffer, UIntPtr bufferLen);
[DllImport("grpc_csharp_ext.dll")]
public static extern StatusCode grpcsharp_batch_context_recv_status_on_client_status(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_details(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_recv_status_on_client_trailing_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_batch_context_server_rpc_new_call(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_method(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_host(BatchContextSafeHandle ctx); // returns const char*
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec grpcsharp_batch_context_server_rpc_new_deadline(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_batch_context_server_rpc_new_request_metadata(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_batch_context_recv_close_on_server_cancelled(BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_batch_context_destroy(IntPtr ctx);
// CallCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_composite_call_credentials_create(CallCredentialsSafeHandle creds1, CallCredentialsSafeHandle creds2);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_credentials_release(IntPtr credentials);
// CallSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_cancel(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_cancel_with_status(CallSafeHandle call, StatusCode status, string description);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_unary(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_client_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_server_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len,
MetadataArraySafeHandle metadataArray, WriteFlags writeFlags);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_duplex_streaming(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_message(CallSafeHandle call,
BatchContextSafeHandle ctx, byte[] send_buffer, UIntPtr send_buffer_len, WriteFlags writeFlags, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_close_from_client(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_status_from_server(CallSafeHandle call,
BatchContextSafeHandle ctx, StatusCode statusCode, string statusMessage, MetadataArraySafeHandle metadataArray, bool sendEmptyInitialMetadata);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_recv_message(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_recv_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_start_serverside(CallSafeHandle call,
BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_send_initial_metadata(CallSafeHandle call,
BatchContextSafeHandle ctx, MetadataArraySafeHandle metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_call_set_credentials(CallSafeHandle call, CallCredentialsSafeHandle credentials);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_call_get_peer(CallSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_call_destroy(IntPtr call);
// ChannelArgsSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelArgsSafeHandle grpcsharp_channel_args_create(UIntPtr numArgs);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_string(ChannelArgsSafeHandle args, UIntPtr index, string key, string value);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_channel_args_set_integer(ChannelArgsSafeHandle args, UIntPtr index, string key, int value);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_args_destroy(IntPtr args);
// ChannelCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ChannelCredentialsSafeHandle grpcsharp_ssl_credentials_create(string pemRootCerts, string keyCertPairCertChain, string keyCertPairPrivateKey);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelCredentialsSafeHandle grpcsharp_composite_channel_credentials_create(ChannelCredentialsSafeHandle channelCreds, CallCredentialsSafeHandle callCreds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_credentials_release(IntPtr credentials);
// ChannelSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_insecure_channel_create(string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelSafeHandle grpcsharp_secure_channel_create(ChannelCredentialsSafeHandle credentials, string target, ChannelArgsSafeHandle channelArgs);
[DllImport("grpc_csharp_ext.dll")]
public static extern CallSafeHandle grpcsharp_channel_create_call(ChannelSafeHandle channel, CallSafeHandle parentCall, ContextPropagationFlags propagationMask, CompletionQueueSafeHandle cq, string method, string host, Timespec deadline);
[DllImport("grpc_csharp_ext.dll")]
public static extern ChannelState grpcsharp_channel_check_connectivity_state(ChannelSafeHandle channel, int tryToConnect);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_watch_connectivity_state(ChannelSafeHandle channel, ChannelState lastObservedState,
Timespec deadline, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern CStringSafeHandle grpcsharp_channel_get_target(ChannelSafeHandle call);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_channel_destroy(IntPtr channel);
// CompletionQueueEvent
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_sizeof_grpc_event();
// CompletionQueueSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueSafeHandle grpcsharp_completion_queue_create();
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_shutdown(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_next(CompletionQueueSafeHandle cq);
[DllImport("grpc_csharp_ext.dll")]
public static extern CompletionQueueEvent grpcsharp_completion_queue_pluck(CompletionQueueSafeHandle cq, IntPtr tag);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_completion_queue_destroy(IntPtr cq);
// CStringSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern void gprsharp_free(IntPtr ptr);
// MetadataArraySafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern MetadataArraySafeHandle grpcsharp_metadata_array_create(UIntPtr capacity);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_array_add(MetadataArraySafeHandle array, string key, byte[] value, UIntPtr valueLength);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_count(IntPtr metadataArray);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_key(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_metadata_array_get_value(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern UIntPtr grpcsharp_metadata_array_get_value_length(IntPtr metadataArray, UIntPtr index);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_metadata_array_destroy_full(IntPtr array);
// NativeLogRedirector
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_redirect_log(GprLogDelegate callback);
// NativeMetadataCredentialsPlugin
[DllImport("grpc_csharp_ext.dll")]
public static extern CallCredentialsSafeHandle grpcsharp_metadata_credentials_create_from_plugin(NativeMetadataInterceptor interceptor);
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern void grpcsharp_metadata_credentials_notify_from_plugin(IntPtr callbackPtr, IntPtr userData, MetadataArraySafeHandle metadataArray, StatusCode statusCode, string errorDetails);
// ServerCredentialsSafeHandle
[DllImport("grpc_csharp_ext.dll", CharSet = CharSet.Ansi)]
public static extern ServerCredentialsSafeHandle grpcsharp_ssl_server_credentials_create(string pemRootCerts, string[] keyCertPairCertChainArray, string[] keyCertPairPrivateKeyArray, UIntPtr numKeyCertPairs, bool forceClientAuth);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_credentials_release(IntPtr credentials);
// ServerSafeHandle
[DllImport("grpc_csharp_ext.dll")]
public static extern ServerSafeHandle grpcsharp_server_create(CompletionQueueSafeHandle cq, ChannelArgsSafeHandle args);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_insecure_http2_port(ServerSafeHandle server, string addr);
[DllImport("grpc_csharp_ext.dll")]
public static extern int grpcsharp_server_add_secure_http2_port(ServerSafeHandle server, string addr, ServerCredentialsSafeHandle creds);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_start(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_server_request_call(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_cancel_all_calls(ServerSafeHandle server);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_shutdown_and_notify_callback(ServerSafeHandle server, CompletionQueueSafeHandle cq, BatchContextSafeHandle ctx);
[DllImport("grpc_csharp_ext.dll")]
public static extern void grpcsharp_server_destroy(IntPtr server);
// Timespec
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_now(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_future(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_inf_past(GPRClockType clockType);
[DllImport("grpc_csharp_ext.dll")]
public static extern Timespec gprsharp_convert_clock_type(Timespec t, GPRClockType targetClock);
[DllImport("grpc_csharp_ext.dll")]
public static extern int gprsharp_sizeof_timespec();
// Testing
[DllImport("grpc_csharp_ext.dll")]
public static extern GRPCCallError grpcsharp_test_callback([MarshalAs(UnmanagedType.FunctionPtr)] OpCompletionDelegate callback);
[DllImport("grpc_csharp_ext.dll")]
public static extern IntPtr grpcsharp_test_nop(IntPtr ptr);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;
namespace Windows.UI.Xaml.Media.Animation.Tests
{
[ConditionalClass(typeof(PlatformDetection), nameof(PlatformDetection.IsWinUISupported))]
public class RepeatBehaviorTests
{
[Fact]
public void Ctor_Default()
{
var repeatBehaviour = new RepeatBehavior();
Assert.True(repeatBehaviour.HasCount);
Assert.Equal(0, repeatBehaviour.Count);
Assert.False(repeatBehaviour.HasDuration);
Assert.Equal(TimeSpan.Zero, repeatBehaviour.Duration);
Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type);
}
[Theory]
[InlineData(0)]
[InlineData(10)]
[InlineData(double.MaxValue)]
public void Ctor_Count(double count)
{
var repeatBehaviour = new RepeatBehavior(count);
Assert.True(repeatBehaviour.HasCount);
Assert.Equal(count, repeatBehaviour.Count);
Assert.False(repeatBehaviour.HasDuration);
Assert.Equal(TimeSpan.Zero, repeatBehaviour.Duration);
Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type);
Assert.Equal(count.GetHashCode(), repeatBehaviour.GetHashCode());
}
[Theory]
[InlineData(-1)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NegativeInfinity)]
public void Ctor_InvalidCount_ThrowsArgumentOutOfRangeException(double count)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => new RepeatBehavior(count));
}
[Theory]
[InlineData(0)]
[InlineData(1)]
public void Ctor_TimeSpan(int seconds)
{
var repeatBehaviour = new RepeatBehavior(TimeSpan.FromSeconds(seconds));
Assert.False(repeatBehaviour.HasCount);
Assert.Equal(0, repeatBehaviour.Count);
Assert.True(repeatBehaviour.HasDuration);
Assert.Equal(TimeSpan.FromSeconds(seconds), repeatBehaviour.Duration);
Assert.Equal(RepeatBehaviorType.Duration, repeatBehaviour.Type);
Assert.Equal(TimeSpan.FromSeconds(seconds).GetHashCode(), repeatBehaviour.GetHashCode());
}
[Fact]
public void Ctor_NegativeTimeSpan_ThrowsArgumentOutOfRangeException()
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("duration", () => new RepeatBehavior(TimeSpan.FromTicks(-1)));
}
[Fact]
public void Forever_Get_ReturnsExpected()
{
RepeatBehavior forever = RepeatBehavior.Forever;
Assert.False(forever.HasCount);
Assert.Equal(0, forever.Count);
Assert.False(forever.HasDuration);
Assert.Equal(TimeSpan.Zero, forever.Duration);
Assert.Equal(RepeatBehaviorType.Forever, forever.Type);
Assert.Equal(int.MaxValue - 42, forever.GetHashCode());
}
[Theory]
[InlineData(-1)]
[InlineData(0)]
[InlineData(10)]
[InlineData(double.MaxValue)]
[InlineData(double.NaN)]
[InlineData(double.PositiveInfinity)]
[InlineData(double.NegativeInfinity)]
public void Count_Set_GetReturnsExpected(double value)
{
var repeatBehaviour = new RepeatBehavior(TimeSpan.MaxValue) { Count = value };
Assert.False(repeatBehaviour.HasCount);
Assert.Equal(value, repeatBehaviour.Count);
// Although we set a count, the type is unchanged.
Assert.Equal(RepeatBehaviorType.Duration, repeatBehaviour.Type);
}
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(-1)]
public void Duration_Set_GetReturnsExpected(int seconds)
{
var repeatBehaviour = new RepeatBehavior(1) { Duration = TimeSpan.FromSeconds(seconds) };
Assert.False(repeatBehaviour.HasDuration);
Assert.Equal(TimeSpan.FromSeconds(seconds), repeatBehaviour.Duration);
// Although we set a duration, the type is unchanged.
Assert.Equal(RepeatBehaviorType.Count, repeatBehaviour.Type);
}
[Theory]
[InlineData(RepeatBehaviorType.Count - 1)]
[InlineData(RepeatBehaviorType.Count)]
[InlineData(RepeatBehaviorType.Duration)]
[InlineData(RepeatBehaviorType.Forever)]
[InlineData(RepeatBehaviorType.Forever + 1)]
public void Type_Set_GetReturnsExpected(RepeatBehaviorType type)
{
var repeatBehaviour = new RepeatBehavior(1) { Type = type };
Assert.Equal(type == RepeatBehaviorType.Count, repeatBehaviour.HasCount);
Assert.Equal(type == RepeatBehaviorType.Duration, repeatBehaviour.HasDuration);
}
public static IEnumerable<object[]> Equals_TestData()
{
yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(2), true };
yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(1), false };
yield return new object[] { new RepeatBehavior(2), RepeatBehavior.Forever, false };
yield return new object[] { new RepeatBehavior(2), new RepeatBehavior(TimeSpan.FromSeconds(2)), false };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(TimeSpan.FromSeconds(2)), true };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(TimeSpan.FromSeconds(1)), false };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), RepeatBehavior.Forever, false };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new RepeatBehavior(2), false };
yield return new object[] { RepeatBehavior.Forever, RepeatBehavior.Forever, true };
yield return new object[] { RepeatBehavior.Forever, new RepeatBehavior(TimeSpan.FromSeconds(2)), false };
yield return new object[] { RepeatBehavior.Forever, new RepeatBehavior(2), false };
yield return new object[] { new RepeatBehavior { Type = RepeatBehaviorType.Count - 1 }, new RepeatBehavior { Type = RepeatBehaviorType.Count - 1 }, false };
yield return new object[] { new RepeatBehavior { Type = RepeatBehaviorType.Forever + 1 }, new RepeatBehavior { Type = RepeatBehaviorType.Count + 1 }, false };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), new object(), false };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), null, false };
}
[Theory]
[MemberData(nameof(Equals_TestData))]
public void Equals_Object_ReturnsExpected(RepeatBehavior repeatBehaviour, object other, bool expected)
{
Assert.Equal(expected, repeatBehaviour.Equals(other));
if (other is RepeatBehavior otherRepeatBehaviour)
{
Assert.Equal(expected, RepeatBehavior.Equals(repeatBehaviour, otherRepeatBehaviour));
Assert.Equal(expected, repeatBehaviour.Equals(otherRepeatBehaviour));
Assert.Equal(expected, repeatBehaviour == otherRepeatBehaviour);
Assert.Equal(!expected, repeatBehaviour != otherRepeatBehaviour);
if (repeatBehaviour.Type >= RepeatBehaviorType.Count && repeatBehaviour.Type <= RepeatBehaviorType.Forever)
{
Assert.Equal(expected, repeatBehaviour.GetHashCode().Equals(otherRepeatBehaviour.GetHashCode()));
}
else if (repeatBehaviour.Type == otherRepeatBehaviour.Type)
{
Assert.Equal(repeatBehaviour.GetHashCode(), otherRepeatBehaviour.GetHashCode());
}
}
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[] { RepeatBehavior.Forever, null, null, "Forever" };
yield return new object[] { RepeatBehavior.Forever, "InvalidFormat", CultureInfo.CurrentCulture, "Forever" };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), null, null, TimeSpan.FromSeconds(2).ToString() };
yield return new object[] { new RepeatBehavior(TimeSpan.FromSeconds(2)), "InvalidFormat", CultureInfo.CurrentCulture, TimeSpan.FromSeconds(2).ToString() };
var culture = new CultureInfo("en-US");
culture.NumberFormat.NumberDecimalSeparator = "|";
yield return new object[] { new RepeatBehavior(2.2), "abc", culture, "abcx" };
yield return new object[] { new RepeatBehavior(2.2), "N4", culture, "2|2000x" };
yield return new object[] { new RepeatBehavior(2.2), null, culture, "2|2x" };
yield return new object[] { new RepeatBehavior(2.2), null, null, $"{2.2.ToString()}x" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public void ToString_Invoke_ReturnsExpected(RepeatBehavior keyTime, string format, IFormatProvider formatProvider, string expected)
{
if (format == null)
{
if (formatProvider == null)
{
Assert.Equal(expected, keyTime.ToString());
}
Assert.Equal(expected, keyTime.ToString(formatProvider));
}
Assert.Equal(expected, ((IFormattable)keyTime).ToString(format, formatProvider));
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Security;
using System.Text;
using System.Threading;
using RuntimeTypeCache = System.RuntimeType.RuntimeTypeCache;
namespace System.Reflection
{
internal sealed class RuntimeMethodInfo : MethodInfo, IRuntimeMethodInfo
{
#region Private Data Members
private IntPtr m_handle;
private RuntimeTypeCache m_reflectedTypeCache;
private string? m_name;
private string? m_toString;
private ParameterInfo[]? m_parameters;
private ParameterInfo? m_returnParameter;
private BindingFlags m_bindingFlags;
private MethodAttributes m_methodAttributes;
private Signature? m_signature;
private RuntimeType m_declaringType;
private object? m_keepalive;
private INVOCATION_FLAGS m_invocationFlags;
internal INVOCATION_FLAGS InvocationFlags
{
get
{
if ((m_invocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED) == 0)
{
INVOCATION_FLAGS invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_UNKNOWN;
Type? declaringType = DeclaringType;
//
// first take care of all the NO_INVOKE cases.
if (ContainsGenericParameters ||
IsDisallowedByRefType(ReturnType) ||
(declaringType != null && declaringType.ContainsGenericParameters) ||
((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs))
{
// We don't need other flags if this method cannot be invoked
invocationFlags = INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE;
}
else
{
// Check for byref-like types
if ((declaringType != null && declaringType.IsByRefLike) || ReturnType.IsByRefLike)
invocationFlags |= INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS;
}
m_invocationFlags = invocationFlags | INVOCATION_FLAGS.INVOCATION_FLAGS_INITIALIZED;
}
return m_invocationFlags;
}
}
private static bool IsDisallowedByRefType(Type type)
{
if (!type.IsByRef)
return false;
Type elementType = type.GetElementType()!;
return elementType.IsByRefLike || elementType == typeof(void);
}
#endregion
#region Constructor
internal RuntimeMethodInfo(
RuntimeMethodHandleInternal handle, RuntimeType declaringType,
RuntimeTypeCache reflectedTypeCache, MethodAttributes methodAttributes, BindingFlags bindingFlags, object? keepalive)
{
Debug.Assert(!handle.IsNullHandle());
Debug.Assert(methodAttributes == RuntimeMethodHandle.GetAttributes(handle));
m_bindingFlags = bindingFlags;
m_declaringType = declaringType;
m_keepalive = keepalive;
m_handle = handle.Value;
m_reflectedTypeCache = reflectedTypeCache;
m_methodAttributes = methodAttributes;
}
#endregion
#region Private Methods
RuntimeMethodHandleInternal IRuntimeMethodInfo.Value => new RuntimeMethodHandleInternal(m_handle);
private RuntimeType ReflectedTypeInternal => m_reflectedTypeCache.GetRuntimeType();
private ParameterInfo[] FetchNonReturnParameters() =>
m_parameters ??= RuntimeParameterInfo.GetParameters(this, this, Signature);
private ParameterInfo FetchReturnParameter() =>
m_returnParameter ??= RuntimeParameterInfo.GetReturnParameter(this, this, Signature);
#endregion
#region Internal Members
internal override bool CacheEquals(object? o) =>
o is RuntimeMethodInfo m && m.m_handle == m_handle;
internal Signature Signature => m_signature ??= new Signature(this, m_declaringType);
internal BindingFlags BindingFlags => m_bindingFlags;
internal RuntimeMethodInfo? GetParentDefinition()
{
if (!IsVirtual || m_declaringType.IsInterface)
return null;
RuntimeType? parent = (RuntimeType?)m_declaringType.BaseType;
if (parent == null)
return null;
int slot = RuntimeMethodHandle.GetSlot(this);
if (RuntimeTypeHandle.GetNumVirtuals(parent) <= slot)
return null;
return (RuntimeMethodInfo?)RuntimeType.GetMethodBase(parent, RuntimeTypeHandle.GetMethodAt(parent, slot));
}
// Unlike DeclaringType, this will return a valid type even for global methods
internal RuntimeType GetDeclaringTypeInternal()
{
return m_declaringType;
}
internal sealed override int GenericParameterCount => RuntimeMethodHandle.GetGenericParameterCount(this);
#endregion
#region Object Overrides
public override string ToString()
{
if (m_toString == null)
{
var sbName = new ValueStringBuilder(MethodNameBufferSize);
sbName.Append(ReturnType.FormatTypeName());
sbName.Append(' ');
sbName.Append(Name);
if (IsGenericMethod)
sbName.Append(RuntimeMethodHandle.ConstructInstantiation(this, TypeNameFormatFlags.FormatBasic));
sbName.Append('(');
AppendParameters(ref sbName, GetParameterTypes(), CallingConvention);
sbName.Append(')');
m_toString = sbName.ToString();
}
return m_toString;
}
public override int GetHashCode()
{
// See RuntimeMethodInfo.Equals() below.
if (IsGenericMethod)
return ValueType.GetHashCodeOfPtr(m_handle);
else
return base.GetHashCode();
}
public override bool Equals(object? obj)
{
if (!IsGenericMethod)
return obj == (object)this;
// We cannot do simple object identity comparisons for generic methods.
// Equals will be called in CerHashTable when RuntimeType+RuntimeTypeCache.GetGenericMethodInfo()
// retrieve items from and insert items into s_methodInstantiations which is a CerHashtable.
RuntimeMethodInfo? mi = obj as RuntimeMethodInfo;
if (mi == null || !mi.IsGenericMethod)
return false;
// now we know that both operands are generic methods
IRuntimeMethodInfo handle1 = RuntimeMethodHandle.StripMethodInstantiation(this);
IRuntimeMethodInfo handle2 = RuntimeMethodHandle.StripMethodInstantiation(mi);
if (handle1.Value.Value != handle2.Value.Value)
return false;
Type[] lhs = GetGenericArguments();
Type[] rhs = mi.GetGenericArguments();
if (lhs.Length != rhs.Length)
return false;
for (int i = 0; i < lhs.Length; i++)
{
if (lhs[i] != rhs[i])
return false;
}
if (DeclaringType != mi.DeclaringType)
return false;
if (ReflectedType != mi.ReflectedType)
return false;
return true;
}
#endregion
#region ICustomAttributeProvider
public override object[] GetCustomAttributes(bool inherit)
{
return CustomAttribute.GetCustomAttributes(this, (typeof(object) as RuntimeType)!, inherit);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.GetCustomAttributes(this, attributeRuntimeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
if (attributeType == null)
throw new ArgumentNullException(nameof(attributeType));
RuntimeType? attributeRuntimeType = attributeType.UnderlyingSystemType as RuntimeType;
if (attributeRuntimeType == null)
throw new ArgumentException(SR.Arg_MustBeType, nameof(attributeType));
return CustomAttribute.IsDefined(this, attributeRuntimeType, inherit);
}
public override IList<CustomAttributeData> GetCustomAttributesData()
{
return CustomAttributeData.GetCustomAttributesInternal(this);
}
#endregion
#region MemberInfo Overrides
public override string Name => m_name ??= RuntimeMethodHandle.GetName(this);
public override Type? DeclaringType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_declaringType;
}
}
public sealed override bool HasSameMetadataDefinitionAs(MemberInfo other) => HasSameMetadataDefinitionAsCore<RuntimeMethodInfo>(other);
public override Type? ReflectedType
{
get
{
if (m_reflectedTypeCache.IsGlobal)
return null;
return m_reflectedTypeCache.GetRuntimeType();
}
}
public override MemberTypes MemberType => MemberTypes.Method;
public override int MetadataToken => RuntimeMethodHandle.GetMethodDef(this);
public override Module Module => GetRuntimeModule();
internal RuntimeType GetRuntimeType() { return m_declaringType; }
internal RuntimeModule GetRuntimeModule() { return m_declaringType.GetRuntimeModule(); }
internal RuntimeAssembly GetRuntimeAssembly() { return GetRuntimeModule().GetRuntimeAssembly(); }
public override bool IsSecurityCritical => true;
public override bool IsSecuritySafeCritical => false;
public override bool IsSecurityTransparent => false;
#endregion
#region MethodBase Overrides
internal override ParameterInfo[] GetParametersNoCopy() =>
FetchNonReturnParameters();
public override ParameterInfo[] GetParameters()
{
ParameterInfo[] parameters = FetchNonReturnParameters();
if (parameters.Length == 0)
return parameters;
ParameterInfo[] ret = new ParameterInfo[parameters.Length];
Array.Copy(parameters, ret, parameters.Length);
return ret;
}
public override MethodImplAttributes GetMethodImplementationFlags()
{
return RuntimeMethodHandle.GetImplAttributes(this);
}
public override RuntimeMethodHandle MethodHandle => new RuntimeMethodHandle(this);
public override MethodAttributes Attributes => m_methodAttributes;
public override CallingConventions CallingConvention => Signature.CallingConvention;
public override MethodBody? GetMethodBody()
{
RuntimeMethodBody? mb = RuntimeMethodHandle.GetMethodBody(this, ReflectedTypeInternal);
if (mb != null)
mb._methodBase = this;
return mb;
}
#endregion
#region Invocation Logic(On MemberBase)
private void CheckConsistency(object? target)
{
// only test instance methods
if ((m_methodAttributes & MethodAttributes.Static) != MethodAttributes.Static)
{
if (!m_declaringType.IsInstanceOfType(target))
{
if (target == null)
throw new TargetException(SR.RFLCT_Targ_StatMethReqTarg);
else
throw new TargetException(SR.RFLCT_Targ_ITargMismatch);
}
}
}
[DoesNotReturn]
private void ThrowNoInvokeException()
{
// method is on a class that contains stack pointers
if ((InvocationFlags & INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS) != 0)
{
throw new NotSupportedException();
}
// method is vararg
else if ((CallingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs)
{
throw new NotSupportedException();
}
// method is generic or on a generic class
else if (DeclaringType!.ContainsGenericParameters || ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Arg_UnboundGenParam);
}
// method is abstract class
else if (IsAbstract)
{
throw new MemberAccessException();
}
else if (ReturnType.IsByRef)
{
Type elementType = ReturnType.GetElementType()!;
if (elementType.IsByRefLike)
throw new NotSupportedException(SR.NotSupported_ByRefToByRefLikeReturn);
if (elementType == typeof(void))
throw new NotSupportedException(SR.NotSupported_ByRefToVoidReturn);
}
throw new TargetException();
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
public override object? Invoke(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
object[]? arguments = InvokeArgumentsCheck(obj, invokeAttr, binder, parameters, culture);
bool wrapExceptions = (invokeAttr & BindingFlags.DoNotWrapExceptions) == 0;
if (arguments == null || arguments.Length == 0)
return RuntimeMethodHandle.InvokeMethod(obj, null, Signature, false, wrapExceptions);
else
{
object retValue = RuntimeMethodHandle.InvokeMethod(obj, arguments, Signature, false, wrapExceptions);
// copy out. This should be made only if ByRef are present.
for (int index = 0; index < arguments.Length; index++)
parameters![index] = arguments[index];
return retValue;
}
}
[DebuggerStepThroughAttribute]
[Diagnostics.DebuggerHidden]
private object[]? InvokeArgumentsCheck(object? obj, BindingFlags invokeAttr, Binder? binder, object?[]? parameters, CultureInfo? culture)
{
Signature sig = Signature;
// get the signature
int formalCount = sig.Arguments.Length;
int actualCount = (parameters != null) ? parameters.Length : 0;
INVOCATION_FLAGS invocationFlags = InvocationFlags;
// INVOCATION_FLAGS_CONTAINS_STACK_POINTERS means that the struct (either the declaring type or the return type)
// contains pointers that point to the stack. This is either a ByRef or a TypedReference. These structs cannot
// be boxed and thus cannot be invoked through reflection which only deals with boxed value type objects.
if ((invocationFlags & (INVOCATION_FLAGS.INVOCATION_FLAGS_NO_INVOKE | INVOCATION_FLAGS.INVOCATION_FLAGS_CONTAINS_STACK_POINTERS)) != 0)
ThrowNoInvokeException();
// check basic method consistency. This call will throw if there are problems in the target/method relationship
CheckConsistency(obj);
if (formalCount != actualCount)
throw new TargetParameterCountException(SR.Arg_ParmCnt);
if (actualCount != 0)
return CheckArguments(parameters!, binder, invokeAttr, culture, sig);
else
return null;
}
#endregion
#region MethodInfo Overrides
public override Type ReturnType => Signature.ReturnType;
public override ICustomAttributeProvider ReturnTypeCustomAttributes => ReturnParameter;
public override ParameterInfo ReturnParameter => FetchReturnParameter();
public override bool IsCollectible => RuntimeMethodHandle.GetIsCollectible(new RuntimeMethodHandleInternal(m_handle)) != Interop.BOOL.FALSE;
public override MethodInfo GetBaseDefinition()
{
if (!IsVirtual || IsStatic || m_declaringType == null || m_declaringType.IsInterface)
return this;
int slot = RuntimeMethodHandle.GetSlot(this);
RuntimeType declaringType = (RuntimeType)DeclaringType!;
RuntimeType? baseDeclaringType = declaringType;
RuntimeMethodHandleInternal baseMethodHandle = new RuntimeMethodHandleInternal();
do
{
int cVtblSlots = RuntimeTypeHandle.GetNumVirtuals(declaringType);
if (cVtblSlots <= slot)
break;
baseMethodHandle = RuntimeTypeHandle.GetMethodAt(declaringType, slot);
baseDeclaringType = declaringType;
declaringType = (RuntimeType)declaringType.BaseType!;
} while (declaringType != null);
return (MethodInfo)RuntimeType.GetMethodBase(baseDeclaringType, baseMethodHandle)!;
}
public override Delegate CreateDelegate(Type delegateType)
{
// This API existed in v1/v1.1 and only expected to create closed
// instance delegates. Constrain the call to BindToMethodInfo to
// open delegates only for backwards compatibility. But we'll allow
// relaxed signature checking and open static delegates because
// there's no ambiguity there (the caller would have to explicitly
// pass us a static method or a method with a non-exact signature
// and the only change in behavior from v1.1 there is that we won't
// fail the call).
return CreateDelegateInternal(
delegateType,
null,
DelegateBindingFlags.OpenDelegateOnly | DelegateBindingFlags.RelaxedSignature);
}
public override Delegate CreateDelegate(Type delegateType, object? target)
{
// This API is new in Whidbey and allows the full range of delegate
// flexability (open or closed delegates binding to static or
// instance methods with relaxed signature checking). The delegate
// can also be closed over null. There's no ambiguity with all these
// options since the caller is providing us a specific MethodInfo.
return CreateDelegateInternal(
delegateType,
target,
DelegateBindingFlags.RelaxedSignature);
}
private Delegate CreateDelegateInternal(Type delegateType, object? firstArgument, DelegateBindingFlags bindingFlags)
{
// Validate the parameters.
if (delegateType == null)
throw new ArgumentNullException(nameof(delegateType));
RuntimeType? rtType = delegateType as RuntimeType;
if (rtType == null)
throw new ArgumentException(SR.Argument_MustBeRuntimeType, nameof(delegateType));
if (!rtType.IsDelegate())
throw new ArgumentException(SR.Arg_MustBeDelegate, nameof(delegateType));
Delegate? d = Delegate.CreateDelegateInternal(rtType, this, firstArgument, bindingFlags);
if (d == null)
{
throw new ArgumentException(SR.Arg_DlgtTargMeth);
}
return d;
}
#endregion
#region Generics
public override MethodInfo MakeGenericMethod(params Type[] methodInstantiation)
{
if (methodInstantiation == null)
throw new ArgumentNullException(nameof(methodInstantiation));
RuntimeType[] methodInstantionRuntimeType = new RuntimeType[methodInstantiation.Length];
if (!IsGenericMethodDefinition)
throw new InvalidOperationException(
SR.Format(SR.Arg_NotGenericMethodDefinition, this));
for (int i = 0; i < methodInstantiation.Length; i++)
{
Type methodInstantiationElem = methodInstantiation[i];
if (methodInstantiationElem == null)
throw new ArgumentNullException();
RuntimeType? rtMethodInstantiationElem = methodInstantiationElem as RuntimeType;
if (rtMethodInstantiationElem == null)
{
Type[] methodInstantiationCopy = new Type[methodInstantiation.Length];
for (int iCopy = 0; iCopy < methodInstantiation.Length; iCopy++)
methodInstantiationCopy[iCopy] = methodInstantiation[iCopy];
methodInstantiation = methodInstantiationCopy;
return System.Reflection.Emit.MethodBuilderInstantiation.MakeGenericMethod(this, methodInstantiation);
}
methodInstantionRuntimeType[i] = rtMethodInstantiationElem;
}
RuntimeType[] genericParameters = GetGenericArgumentsInternal();
RuntimeType.SanityCheckGenericArguments(methodInstantionRuntimeType, genericParameters);
MethodInfo? ret = null;
try
{
ret = RuntimeType.GetMethodBase(ReflectedTypeInternal,
RuntimeMethodHandle.GetStubIfNeeded(new RuntimeMethodHandleInternal(m_handle), m_declaringType, methodInstantionRuntimeType)) as MethodInfo;
}
catch (VerificationException e)
{
RuntimeType.ValidateGenericArguments(this, methodInstantionRuntimeType, e);
throw;
}
return ret!;
}
internal RuntimeType[] GetGenericArgumentsInternal() =>
RuntimeMethodHandle.GetMethodInstantiationInternal(this);
public override Type[] GetGenericArguments() =>
RuntimeMethodHandle.GetMethodInstantiationPublic(this) ?? Array.Empty<Type>();
public override MethodInfo GetGenericMethodDefinition()
{
if (!IsGenericMethod)
throw new InvalidOperationException();
return (RuntimeType.GetMethodBase(m_declaringType, RuntimeMethodHandle.StripMethodInstantiation(this)) as MethodInfo)!;
}
public override bool IsGenericMethod => RuntimeMethodHandle.HasMethodInstantiation(this);
public override bool IsGenericMethodDefinition => RuntimeMethodHandle.IsGenericMethodDefinition(this);
public override bool ContainsGenericParameters
{
get
{
if (DeclaringType != null && DeclaringType.ContainsGenericParameters)
return true;
if (!IsGenericMethod)
return false;
Type[] pis = GetGenericArguments();
for (int i = 0; i < pis.Length; i++)
{
if (pis[i].ContainsGenericParameters)
return true;
}
return false;
}
}
#endregion
#region Legacy Internal
internal static MethodBase? InternalGetCurrentMethod(ref StackCrawlMark stackMark)
{
IRuntimeMethodInfo? method = RuntimeMethodHandle.GetCurrentMethod(ref stackMark);
if (method == null)
return null;
return RuntimeType.GetMethodBase(method);
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Network
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// PacketCapturesOperations operations.
/// </summary>
internal partial class PacketCapturesOperations : IServiceOperations<NetworkManagementClient>, IPacketCapturesOperations
{
/// <summary>
/// Initializes a new instance of the PacketCapturesOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal PacketCapturesOperations(NetworkManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
Client = client;
}
/// <summary>
/// Gets a reference to the NetworkManagementClient
/// </summary>
public NetworkManagementClient Client { get; private set; }
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PacketCaptureResult>> CreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send Request
AzureOperationResponse<PacketCaptureResult> _response = await BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Gets a packet capture session by name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureResult>> GetWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse> StopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse _response = await BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> GetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Send request
AzureOperationResponse<PacketCaptureQueryStatusResult> _response = await BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, customHeaders, cancellationToken).ConfigureAwait(false);
return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// Lists all packet capture sessions within the specified resource group.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<IEnumerable<PacketCaptureResult>>> ListWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IEnumerable<PacketCaptureResult>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page1<PacketCaptureResult>>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Create and start a packet capture on the specified VM.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='parameters'>
/// Parameters that define the create packet capture operation.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureResult>> BeginCreateWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (parameters == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "parameters");
}
if (parameters != null)
{
parameters.Validate();
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("parameters", parameters);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginCreate", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(parameters != null)
{
_requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 201)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureResult>();
_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 == 201)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Deletes the specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("DELETE");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 204 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Stops a specified packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the network watcher.
/// </param>
/// <param name='packetCaptureName'>
/// The name of the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse> BeginStopWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginStop", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/stop").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Query the status of a running packet capture session.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='networkWatcherName'>
/// The name of the Network Watcher resource.
/// </param>
/// <param name='packetCaptureName'>
/// The name given to the packet capture session.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<AzureOperationResponse<PacketCaptureQueryStatusResult>> BeginGetStatusWithHttpMessagesAsync(string resourceGroupName, string networkWatcherName, string packetCaptureName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (networkWatcherName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "networkWatcherName");
}
if (packetCaptureName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "packetCaptureName");
}
if (Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2017-06-01";
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("networkWatcherName", networkWatcherName);
tracingParameters.Add("packetCaptureName", packetCaptureName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "BeginGetStatus", tracingParameters);
}
// Construct URL
var _baseUrl = Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/networkWatchers/{networkWatcherName}/packetCaptures/{packetCaptureName}/queryStatus").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{networkWatcherName}", System.Uri.EscapeDataString(networkWatcherName));
_url = _url.Replace("{packetCaptureName}", System.Uri.EscapeDataString(packetCaptureName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200 && (int)_statusCode != 202)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<PacketCaptureQueryStatusResult>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
// Deserialize Response
if ((int)_statusCode == 202)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<PacketCaptureQueryStatusResult>(_responseContent, Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
/*
Copyright (c) 2005-2006 Tomas Matousek.
The use and distribution terms for this software are contained in the file named License.txt,
which can be found in the root of the Phalanger distribution. By using this software
in any fashion, you are agreeing to be bound by the terms of this license.
You must not remove this notice from this software.
*/
using System;
using System.Globalization;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Win32;
using System.Xml;
using System.ComponentModel;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using PHP.Core;
using PHP.Core.Reflection;
using System.Diagnostics;
#if SILVERLIGHT
using PHP.CoreCLR;
#endif
namespace PHP.Library
{
#region DateTimeZone
/// <summary>
/// Representation of time zone.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
[ImplementsType]
public class DateTimeZone : PhpObject
{
internal TimeZoneInfo timezone;
#region Construction
public DateTimeZone(ScriptContext/*!*/context, TimeZoneInfo/*!*/resolvedTimeZone)
: this(context, true)
{
Debug.Assert(context != null);
Debug.Assert(resolvedTimeZone != null);
this.timezone = resolvedTimeZone;
}
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public DateTimeZone(ScriptContext context, bool newInstance)
: base(context, newInstance)
{ }
/// <summary>
/// For internal purposes only.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public DateTimeZone(ScriptContext context, DTypeDesc caller)
: base(context, caller)
{ }
#if !SILVERLIGHT
/// <summary>Deserializing constructor.</summary>
protected DateTimeZone(SerializationInfo info, StreamingContext context)
: base(info, context)
{ }
#endif
#endregion
#region Methods
// public __construct ( string $timezone )
[ImplementsMethod]
public object __construct(ScriptContext/*!*/context, object timezone_name)
{
if (timezone_name != null)
{
var zoneName = PHP.Core.Convert.ObjectToString(timezone_name);
this.timezone = PhpTimeZone.GetTimeZone(zoneName);
if (this.timezone == null)
PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", zoneName));
}
else
{
this.timezone = PhpTimeZone.CurrentTimeZone;
}
return null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object __construct(object instance, PhpStack stack)
{
var arg1 = stack.PeekValue(1);
stack.RemoveFrame();
return ((DateTimeZone)instance).__construct(stack.Context, arg1);
}
//public array getLocation ( void )
[ImplementsMethod]
public object getLocation(ScriptContext/*!*/context)
{
throw new NotImplementedException();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getLocation(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((DateTimeZone)instance).getLocation(stack.Context);
}
//public string getName ( void )
[ImplementsMethod]
public object getName(ScriptContext/*!*/context)
{
return (timezone != null) ? timezone.Id : null;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getName(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((DateTimeZone)instance).getName(stack.Context);
}
//public int getOffset ( DateTime $datetime )
[ImplementsMethod]
public object getOffset(ScriptContext/*!*/context, object datetime)
{
if (this.timezone == null)
return false;
if (datetime == null)
{
PhpException.ArgumentNull("datetime");
return false;
}
var dt = datetime as __PHP__DateTime;
if (dt == null)
{
PhpException.InvalidArgumentType("datetime", "DateTime");
return false;
}
return (int)this.timezone.BaseUtcOffset.TotalSeconds + (this.timezone.IsDaylightSavingTime(dt.Time) ? 3600 : 0);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getOffset(object instance, PhpStack stack)
{
var arg1 = stack.PeekValue(1);
stack.RemoveFrame();
return ((DateTimeZone)instance).getOffset(stack.Context, arg1);
}
//public array getTransitions ([ int $timestamp_begin [, int $timestamp_end ]] )
[ImplementsMethod]
public object getTransitions(ScriptContext/*!*/context, [Optional]object timestamp_begin, [Optional]object timestamp_end)
{
// TODO: timestamp_begin, timestamp_end
var rules = this.timezone.GetAdjustmentRules();
var array = new PhpArray(rules.Length);
//var now = DateTime.UtcNow;
for (int i = 0; i < rules.Length; i++)
{
var rule = rules[i];
// TODO: timezone transitions
//if (rule.DateStart > now || rule.DateEnd < now) continue;
//var transition = new PhpArray(5);
//transition["ts"] = (int)(new DateTime(now.Year, rule.DaylightTransitionStart.Month, rule.DaylightTransitionStart.Day) - DateTimeUtils.UtcStartOfUnixEpoch).TotalSeconds;
////transition["time"] = ;
////transition["offset"] = ;
//transition["isdst"] = 1;
////transition["abbr"] = ;
//array.Add(transition);
}
return array;
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object getTransitions(object instance, PhpStack stack)
{
var arg1 = stack.PeekValueOptional(1);
var arg2 = stack.PeekValueOptional(2);
stack.RemoveFrame();
return ((DateTimeZone)instance).getTransitions(stack.Context, arg1, arg2);
}
//public static array listAbbreviations ( void )
[ImplementsMethod]
public object listAbbreviations(ScriptContext/*!*/context)
{
throw new NotImplementedException();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object listAbbreviations(object instance, PhpStack stack)
{
stack.RemoveFrame();
return ((DateTimeZone)instance).listAbbreviations(stack.Context);
}
//public static array listIdentifiers ([ int $what = DateTimeZone::ALL [, string $country = NULL ]] )
[ImplementsMethod]
public static object listIdentifiers(ScriptContext/*!*/context, [Optional]object what, [Optional]object country)
{
throw new NotImplementedException();
}
[EditorBrowsable(EditorBrowsableState.Never)]
public static object listIdentifiers(object instance, PhpStack stack)
{
var arg1 = stack.PeekValueOptional(1);
var arg2 = stack.PeekValueOptional(2);
stack.RemoveFrame();
return listIdentifiers(stack.Context, arg1, arg2);
}
#endregion
}
#endregion
/// <summary>
/// Provides timezone information for PHP functions.
/// </summary>
[ImplementsExtension(LibraryDescriptor.ExtDate)]
public static class PhpTimeZone
{
private const string EnvVariableName = "TZ";
private struct TimeZoneInfoItem
{
/// <summary>
/// Comparer of <see cref="TimeZoneInfoItem"/>, comparing its <see cref="TimeZoneInfoItem.PhpName"/>.
/// </summary>
public class Comparer : IComparer<TimeZoneInfoItem>
{
public int Compare(TimeZoneInfoItem x, TimeZoneInfoItem y)
{
return StringComparer.OrdinalIgnoreCase.Compare(x.PhpName, y.PhpName);
}
}
/// <summary>
/// PHP time zone name.
/// </summary>
public readonly string PhpName;
/// <summary>
/// Actual <see cref="TimeZoneInfo"/> from .NET.
/// </summary>
public readonly TimeZoneInfo Info;
/// <summary>
/// An abbrevation, not supported.
/// </summary>
public readonly string Abbrevation;
/// <summary>
/// Not listed item used only as an alias for another time zone.
/// </summary>
public readonly bool IsAlias;
internal TimeZoneInfoItem(string/*!*/phpName, TimeZoneInfo/*!*/info, string abbrevation, bool isAlias)
{
// alter the ID with php-like name
if (!phpName.EqualsOrdinalIgnoreCase(info.Id))
info = TimeZoneInfo.CreateCustomTimeZone(phpName, info.BaseUtcOffset, info.DisplayName, info.StandardName, info.DaylightName, info.GetAdjustmentRules());
//
this.PhpName = phpName;
this.Info = info;
this.Abbrevation = abbrevation;
this.IsAlias = isAlias;
}
}
/// <summary>
/// Initializes list of time zones.
/// </summary>
static PhpTimeZone()
{
// initialize tz database (from system time zone database)
timezones = InitializeTimeZones();
}
#region timezones
/// <summary>
/// PHP time zone database.
/// </summary>
private readonly static TimeZoneInfoItem[]/*!!*/timezones;
private static TimeZoneInfoItem[]/*!!*/InitializeTimeZones()
{
// read list of initial timezones
var sortedTZ = new SortedSet<TimeZoneInfoItem>(
EnvironmentUtils.IsWindows ? InitialTimeZones_Windows() : InitialTimeZones_Mono(),
new TimeZoneInfoItem.Comparer());
// add additional time zones:
sortedTZ.Add(new TimeZoneInfoItem("UTC", TimeZoneInfo.Utc, null, false));
sortedTZ.Add(new TimeZoneInfoItem("Etc/UTC", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("Etc/GMT-0", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("GMT", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("GMT0", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("UCT", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("Universal", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("Zulu", TimeZoneInfo.Utc, null, true));
sortedTZ.Add(new TimeZoneInfoItem("MET", sortedTZ.First(t => t.PhpName == "Europe/Rome").Info, null, true));
sortedTZ.Add(new TimeZoneInfoItem("WET", sortedTZ.First(t => t.PhpName == "Europe/Berlin").Info, null, true));
//{ "PRC"
//{ "ROC"
//{ "ROK"
// W-SU =
//{ "Poland"
//{ "Portugal"
//{ "PRC"
//{ "ROC"
//{ "ROK"
//{ "Singapore" = Asia/Singapore
//{ "Turkey"
//
return sortedTZ.ToArray();
}
private static IEnumerable<TimeZoneInfoItem>/*!!*/InitialTimeZones_Windows()
{
Debug.Assert(EnvironmentUtils.IsWindows);
// time zone cache:
var tzcache = new Dictionary<string, TimeZoneInfo>(128, StringComparer.OrdinalIgnoreCase);
Func<string, TimeZoneInfo> cachelookup = (id) =>
{
TimeZoneInfo tz;
if (!tzcache.TryGetValue(id, out tz))
{
TimeZoneInfo winTZ = null;
try
{
winTZ = TimeZoneInfo.FindSystemTimeZoneById(id);
}
catch { }
tzcache[id] = tz = winTZ; // null in case "id" is not defined in Windows registry (probably missing Windows Update)
}
return tz;
};
// collect php time zone names and match them with Windows TZ IDs:
var tzdoc = new XmlDocument();
tzdoc.LoadXml(Strings.WindowsTZ);
foreach (XmlNode tz in tzdoc.DocumentElement.SelectNodes(@"//windowsZones/mapTimezones/mapZone"))
{
// <mapZone other="Dateline Standard Time" type="Etc/GMT+12"/>
// @other = Windows TZ ID
// @type = PHP TZ names, separated by space
var windowsId = tz.Attributes["other"].Value;
var phpIds = tz.Attributes["type"].Value;
var windowsTZ = cachelookup(windowsId);
if (windowsTZ != null) // TZ not defined in Windows registry, ignore such time zone // TODO: show a warning
foreach (var phpTzName in phpIds.Split(' '))
{
Debug.Assert(!string.IsNullOrWhiteSpace(phpTzName));
bool isAlias = !phpTzName.Contains('/') || phpTzName.Contains("GMT"); // whether to display such tz within timezone_identifiers_list()
yield return new TimeZoneInfoItem(phpTzName, windowsTZ, null, isAlias);
}
}
//
//{ "US/Alaska"
//{ "US/Aleutian"
//{ "US/Arizona"
yield return new TimeZoneInfoItem("US/Central", cachelookup("Central Standard Time"), null, true);
//{ "US/East-Indiana"
//{ "US/Eastern"
yield return new TimeZoneInfoItem("US/Hawaii", cachelookup("Hawaiian Standard Time"), null, true);
//{ "US/Indiana-Starke"
//{ "US/Michigan"
//{ "US/Mountain"
//{ "US/Pacific"
//{ "US/Pacific-New"
//{ "US/Samoa"
}
private static IEnumerable<TimeZoneInfoItem>/*!!*/InitialTimeZones_Mono()
{
Debug.Assert(!EnvironmentUtils.IsDotNetFramework);
var tzns = TimeZoneInfo.GetSystemTimeZones();
if (tzns == null)
yield break;
foreach (var x in tzns)
{
bool isAlias = !x.Id.Contains('/') || x.Id.Contains("GMT"); // whether to display such tz within timezone_identifiers_list()
yield return new TimeZoneInfoItem(x.Id, x, null, isAlias);
}
}
#endregion
/// <summary>
/// Gets the current time zone for PHP date-time library functions. Associated with the current thread.
/// </summary>
/// <remarks>It returns the time zone set by date_default_timezone_set PHP function.
/// If no time zone was set, the time zone is determined in following order:
/// 1. the time zone set in configuration
/// 2. the time zone of the current system
/// 3. default UTC time zone</remarks>
public static TimeZoneInfo CurrentTimeZone
{
get
{
TimeZoneInfo info;
var ctx = ScriptContext.CurrentContext;
// timezone is set by date_default_timezone_set(), return this one
if (ctx.Properties.TryGetProperty<TimeZoneInfo>(out info) == false || info == null)
{
// default timezone was not set, use & cache the current timezone
info = ctx.Properties
.GetOrCreateProperty(() => new CurrentTimeZoneCache())
.TimeZone;
}
//
return info;
}
#if DEBUG // for unit tests only
internal set
{
ScriptContext.CurrentContext.Properties.SetProperty(value);
}
#endif
}
#region CurrentTimeZoneCache
/// <summary>
/// Cache of current TimeZone with auto-update ability.
/// </summary>
private class CurrentTimeZoneCache
{
public CurrentTimeZoneCache()
{
}
#if DEBUG
internal CurrentTimeZoneCache(TimeZoneInfo timezone)
{
this._timeZone = timezone;
this._changedFunc = (_) => false;
}
#endif
/// <summary>
/// Get the TimeZone set by the current process. Depends on environment variable, or local configuration, or system time zone.
/// </summary>
public TimeZoneInfo TimeZone
{
get
{
if (_timeZone == null || _changedFunc == null || _changedFunc(_timeZone) == true)
_timeZone = DetermineTimeZone(out _changedFunc); // get the current timezone, update the function that determines, if the timezone has to be rechecked.
return _timeZone;
}
}
private TimeZoneInfo _timeZone;
/// <summary>
/// Function that determines if the current timezone should be rechecked.
/// </summary>
private Func<TimeZoneInfo/*!*/, bool> _changedFunc;
/// <summary>
/// Finds out the time zone in the way how PHP does.
/// </summary>
private static TimeZoneInfo DetermineTimeZone(out Func<TimeZoneInfo, bool> changedFunc)
{
TimeZoneInfo result;
// check environment variable:
#if !SILVERLIGHT
string env_tz = Environment.GetEnvironmentVariable(EnvVariableName);
if (!String.IsNullOrEmpty(env_tz))
{
result = GetTimeZone(env_tz);
if (result != null)
{
// recheck the timezone only if the environment variable changes
changedFunc = (timezone) => !String.Equals(timezone.StandardName, Environment.GetEnvironmentVariable(EnvVariableName), StringComparison.OrdinalIgnoreCase);
// return the timezone set in environment
return result;
}
PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone_env", env_tz));
}
#endif
// check configuration:
LibraryConfiguration config = LibraryConfiguration.Local;
if (config.Date.TimeZone != null)
{
// recheck the timezone only if the local configuration changes, ignore the environment variable from this point at all
changedFunc = (timezone) => LibraryConfiguration.Local.Date.TimeZone != timezone;
return config.Date.TimeZone;
}
// convert current system time zone to PHP zone:
result = SystemToPhpTimeZone(TimeZoneInfo.Local);
// UTC:
if (result == null)
result = DateTimeUtils.UtcTimeZone;// GetTimeZone("UTC");
PhpException.Throw(PhpError.Strict, LibResources.GetString("using_implicit_timezone", result.Id));
// recheck the timezone when the TimeZone in local configuration is set
changedFunc = (timezone) => LibraryConfiguration.Local.Date.TimeZone != null;
return result;
}
}
#endregion
#if !SILVERLIGHT
/// <summary>
/// Gets/sets/resets legacy configuration setting "date.timezone".
/// </summary>
internal static object GsrTimeZone(LibraryConfiguration/*!*/ local, LibraryConfiguration/*!*/ @default, object value, IniAction action)
{
string result = (local.Date.TimeZone != null) ? local.Date.TimeZone.StandardName : null;
switch (action)
{
case IniAction.Set:
{
string name = Core.Convert.ObjectToString(value);
TimeZoneInfo zone = GetTimeZone(name);
if (zone == null)
{
PhpException.Throw(PhpError.Warning, LibResources.GetString("unknown_timezone", name));
}
else
{
local.Date.TimeZone = zone;
}
break;
}
case IniAction.Restore:
local.Date.TimeZone = @default.Date.TimeZone;
break;
}
return result;
}
#endif
/// <summary>
/// Gets an instance of <see cref="TimeZone"/> corresponding to specified PHP name for time zone.
/// </summary>
/// <param name="phpName">PHP time zone name.</param>
/// <returns>The time zone or a <B>null</B> reference.</returns>
public static TimeZoneInfo GetTimeZone(string/*!*/ phpName)
{
if (string.IsNullOrEmpty(phpName))
return null;
// simple binary search (not the Array.BinarySearch)
var timezones = PhpTimeZone.timezones;
int a = 0, b = timezones.Length - 1;
while (a <= b)
{
int x = (a + b) >> 1;
int comparison = StringComparer.OrdinalIgnoreCase.Compare(timezones[x].PhpName, phpName);
if (comparison == 0)
return timezones[x].Info;
if (comparison < 0)
a = x + 1;
else //if (comparison > 0)
b = x - 1;
}
return null;
}
/// <summary>
/// Tries to match given <paramref name="systemTimeZone"/> to our fixed <see cref="timezones"/>.
/// </summary>
private static TimeZoneInfo SystemToPhpTimeZone(TimeZoneInfo systemTimeZone)
{
if (systemTimeZone == null)
return null;
var tzns = timezones;
for (int i = 0; i < tzns.Length; i++)
{
var tz = tzns[i].Info;
if (tz != null && tz.DisplayName.EqualsOrdinalIgnoreCase(systemTimeZone.DisplayName) && tz.HasSameRules(systemTimeZone))
return tz;
}
return null;
}
#region date_default_timezone_get, date_default_timezone_set
[ImplementsFunction("date_default_timezone_set")]
public static bool SetCurrentTimeZone(string zoneName)
{
var zone = GetTimeZone(zoneName);
if (zone == null)
{
PhpException.Throw(PhpError.Notice, LibResources.GetString("unknown_timezone", zoneName));
return false;
}
ScriptContext.CurrentContext.Properties.SetProperty<TimeZoneInfo>(zone);
return true;
}
[ImplementsFunction("date_default_timezone_get")]
public static string GetCurrentTimeZone()
{
var timezone = CurrentTimeZone;
return (timezone != null) ? timezone.Id : null;
}
#endregion
#region timezone_identifiers_list, timezone_version_get
[ImplementsFunction("timezone_identifiers_list")]
public static PhpArray IdentifierList()
{
var timezones = PhpTimeZone.timezones;
// copy names to PHP array:
var array = new PhpArray(timezones.Length);
for (int i = 0; i < timezones.Length; i++)
if (!timezones[i].IsAlias)
array.AddToEnd(timezones[i].PhpName);
//
return array;
}
/// <summary>
/// Gets the version of used the time zone database.
/// </summary>
[ImplementsFunction("timezone_version_get")]
public static string GetTZVersion()
{
try
{
using (var reg = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"))
return reg.GetValue("TzVersion", 0).ToString() + ".system";
}
catch { }
// no windows update installed
return "0.system";
}
#endregion
#region timezone_open, timezone_offset_get
/// <summary>
/// Alias of new <see cref="DateTimeZone"/>
/// </summary>
[ImplementsFunction("timezone_open")]
[return: CastToFalse]
public static object TimeZoneOpen(ScriptContext/*!*/context, string timezone)
{
var tz = GetTimeZone(timezone);
if (tz == null)
return null;
return new DateTimeZone(context, tz);
}
/// <summary>
/// Alias of <see cref="DateTimeZone.getOffset"/>
/// </summary>
[ImplementsFunction("timezone_offset_get")]
[return: CastToFalse]
public static int TimeZoneOffsetGet(ScriptContext context, DateTimeZone timezone, __PHP__DateTime datetime)
{
if (timezone == null)
return -1;
var result = timezone.getOffset(context, datetime);
if (result == null)
return -1;
return PHP.Core.Convert.ObjectToInteger(timezone.getOffset(context, datetime));
}
[ImplementsFunction("timezone_transitions_get")]
[return: CastToFalse]
public static PhpArray TimeZoneGetTransitions(ScriptContext context, DateTimeZone timezone)
{
if (timezone == null)
return null;
return (PhpArray)timezone.getTransitions(context, Arg.Default, Arg.Default);
}
#endregion
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure;
using Microsoft.Azure.Management.Automation;
using Microsoft.Azure.Management.Automation.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Automation
{
/// <summary>
/// Service operation for automation dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
internal partial class DscNodeConfigurationOperations : IServiceOperations<AutomationManagementClient>, IDscNodeConfigurationOperations
{
/// <summary>
/// Initializes a new instance of the DscNodeConfigurationOperations
/// class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal DscNodeConfigurationOperations(AutomationManagementClient client)
{
this._client = client;
}
private AutomationManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Automation.AutomationManagementClient.
/// </summary>
public AutomationManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Create the node configuration identified by node configuration
/// name. (see http://aka.ms/azureautomationsdk/dscnodeconfigurations
/// for more information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Required. The create or update parameters for configuration.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get Dsc node configuration operation.
/// </returns>
public async Task<DscNodeConfigurationGetResponse> CreateOrUpdateAsync(string resourceGroupName, string automationAccount, DscNodeConfigurationCreateOrUpdateParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (parameters == null)
{
throw new ArgumentNullException("parameters");
}
if (parameters.Configuration == null)
{
throw new ArgumentNullException("parameters.Configuration");
}
if (parameters.Name == null)
{
throw new ArgumentNullException("parameters.Name");
}
if (parameters.Source == null)
{
throw new ArgumentNullException("parameters.Source");
}
if (parameters.Source.ContentHash != null)
{
if (parameters.Source.ContentHash.Algorithm == null)
{
throw new ArgumentNullException("parameters.Source.ContentHash.Algorithm");
}
if (parameters.Source.ContentHash.Value == null)
{
throw new ArgumentNullException("parameters.Source.ContentHash.Value");
}
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "CreateOrUpdateAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodeConfigurations/";
url = url + Uri.EscapeDataString(parameters.Name);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-31");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Serialize Request
string requestContent = null;
JToken requestDoc = null;
JObject dscNodeConfigurationCreateOrUpdateParametersValue = new JObject();
requestDoc = dscNodeConfigurationCreateOrUpdateParametersValue;
JObject sourceValue = new JObject();
dscNodeConfigurationCreateOrUpdateParametersValue["source"] = sourceValue;
if (parameters.Source.ContentHash != null)
{
JObject hashValue = new JObject();
sourceValue["hash"] = hashValue;
hashValue["algorithm"] = parameters.Source.ContentHash.Algorithm;
hashValue["value"] = parameters.Source.ContentHash.Value;
}
if (parameters.Source.ContentType != null)
{
sourceValue["type"] = parameters.Source.ContentType;
}
if (parameters.Source.Value != null)
{
sourceValue["value"] = parameters.Source.Value;
}
if (parameters.Source.Version != null)
{
sourceValue["version"] = parameters.Source.Version;
}
dscNodeConfigurationCreateOrUpdateParametersValue["name"] = parameters.Name;
JObject configurationValue = new JObject();
dscNodeConfigurationCreateOrUpdateParametersValue["configuration"] = configurationValue;
if (parameters.Configuration.Name != null)
{
configurationValue["name"] = parameters.Configuration.Name;
}
dscNodeConfigurationCreateOrUpdateParametersValue["incrementNodeConfigurationBuild"] = parameters.IncrementNodeConfigurationBuild;
requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented);
httpRequest.Content = new StringContent(requestContent, Encoding.UTF8);
httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeConfigurationGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeConfigurationGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNodeConfiguration nodeConfigurationInstance = new DscNodeConfiguration();
result.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
nodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
nodeConfigurationInstance.CreationTime = creationTimeInstance;
}
JToken configurationValue2 = responseDoc["configuration"];
if (configurationValue2 != null && configurationValue2.Type != JTokenType.Null)
{
DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty();
nodeConfigurationInstance.Configuration = configurationInstance;
JToken nameValue2 = configurationValue2["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
configurationInstance.Name = nameInstance2;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeConfigurationInstance.Id = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Delete the Dsc node configurations by node configuration. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeConfigurationName'>
/// Required. The Dsc node configuration name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string automationAccount, string nodeConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (nodeConfigurationName == null)
{
throw new ArgumentNullException("nodeConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeConfigurationName", nodeConfigurationName);
TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodeConfigurations/";
url = url + Uri.EscapeDataString(nodeConfigurationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-31");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Delete;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
AzureOperationResponse result = null;
// Deserialize Response
result = new AzureOperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve the Dsc node configurations by node configuration. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='nodeConfigurationName'>
/// Required. The Dsc node configuration name.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the get Dsc node configuration operation.
/// </returns>
public async Task<DscNodeConfigurationGetResponse> GetAsync(string resourceGroupName, string automationAccount, string nodeConfigurationName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
if (nodeConfigurationName == null)
{
throw new ArgumentNullException("nodeConfigurationName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("nodeConfigurationName", nodeConfigurationName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodeConfigurations/";
url = url + Uri.EscapeDataString(nodeConfigurationName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-10-31");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeConfigurationGetResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeConfigurationGetResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
DscNodeConfiguration nodeConfigurationInstance = new DscNodeConfiguration();
result.NodeConfiguration = nodeConfigurationInstance;
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
nodeConfigurationInstance.Name = nameInstance;
}
JToken lastModifiedTimeValue = responseDoc["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
nodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken creationTimeValue = responseDoc["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
nodeConfigurationInstance.CreationTime = creationTimeInstance;
}
JToken configurationValue = responseDoc["configuration"];
if (configurationValue != null && configurationValue.Type != JTokenType.Null)
{
DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty();
nodeConfigurationInstance.Configuration = configurationInstance;
JToken nameValue2 = configurationValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
configurationInstance.Name = nameInstance2;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
nodeConfigurationInstance.Id = idInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve a list of dsc node configurations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group
/// </param>
/// <param name='automationAccount'>
/// Required. The automation account name.
/// </param>
/// <param name='parameters'>
/// Optional. The parameters supplied to the list operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list job operation.
/// </returns>
public async Task<DscNodeConfigurationListResponse> ListAsync(string resourceGroupName, string automationAccount, DscNodeConfigurationListParameters parameters, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (automationAccount == null)
{
throw new ArgumentNullException("automationAccount");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("automationAccount", automationAccount);
tracingParameters.Add("parameters", parameters);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
if (this.Client.ResourceNamespace != null)
{
url = url + Uri.EscapeDataString(this.Client.ResourceNamespace);
}
url = url + "/automationAccounts/";
url = url + Uri.EscapeDataString(automationAccount);
url = url + "/nodeConfigurations";
List<string> queryParameters = new List<string>();
List<string> odataFilter = new List<string>();
if (parameters != null && parameters.ConfigurationName != null)
{
odataFilter.Add("configuration/name eq '" + Uri.EscapeDataString(parameters.ConfigurationName) + "'");
}
if (odataFilter.Count > 0)
{
queryParameters.Add("$filter=" + string.Join(null, odataFilter));
}
queryParameters.Add("api-version=2015-10-31");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeConfigurationListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeConfigurationListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration();
result.DscNodeConfigurations.Add(dscNodeConfigurationInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dscNodeConfigurationInstance.Name = nameInstance;
}
JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken creationTimeValue = valueValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
dscNodeConfigurationInstance.CreationTime = creationTimeInstance;
}
JToken configurationValue = valueValue["configuration"];
if (configurationValue != null && configurationValue.Type != JTokenType.Null)
{
DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty();
dscNodeConfigurationInstance.Configuration = configurationInstance;
JToken nameValue2 = configurationValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
configurationInstance.Name = nameInstance2;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeConfigurationInstance.Id = idInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Retrieve next list of dsc node configrations. (see
/// http://aka.ms/azureautomationsdk/dscnodeconfigurations for more
/// information)
/// </summary>
/// <param name='nextLink'>
/// Required. The link to retrieve next set of items.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the list job operation.
/// </returns>
public async Task<DscNodeConfigurationListResponse> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("Accept", "application/json");
httpRequest.Headers.Add("ocp-referer", url);
httpRequest.Headers.Add("x-ms-version", "2014-06-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
DscNodeConfigurationListResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new DscNodeConfigurationListResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
DscNodeConfiguration dscNodeConfigurationInstance = new DscNodeConfiguration();
result.DscNodeConfigurations.Add(dscNodeConfigurationInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
dscNodeConfigurationInstance.Name = nameInstance;
}
JToken lastModifiedTimeValue = valueValue["lastModifiedTime"];
if (lastModifiedTimeValue != null && lastModifiedTimeValue.Type != JTokenType.Null)
{
DateTimeOffset lastModifiedTimeInstance = ((DateTimeOffset)lastModifiedTimeValue);
dscNodeConfigurationInstance.LastModifiedTime = lastModifiedTimeInstance;
}
JToken creationTimeValue = valueValue["creationTime"];
if (creationTimeValue != null && creationTimeValue.Type != JTokenType.Null)
{
DateTimeOffset creationTimeInstance = ((DateTimeOffset)creationTimeValue);
dscNodeConfigurationInstance.CreationTime = creationTimeInstance;
}
JToken configurationValue = valueValue["configuration"];
if (configurationValue != null && configurationValue.Type != JTokenType.Null)
{
DscConfigurationAssociationProperty configurationInstance = new DscConfigurationAssociationProperty();
dscNodeConfigurationInstance.Configuration = configurationInstance;
JToken nameValue2 = configurationValue["name"];
if (nameValue2 != null && nameValue2.Type != JTokenType.Null)
{
string nameInstance2 = ((string)nameValue2);
configurationInstance.Name = nameInstance2;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
dscNodeConfigurationInstance.Id = idInstance;
}
}
}
JToken odatanextLinkValue = responseDoc["odata.nextLink"];
if (odatanextLinkValue != null && odatanextLinkValue.Type != JTokenType.Null)
{
string odatanextLinkInstance = Regex.Match(((string)odatanextLinkValue), "^.*[&\\?]\\$skiptoken=([^&]*)(&.*)?").Groups[1].Value;
result.SkipToken = odatanextLinkInstance;
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
FluorineFx open source library
Copyright (C) 2007 Zoltan Csibi, zoltan@TheSilentGroup.com, FluorineFx.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using System.Runtime.Serialization;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using FluorineFx.Util;
using FluorineFx.Exceptions;
namespace FluorineFx
{
/// <summary>
/// The ASObject class represents a Flash object.
/// </summary>
[TypeConverter(typeof(ASObjectConverter))]
#if !SILVERLIGHT
[Serializable]
#endif
public class ASObject : Dictionary<string, Object>
{
private string _typeName;
/// <summary>
/// Initializes a new instance of the ASObject class.
/// </summary>
public ASObject()
{
}
/// <summary>
/// Initializes a new instance of the ASObject class.
/// </summary>
/// <param name="typeName">Typed object type name.</param>
public ASObject(string typeName)
{
_typeName = typeName;
}
/// <summary>
/// Initializes a new instance of the ASObject class by copying the elements from the specified dictionary to the new ASObject object.
/// </summary>
/// <param name="dictionary">The IDictionary object to copy to a new ASObject object.</param>
public ASObject(IDictionary<string, object> dictionary)
: base(dictionary)
{
}
#if !SILVERLIGHT
/// <summary>
/// Initializes a new instance of an ASObject object during deserialization.
/// </summary>
/// <param name="info">The information needed to serialize an object.</param>
/// <param name="context">The source or destination for the serialization stream.</param>
public ASObject(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Gets or sets the type name for a typed object.
/// </summary>
public string TypeName
{
get { return _typeName; }
set { _typeName = value; }
}
/// <summary>
/// Gets the Boolean value indicating whether the ASObject is typed.
/// </summary>
public bool IsTypedObject
{
get { return !string.IsNullOrEmpty(_typeName); }
}
/// <summary>
/// Returns a string that represents the current ASObject object.
/// </summary>
/// <returns>A string that represents the current ASObject object.</returns>
public override string ToString()
{
StringBuilder sb = new StringBuilder();
if( IsTypedObject )
sb.Append(TypeName);
sb.Append("{");
int i = 0;
foreach (KeyValuePair<string, object> entry in this)
{
if (i != 0)
sb.Append(", ");
sb.Append(entry.Key);
i++;
}
sb.Append("}");
return sb.ToString();
}
}
/// <summary>
/// Provides a type converter to convert ASObject objects to and from various other representations.
/// </summary>
public class ASObjectConverter : TypeConverter
{
/// <summary>
/// Overloaded. Returns whether this converter can convert the object to the specified type.
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
/// <param name="destinationType">A Type that represents the type you want to convert to.</param>
/// <returns>true if this converter can perform the conversion; otherwise, false.</returns>
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
if (destinationType.IsValueType || destinationType.IsEnum)
return false;
if (!ReflectionUtils.IsInstantiatableType(destinationType))
return false;
return true;
}
/// <summary>
/// This type supports the Fluorine infrastructure and is not intended to be used directly from your code.
/// </summary>
/// <param name="context">An ITypeDescriptorContext that provides a format context.</param>
/// <param name="culture">A CultureInfo object. If a null reference (Nothing in Visual Basic) is passed, the current culture is assumed.</param>
/// <param name="value">The Object to convert.</param>
/// <param name="destinationType">The Type to convert the value parameter to.</param>
/// <returns>An Object that represents the converted value.</returns>
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
ASObject aso = value as ASObject;
if (!ReflectionUtils.IsInstantiatableType(destinationType))
return null;
object instance = TypeHelper.CreateInstance(destinationType);
if (instance != null)
{
foreach (string memberName in aso.Keys)
{
object val = aso[memberName];
//MemberInfo mi = ReflectionUtils.GetMember(destinationType, key, MemberTypes.Field | MemberTypes.Property);
//if (mi != null)
// ReflectionUtils.SetMemberValue(mi, result, aso[key]);
PropertyInfo propertyInfo = null;
try
{
propertyInfo = destinationType.GetProperty(memberName);
}
catch (AmbiguousMatchException)
{
//To resolve the ambiguity, include BindingFlags.DeclaredOnly to restrict the search to members that are not inherited.
propertyInfo = destinationType.GetProperty(memberName, BindingFlags.DeclaredOnly | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance);
}
if (propertyInfo != null)
{
try
{
val = TypeHelper.ChangeType(val, propertyInfo.PropertyType);
if (propertyInfo.CanWrite && propertyInfo.GetSetMethod() != null)
{
if (propertyInfo.GetIndexParameters() == null || propertyInfo.GetIndexParameters().Length == 0)
propertyInfo.SetValue(instance, val, null);
else
{
string msg = __Res.GetString(__Res.Reflection_PropertyIndexFail, string.Format("{0}.{1}", destinationType.FullName, memberName));
throw new FluorineException(msg);
}
}
else
{
//string msg = __Res.GetString(__Res.Reflection_PropertyReadOnly, string.Format("{0}.{1}", type.FullName, memberName));
}
}
catch (Exception ex)
{
string msg = __Res.GetString(__Res.Reflection_PropertySetFail, string.Format("{0}.{1}", destinationType.FullName, memberName), ex.Message);
throw new FluorineException(msg);
}
}
else
{
FieldInfo fi = destinationType.GetField(memberName, BindingFlags.Public | BindingFlags.Instance);
try
{
if (fi != null)
{
val = TypeHelper.ChangeType(val, fi.FieldType);
fi.SetValue(instance, val);
}
else
{
//string msg = __Res.GetString(__Res.Reflection_MemberNotFound, string.Format("{0}.{1}", destinationType.FullName, memberName));
}
}
catch (Exception ex)
{
string msg = __Res.GetString(__Res.Reflection_FieldSetFail, string.Format("{0}.{1}", destinationType.FullName, memberName), ex.Message);
throw new FluorineException(msg);
}
}
}
}
return instance;
}
}
}
| |
using J2N.Collections.Generic.Extensions;
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using JCG = J2N.Collections.Generic;
using CompoundFileDirectory = Lucene.Net.Store.CompoundFileDirectory;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Codecs.Lucene3x
{
/*
* 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 IndexFileNames = Lucene.Net.Index.IndexFileNames;
using IndexFormatTooNewException = Lucene.Net.Index.IndexFormatTooNewException;
using IndexFormatTooOldException = Lucene.Net.Index.IndexFormatTooOldException;
using IndexInput = Lucene.Net.Store.IndexInput;
using IOContext = Lucene.Net.Store.IOContext;
using IOUtils = Lucene.Net.Util.IOUtils;
using SegmentCommitInfo = Lucene.Net.Index.SegmentCommitInfo;
using SegmentInfo = Lucene.Net.Index.SegmentInfo;
using SegmentInfos = Lucene.Net.Index.SegmentInfos;
/// <summary>
/// Lucene 3x implementation of <see cref="SegmentInfoReader"/>.
/// <para/>
/// @lucene.experimental
/// </summary>
[Obsolete("Only for reading existing 3.x indexes")]
public class Lucene3xSegmentInfoReader : SegmentInfoReader
{
public static void ReadLegacyInfos(SegmentInfos infos, Directory directory, IndexInput input, int format)
{
infos.Version = input.ReadInt64(); // read version
infos.Counter = input.ReadInt32(); // read counter
Lucene3xSegmentInfoReader reader = new Lucene3xSegmentInfoReader();
for (int i = input.ReadInt32(); i > 0; i--) // read segmentInfos
{
SegmentCommitInfo siPerCommit = reader.ReadLegacySegmentInfo(directory, format, input);
SegmentInfo si = siPerCommit.Info;
if (si.Version == null)
{
// Could be a 3.0 - try to open the doc stores - if it fails, it's a
// 2.x segment, and an IndexFormatTooOldException will be thrown,
// which is what we want.
Directory dir = directory;
if (Lucene3xSegmentInfoFormat.GetDocStoreOffset(si) != -1)
{
if (Lucene3xSegmentInfoFormat.GetDocStoreIsCompoundFile(si))
{
dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(Lucene3xSegmentInfoFormat.GetDocStoreSegment(si), "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION), IOContext.READ_ONCE, false);
}
}
else if (si.UseCompoundFile)
{
dir = new CompoundFileDirectory(dir, IndexFileNames.SegmentFileName(si.Name, "", IndexFileNames.COMPOUND_FILE_EXTENSION), IOContext.READ_ONCE, false);
}
try
{
Lucene3xStoredFieldsReader.CheckCodeVersion(dir, Lucene3xSegmentInfoFormat.GetDocStoreSegment(si));
}
finally
{
// If we opened the directory, close it
if (dir != directory)
{
dir.Dispose();
}
}
// Above call succeeded, so it's a 3.0 segment. Upgrade it so the next
// time the segment is read, its version won't be null and we won't
// need to open FieldsReader every time for each such segment.
si.Version = "3.0";
}
else if (si.Version.Equals("2.x", StringComparison.Ordinal))
{
// If it's a 3x index touched by 3.1+ code, then segments record their
// version, whether they are 2.x ones or not. We detect that and throw
// appropriate exception.
throw new IndexFormatTooOldException("segment " + si.Name + " in resource " + input, si.Version);
}
infos.Add(siPerCommit);
}
infos.UserData = input.ReadStringStringMap();
}
public override SegmentInfo Read(Directory directory, string segmentName, IOContext context)
{
// NOTE: this is NOT how 3.x is really written...
string fileName = IndexFileNames.SegmentFileName(segmentName, "", Lucene3xSegmentInfoFormat.UPGRADED_SI_EXTENSION);
bool success = false;
IndexInput input = directory.OpenInput(fileName, context);
try
{
SegmentInfo si = ReadUpgradedSegmentInfo(segmentName, directory, input);
success = true;
return si;
}
finally
{
if (!success)
{
IOUtils.DisposeWhileHandlingException(input);
}
else
{
input.Dispose();
}
}
}
private static void AddIfExists(Directory dir, ISet<string> files, string fileName)
{
if (dir.FileExists(fileName))
{
files.Add(fileName);
}
}
/// <summary>
/// Reads from legacy 3.x segments_N. </summary>
private SegmentCommitInfo ReadLegacySegmentInfo(Directory dir, int format, IndexInput input)
{
// check that it is a format we can understand
if (format > Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS)
{
throw new IndexFormatTooOldException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1);
}
if (format < Lucene3xSegmentInfoFormat.FORMAT_3_1)
{
throw new IndexFormatTooNewException(input, format, Lucene3xSegmentInfoFormat.FORMAT_DIAGNOSTICS, Lucene3xSegmentInfoFormat.FORMAT_3_1);
}
string version;
if (format <= Lucene3xSegmentInfoFormat.FORMAT_3_1)
{
version = input.ReadString();
}
else
{
version = null;
}
string name = input.ReadString();
int docCount = input.ReadInt32();
long delGen = input.ReadInt64();
int docStoreOffset = input.ReadInt32();
IDictionary<string, string> attributes = new Dictionary<string, string>();
// parse the docstore stuff and shove it into attributes
string docStoreSegment;
bool docStoreIsCompoundFile;
if (docStoreOffset != -1)
{
docStoreSegment = input.ReadString();
docStoreIsCompoundFile = input.ReadByte() == SegmentInfo.YES;
attributes[Lucene3xSegmentInfoFormat.DS_OFFSET_KEY] = Convert.ToString(docStoreOffset, CultureInfo.InvariantCulture);
attributes[Lucene3xSegmentInfoFormat.DS_NAME_KEY] = docStoreSegment;
attributes[Lucene3xSegmentInfoFormat.DS_COMPOUND_KEY] = Convert.ToString(docStoreIsCompoundFile, CultureInfo.InvariantCulture);
}
else
{
docStoreSegment = name;
docStoreIsCompoundFile = false;
}
// pre-4.0 indexes write a byte if there is a single norms file
byte b = input.ReadByte();
//System.out.println("version=" + version + " name=" + name + " docCount=" + docCount + " delGen=" + delGen + " dso=" + docStoreOffset + " dss=" + docStoreSegment + " dssCFs=" + docStoreIsCompoundFile + " b=" + b + " format=" + format);
if (Debugging.AssertsEnabled) Debugging.Assert(1 == b, () => "expected 1 but was: " + b + " format: " + format);
int numNormGen = input.ReadInt32();
IDictionary<int, long> normGen;
if (numNormGen == SegmentInfo.NO)
{
normGen = null;
}
else
{
normGen = new Dictionary<int, long>();
for (int j = 0; j < numNormGen; j++)
{
normGen[j] = input.ReadInt64();
}
}
bool isCompoundFile = input.ReadByte() == SegmentInfo.YES;
int delCount = input.ReadInt32();
if (Debugging.AssertsEnabled) Debugging.Assert(delCount <= docCount);
bool hasProx = input.ReadByte() == 1;
IDictionary<string, string> diagnostics = input.ReadStringStringMap();
if (format <= Lucene3xSegmentInfoFormat.FORMAT_HAS_VECTORS)
{
// NOTE: unused
int hasVectors = input.ReadByte();
}
// Replicate logic from 3.x's SegmentInfo.files():
ISet<string> files = new JCG.HashSet<string>();
if (isCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(name, "", IndexFileNames.COMPOUND_FILE_EXTENSION));
}
else
{
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xFieldInfosReader.FIELD_INFOS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.FREQ_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.PROX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xPostingsFormat.TERMS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xNormsProducer.NORMS_EXTENSION));
}
if (docStoreOffset != -1)
{
if (docStoreIsCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xCodec.COMPOUND_FILE_STORE_EXTENSION));
}
else
{
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION));
files.Add(IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(docStoreSegment, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION));
}
}
else if (!isCompoundFile)
{
files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_INDEX_EXTENSION));
files.Add(IndexFileNames.SegmentFileName(name, "", Lucene3xStoredFieldsReader.FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_INDEX_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_FIELDS_EXTENSION));
AddIfExists(dir, files, IndexFileNames.SegmentFileName(name, "", Lucene3xTermVectorsReader.VECTORS_DOCUMENTS_EXTENSION));
}
// parse the normgen stuff and shove it into attributes
if (normGen != null)
{
attributes[Lucene3xSegmentInfoFormat.NORMGEN_KEY] = Convert.ToString(numNormGen, CultureInfo.InvariantCulture);
foreach (KeyValuePair<int, long> ent in normGen)
{
long gen = ent.Value;
if (gen >= SegmentInfo.YES)
{
// Definitely a separate norm file, with generation:
files.Add(IndexFileNames.FileNameFromGeneration(name, "s" + ent.Key, gen));
attributes[Lucene3xSegmentInfoFormat.NORMGEN_PREFIX + ent.Key] = Convert.ToString(gen, CultureInfo.InvariantCulture);
}
else if (gen == SegmentInfo.NO)
{
// No separate norm
}
else
{
// We should have already hit indexformat too old exception
if (Debugging.AssertsEnabled) Debugging.Assert(false);
}
}
}
SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, attributes.AsReadOnly());
info.SetFiles(files);
SegmentCommitInfo infoPerCommit = new SegmentCommitInfo(info, delCount, delGen, -1);
return infoPerCommit;
}
private SegmentInfo ReadUpgradedSegmentInfo(string name, Directory dir, IndexInput input)
{
CodecUtil.CheckHeader(input, Lucene3xSegmentInfoFormat.UPGRADED_SI_CODEC_NAME, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_START, Lucene3xSegmentInfoFormat.UPGRADED_SI_VERSION_CURRENT);
string version = input.ReadString();
int docCount = input.ReadInt32();
IDictionary<string, string> attributes = input.ReadStringStringMap();
bool isCompoundFile = input.ReadByte() == SegmentInfo.YES;
IDictionary<string, string> diagnostics = input.ReadStringStringMap();
ISet<string> files = input.ReadStringSet();
SegmentInfo info = new SegmentInfo(dir, version, name, docCount, isCompoundFile, null, diagnostics, attributes.AsReadOnly());
info.SetFiles(files);
return info;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.IO;
using System.Linq;
using FluentAssertions;
using NUnit.Framework;
using Toscana.Common;
using Toscana.Engine;
using Toscana.Exceptions;
namespace Toscana.Tests
{
[TestFixture]
public class ToscaServiceTemplateTests
{
[Test]
public void Ctor_NodeTypes_Initialized_To_Empty()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.NodeTypes.Should().NotBeNull();
toscaSimpleProfile.NodeTypes.Should().HaveCount(0);
}
[Test]
public void Ctor_CapabilityTypes_Initialized_To_Empty()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.CapabilityTypes.Should().NotBeNull();
toscaSimpleProfile.CapabilityTypes.Should().HaveCount(0);
}
[Test]
public void Ctor_Imports_Initialized_To_Empty()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.Imports.Should().NotBeNull();
toscaSimpleProfile.Imports.Should().HaveCount(0);
}
[Test]
public void Metadata_Initialized_To_Empty_Dictionary()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.Metadata.Should().NotBeNull();
toscaSimpleProfile.Metadata.Should().HaveCount(0);
}
[Test]
public void RelationshipTypes_Initialized_To_Empty_Dictionary()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.RelationshipTypes.Should().NotBeNull();
toscaSimpleProfile.RelationshipTypes.Should().HaveCount(0);
}
[Test]
public void TopologyTemplate_Should_Be_Initialized()
{
var toscaSimpleProfile = new ToscaServiceTemplate();
toscaSimpleProfile.TopologyTemplate.Should().NotBeNull();
}
[Test]
public void ToscaDefinitionsVersion_Invalid_ValidationExceptionThrown()
{
// Arrange
var toscaSimpleProfile = new ToscaServiceTemplate
{
ToscaDefinitionsVersion = "INVALID"
};
var toscaValidator = new ToscaValidator<ToscaServiceTemplate>();
// Act
Action action = () => toscaValidator.Validate(toscaSimpleProfile);
// Assert
action.ShouldThrow<ToscaValidationException>()
.WithMessage("tosca_definitions_version shall be tosca_simple_yaml_1_0");
}
[Test]
public void ToscaDefinitionsVersion_Valid_NoException()
{
// Arrange
var toscaSimpleProfile = new ToscaServiceTemplate
{
ToscaDefinitionsVersion = "tosca_simple_yaml_1_0"
};
var toscaValidator = new ToscaValidator<ToscaServiceTemplate>();
// Act
Action action = () => toscaValidator.Validate(toscaSimpleProfile);
// Assert
action.ShouldNotThrow<Exception>();
}
[Test]
public void Parse_Tosca_Yaml_From_Stream_Succeeds()
{
const string toscaString = @"
tosca_definitions_version: tosca_simple_yaml_1_0
node_types:
example.TransactionSubsystem:
properties:
num_cpus:
type: integer
description: Number of CPUs requested for a software node instance.
default: 1
status: experimental
required: true
entry_schema: default
constraints:
- valid_values: [ 1, 2, 4, 8 ]";
var tosca = ToscaServiceTemplate.Load(toscaString.ToMemoryStream());
// Assert
tosca.ToscaDefinitionsVersion.Should().Be("tosca_simple_yaml_1_0");
tosca.Description.Should().BeNull();
tosca.NodeTypes.Should().HaveCount(1);
var nodeType = tosca.NodeTypes["example.TransactionSubsystem"];
nodeType.Properties.Should().HaveCount(1);
var numCpusProperty = nodeType.Properties["num_cpus"];
numCpusProperty.Type.Should().Be("integer");
numCpusProperty.Description.Should().Be("Number of CPUs requested for a software node instance.");
numCpusProperty.Default.Should().Be("1");
numCpusProperty.Required.Should().BeTrue();
numCpusProperty.Status.Should().Be(ToscaPropertyStatus.experimental);
numCpusProperty.EntrySchema.Type.Should().Be("default");
numCpusProperty.Constraints.Should().HaveCount(1);
numCpusProperty.Constraints.Single().Should().HaveCount(1);
var validValues = (List<object>)numCpusProperty.Constraints.Single()["valid_values"];
validValues.Should().BeEquivalentTo(new List<object> { "1", "2", "4", "8" });
}
[Test]
public void Load_Service_Template_From_Stream_And_Save_Succeeds()
{
const string toscaString = @"
tosca_definitions_version: tosca_simple_yaml_1_0
node_types:
example.TransactionSubsystem:
properties:
num_cpus:
type: integer
description: Number of CPUs requested for a software node instance.
default: 1
status: experimental
required: true
entry_schema: default
constraints:
- valid_values: [ 1, 2, 4, 8 ]";
var serviceTemplate = ToscaServiceTemplate.Load(toscaString.ToMemoryStream());
byte[] savedTemplateBuffer;
using (var memoryStream = new MemoryStream())
{
serviceTemplate.Save(memoryStream);
memoryStream.Flush();
savedTemplateBuffer = memoryStream.GetBuffer();
}
var loadedAfterSaveTemplate = ToscaServiceTemplate.Load(new MemoryStream(savedTemplateBuffer));
// Assert
loadedAfterSaveTemplate.ToscaDefinitionsVersion.Should().Be("tosca_simple_yaml_1_0");
loadedAfterSaveTemplate.Description.Should().BeNull();
loadedAfterSaveTemplate.NodeTypes.Should().HaveCount(1);
var nodeType = serviceTemplate.NodeTypes["example.TransactionSubsystem"];
nodeType.Properties.Should().HaveCount(1);
var numCpusProperty = nodeType.Properties["num_cpus"];
numCpusProperty.Type.Should().Be("integer");
numCpusProperty.Description.Should().Be("Number of CPUs requested for a software node instance.");
numCpusProperty.Default.Should().Be("1");
numCpusProperty.Required.Should().BeTrue();
numCpusProperty.Status.Should().Be(ToscaPropertyStatus.experimental);
numCpusProperty.EntrySchema.Type.Should().Be("default");
numCpusProperty.Constraints.Should().HaveCount(1);
numCpusProperty.Constraints.Single().Should().HaveCount(1);
var validValues = (List<object>)numCpusProperty.Constraints.Single()["valid_values"];
validValues.Should().BeEquivalentTo(new List<object> { "1", "2", "4", "8" });
}
[Test]
public void Service_Template_With_Complex_Data_Type_Can_Be_Parsed()
{
string toscaServiceTemplate = @"
tosca_definitions_version: tosca_simple_yaml_1_0
node_types:
tosca.nodes.SoftwareComponent:
derived_from: tosca.nodes.Root
properties:
# domain-specific software component version
component_version:
type: version
required: false
admin_credential:
type: tosca.datatypes.Credential
required: false
requirements:
- host:
capability: tosca.capabilities.Container
node: tosca.nodes.Compute
relationship: tosca.relationships.HostedOn";
var serviceTemplate = ToscaServiceTemplate.Load(toscaServiceTemplate.ToMemoryStream());
var toscaMetadata = new ToscaMetadata
{ CsarVersion = new Version(1,1), EntryDefinitions = "tosca.yml", ToscaMetaFileVersion = new Version(1,1), CreatedBy = "anonymous" };
var cloudServiceArchive = new ToscaCloudServiceArchive(toscaMetadata);
cloudServiceArchive.AddToscaServiceTemplate("tosca.yml", serviceTemplate);
List<ValidationResult> results;
cloudServiceArchive.TryValidate(out results)
.Should()
.BeTrue(string.Join(Environment.NewLine, results.Select(r => r.ErrorMessage)));
}
}
}
| |
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
namespace EduHub.Data.Entities
{
/// <summary>
/// General Ledger Budgets
/// </summary>
[GeneratedCode("EduHub Data", "0.9")]
public sealed partial class GLBUDG : EduHubEntity
{
#region Navigation Property Cache
private GL Cache_CODE_GL;
private KGLINIT Cache_INITIATIVE_KGLINIT;
#endregion
#region Foreign Navigation Properties
private IReadOnlyList<GLFBUDG> Cache_BUDGETKEY_GLFBUDG_BKEY;
#endregion
/// <inheritdoc />
public override DateTime? EntityLastModified
{
get
{
return LW_DATE;
}
}
#region Field Properties
/// <summary>
/// Combination of subprog,prog,code,init
/// [Uppercase Alphanumeric (15)]
/// </summary>
public string BUDGETKEY { get; internal set; }
/// <summary>
/// Must already exist as a SUBPROGRAM
/// [Uppercase Alphanumeric (4)]
/// </summary>
public string SUBPROGRAM { get; internal set; }
/// <summary>
/// eg, INCOME
/// [Alphanumeric (30)]
/// </summary>
public string TITLE { get; internal set; }
/// <summary>
/// GL Account
/// [Uppercase Alphanumeric (10)]
/// </summary>
public string CODE { get; internal set; }
/// <summary>
/// Program
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string GL_PROGRAM { get; internal set; }
/// <summary>
/// Not mandatory
/// [Uppercase Alphanumeric (3)]
/// </summary>
public string INITIATIVE { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR01 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR02 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR03 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR04 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR05 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR06 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR07 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR08 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR09 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR10 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR11 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? CURR12 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? OPBAL { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR01 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR02 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR03 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR04 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR05 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR06 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR07 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR08 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR09 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR10 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR11 { get; internal set; }
/// <summary>
/// Not used but required fields
/// </summary>
public decimal? LASTYR12 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets this year
/// </summary>
public decimal? BUDG12 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets next year
/// </summary>
public decimal? NEXTBUDG12 { get; internal set; }
/// <summary>
/// Annual budget this year
/// </summary>
public decimal? ANNUALBUDG { get; internal set; }
/// <summary>
/// Annual budget next year
/// </summary>
public decimal? NEXT_ANN_BUDG { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG01 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG02 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG03 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG04 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG05 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG06 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG07 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG08 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG09 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG10 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG11 { get; internal set; }
/// <summary>
/// Monthly budgets last year
/// </summary>
public decimal? LASTBUDG12 { get; internal set; }
/// <summary>
/// Annual budget last year
/// </summary>
public decimal? LAST_ANN_BUDG { get; internal set; }
/// <summary>
/// Imported Y/N
/// [Alphanumeric (1)]
/// </summary>
public string IMPORTED { get; internal set; }
/// <summary>
/// Last write date
/// </summary>
public DateTime? LW_DATE { get; internal set; }
/// <summary>
/// Last write time
/// </summary>
public short? LW_TIME { get; internal set; }
/// <summary>
/// Last operator
/// [Uppercase Alphanumeric (128)]
/// </summary>
public string LW_USER { get; internal set; }
#endregion
#region Navigation Properties
/// <summary>
/// GL (General Ledger) related entity by [GLBUDG.CODE]->[GL.CODE]
/// GL Account
/// </summary>
public GL CODE_GL
{
get
{
if (CODE == null)
{
return null;
}
if (Cache_CODE_GL == null)
{
Cache_CODE_GL = Context.GL.FindByCODE(CODE);
}
return Cache_CODE_GL;
}
}
/// <summary>
/// KGLINIT (General Ledger Initiatives) related entity by [GLBUDG.INITIATIVE]->[KGLINIT.INITIATIVE]
/// Not mandatory
/// </summary>
public KGLINIT INITIATIVE_KGLINIT
{
get
{
if (INITIATIVE == null)
{
return null;
}
if (Cache_INITIATIVE_KGLINIT == null)
{
Cache_INITIATIVE_KGLINIT = Context.KGLINIT.FindByINITIATIVE(INITIATIVE);
}
return Cache_INITIATIVE_KGLINIT;
}
}
#endregion
#region Foreign Navigation Properties
/// <summary>
/// GLFBUDG (SP2 dummy table) related entities by [GLBUDG.BUDGETKEY]->[GLFBUDG.BKEY]
/// Combination of subprog,prog,code,init
/// </summary>
public IReadOnlyList<GLFBUDG> BUDGETKEY_GLFBUDG_BKEY
{
get
{
if (Cache_BUDGETKEY_GLFBUDG_BKEY == null &&
!Context.GLFBUDG.TryFindByBKEY(BUDGETKEY, out Cache_BUDGETKEY_GLFBUDG_BKEY))
{
Cache_BUDGETKEY_GLFBUDG_BKEY = new List<GLFBUDG>().AsReadOnly();
}
return Cache_BUDGETKEY_GLFBUDG_BKEY;
}
}
#endregion
}
}
| |
@import compass/css3
@function black($opacity)
@return rgba(0,0,0,$opacity)
@function white($opacity)
@return rgba(255,255,255,$opacity)
// keyframes mixin
=keyframes($name)
@-webkit-keyframes #{$name}
@content
@-moz-keyframes #{$name}
@content
*
+box-sizing(border-box)
$tancolor: #D0B076
$linecolor: rgba(0,0,255,0.05)
$baseline: 24px
$gearbox-height: 150px
html
height: 100%
body
background: #333
position: relative
height: 100%
margin: 0px
+keyframes(clockwise)
0%
+transform(rotate(0deg))
100%
+transform(rotate(360deg))
+keyframes(counter-clockwise)
0%
+transform(rotate(0deg))
100%
+transform(rotate(-360deg))
.container
position: absolute
top: 50%
left: 50%
margin-left: -100px
height: $gearbox-height
width: 200px
margin-top: -($gearbox-height / 2)
.gearbox
background: #111
height: $gearbox-height
width: 200px
position: relative
border: none
overflow: hidden
+border-radius(6px)
+box-shadow(0px 0px 0px 1px white(0.1))
.overlay
+border-radius(6px)
content: ''
position: absolute
top: 0
left: 0
width: 100%
height: 100%
z-index: 10
+box-shadow(inset 0px 0px 20px black(1))
+single-transition(background, .2s)
&.turn .overlay
background: rgba(0,0,0,0.0)
$gear-color: #555
$gear-size: 60px
$large-gear-size: $gear-size * 2
.gear
position: absolute
height: $gear-size
width: $gear-size
+box-shadow(0px -1px 0px 0px lighten($gear-color, 20%), 0px 1px 0px 0px darken($gear-color, 40%))
+border-radius($gear-size / 2)
&.large
height: $large-gear-size
width: $large-gear-size
+border-radius($large-gear-size / 2)
&:after
$large-gear-inner-size: $large-gear-size - 24px
height: $large-gear-size - 24px
width: $large-gear-size - 24px
+border-radius(($large-gear-size - 24px) / 2)
margin-left: -(($large-gear-size - 24px) / 2)
margin-top: -(($large-gear-size - 24px) / 2)
$center: 10px
&.one
top: $center + 2px
left: $center
&.two
top: 51 + $center
left: 50px + $center
&.three
top: 100px + $center
left: $center
&.four
top: $center + 3px
left: $center + 118px
&:after
content: ''
position: absolute
height: $gear-size - 24px
width: $gear-size - 24px
+border-radius(36px)
background: #111
// border: 1px solid lighten($gear-color, 10%)
top: 50%
left: 50%
margin-left: -(($gear-size - 24px) / 2)
margin-top: -(($gear-size - 24px) / 2)
z-index: 3
+box-shadow(0px 0px 10px white(0.1), inset 0px 0px 10px black(0.1), inset 0px 2px 0px 0px darken($gear-color,30%), inset 0px -1px 0px 0px lighten($gear-color, 20%) )
.gear-inner
position: relative
height: 100%
width: 100%
background: $gear-color
-webkit-animation-iteration-count: infinite
-moz-animation-iteration-count: infinite
+border-radius($gear-size / 2)
border: 1px solid white(0.1)
.large &
+border-radius($large-gear-size / 2)
.gear.one &
-webkit-animation: counter-clockwise 3s infinite linear
-moz-animation: counter-clockwise 3s infinite linear
.gear.two &
-webkit-animation: clockwise 3s infinite linear
-moz-animation: clockwise 3s infinite linear
.gear.three &
-webkit-animation: counter-clockwise 3s infinite linear
-moz-animation: counter-clockwise 3s infinite linear
.gear.four &
-webkit-animation: counter-clockwise 6s infinite linear
-moz-animation: counter-clockwise 6s infinite linear
.bar
$bar-width: 16px
$bar-height: 8px
$actual-height: $bar-width
$actual-width: ($bar-height * 2) + $gear-size
background: $gear-color
height: $actual-height
width: $actual-width
position: absolute
left: 50%
margin-left: -($actual-width / 2)
top: 50%
margin-top: -($actual-height / 2)
+border-radius(2px)
border-left: 1px solid white(0.1)
border-right: 1px solid white(0.1)
.large &
$large-bar-width: ($bar-height * 2) + ($gear-size * 2)
margin-left: -($large-bar-width / 2)
width: $large-bar-width
&:nth-child(2)
+transform(rotate(60deg))
&:nth-child(3)
+transform(rotate(120deg))
&:nth-child(4)
+transform(rotate(90deg))
&:nth-child(5)
+transform(rotate(30deg))
&:nth-child(6)
+transform(rotate(150deg))
h1
font-family: 'Helvetica'
text-align: center
text-transform: uppercase
color: #888
font-size: 19px
padding-top: 10px
text-shadow: 1px 1px 0px #111
| |
//
// Utilities.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2011 Jb Evain
//
// 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 Mono.Cecil.Metadata;
namespace Mono.Cecil
{
static partial class Mixin
{
public static uint ReadCompressedUInt32(byte[] data, ref int position)
{
uint integer;
if ((data[position] & 0x80) == 0)
{
integer = data[position];
position++;
}
else if ((data[position] & 0x40) == 0)
{
integer = (uint)(data[position] & ~0x80) << 8;
integer |= data[position + 1];
position += 2;
}
else
{
integer = (uint)(data[position] & ~0xc0) << 24;
integer |= (uint)data[position + 1] << 16;
integer |= (uint)data[position + 2] << 8;
integer |= (uint)data[position + 3];
position += 4;
}
return integer;
}
public static MetadataToken GetMetadataToken(CodedIndex self, uint data)
{
uint rid;
TokenType token_type;
switch (self)
{
case CodedIndex.TypeDefOrRef:
rid = data >> 2;
switch (data & 3)
{
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasConstant:
rid = data >> 2;
switch (data & 3)
{
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
case 2:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.HasCustomAttribute:
rid = data >> 5;
switch (data & 31)
{
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.Field; goto ret;
case 2:
token_type = TokenType.TypeRef; goto ret;
case 3:
token_type = TokenType.TypeDef; goto ret;
case 4:
token_type = TokenType.Param; goto ret;
case 5:
token_type = TokenType.InterfaceImpl; goto ret;
case 6:
token_type = TokenType.MemberRef; goto ret;
case 7:
token_type = TokenType.Module; goto ret;
case 8:
token_type = TokenType.Permission; goto ret;
case 9:
token_type = TokenType.Property; goto ret;
case 10:
token_type = TokenType.Event; goto ret;
case 11:
token_type = TokenType.Signature; goto ret;
case 12:
token_type = TokenType.ModuleRef; goto ret;
case 13:
token_type = TokenType.TypeSpec; goto ret;
case 14:
token_type = TokenType.Assembly; goto ret;
case 15:
token_type = TokenType.AssemblyRef; goto ret;
case 16:
token_type = TokenType.File; goto ret;
case 17:
token_type = TokenType.ExportedType; goto ret;
case 18:
token_type = TokenType.ManifestResource; goto ret;
case 19:
token_type = TokenType.GenericParam; goto ret;
default:
goto exit;
}
case CodedIndex.HasFieldMarshal:
rid = data >> 1;
switch (data & 1)
{
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Param; goto ret;
default:
goto exit;
}
case CodedIndex.HasDeclSecurity:
rid = data >> 2;
switch (data & 3)
{
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
case 2:
token_type = TokenType.Assembly; goto ret;
default:
goto exit;
}
case CodedIndex.MemberRefParent:
rid = data >> 3;
switch (data & 7)
{
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.TypeRef; goto ret;
case 2:
token_type = TokenType.ModuleRef; goto ret;
case 3:
token_type = TokenType.Method; goto ret;
case 4:
token_type = TokenType.TypeSpec; goto ret;
default:
goto exit;
}
case CodedIndex.HasSemantics:
rid = data >> 1;
switch (data & 1)
{
case 0:
token_type = TokenType.Event; goto ret;
case 1:
token_type = TokenType.Property; goto ret;
default:
goto exit;
}
case CodedIndex.MethodDefOrRef:
rid = data >> 1;
switch (data & 1)
{
case 0:
token_type = TokenType.Method; goto ret;
case 1:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.MemberForwarded:
rid = data >> 1;
switch (data & 1)
{
case 0:
token_type = TokenType.Field; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default:
goto exit;
}
case CodedIndex.Implementation:
rid = data >> 2;
switch (data & 3)
{
case 0:
token_type = TokenType.File; goto ret;
case 1:
token_type = TokenType.AssemblyRef; goto ret;
case 2:
token_type = TokenType.ExportedType; goto ret;
default:
goto exit;
}
case CodedIndex.CustomAttributeType:
rid = data >> 3;
switch (data & 7)
{
case 2:
token_type = TokenType.Method; goto ret;
case 3:
token_type = TokenType.MemberRef; goto ret;
default:
goto exit;
}
case CodedIndex.ResolutionScope:
rid = data >> 2;
switch (data & 3)
{
case 0:
token_type = TokenType.Module; goto ret;
case 1:
token_type = TokenType.ModuleRef; goto ret;
case 2:
token_type = TokenType.AssemblyRef; goto ret;
case 3:
token_type = TokenType.TypeRef; goto ret;
default:
goto exit;
}
case CodedIndex.TypeOrMethodDef:
rid = data >> 1;
switch (data & 1)
{
case 0:
token_type = TokenType.TypeDef; goto ret;
case 1:
token_type = TokenType.Method; goto ret;
default: goto exit;
}
default:
goto exit;
}
ret:
return new MetadataToken(token_type, rid);
exit:
return MetadataToken.Zero;
}
public static int GetSize(CodedIndex self, Func<Table, int> counter)
{
int bits;
Table[] tables;
switch (self)
{
case CodedIndex.TypeDefOrRef:
bits = 2;
tables = new[] { Table.TypeDef, Table.TypeRef, Table.TypeSpec };
break;
case CodedIndex.HasConstant:
bits = 2;
tables = new[] { Table.Field, Table.Param, Table.Property };
break;
case CodedIndex.HasCustomAttribute:
bits = 5;
tables = new[] {
Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef,
Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef,
Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType,
Table.ManifestResource, Table.GenericParam
};
break;
case CodedIndex.HasFieldMarshal:
bits = 1;
tables = new[] { Table.Field, Table.Param };
break;
case CodedIndex.HasDeclSecurity:
bits = 2;
tables = new[] { Table.TypeDef, Table.Method, Table.Assembly };
break;
case CodedIndex.MemberRefParent:
bits = 3;
tables = new[] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec };
break;
case CodedIndex.HasSemantics:
bits = 1;
tables = new[] { Table.Event, Table.Property };
break;
case CodedIndex.MethodDefOrRef:
bits = 1;
tables = new[] { Table.Method, Table.MemberRef };
break;
case CodedIndex.MemberForwarded:
bits = 1;
tables = new[] { Table.Field, Table.Method };
break;
case CodedIndex.Implementation:
bits = 2;
tables = new[] { Table.File, Table.AssemblyRef, Table.ExportedType };
break;
case CodedIndex.CustomAttributeType:
bits = 3;
tables = new[] { Table.Method, Table.MemberRef };
break;
case CodedIndex.ResolutionScope:
bits = 2;
tables = new[] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef };
break;
case CodedIndex.TypeOrMethodDef:
bits = 1;
tables = new[] { Table.TypeDef, Table.Method };
break;
default:
throw new ArgumentException();
}
int max = 0;
for (int i = 0; i < tables.Length; i++)
{
max = System.Math.Max(counter(tables[i]), max);
}
return max < (1 << (16 - bits)) ? 2 : 4;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Xml.Serialization
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Schema;
using System.Globalization;
using System.Xml.Extensions;
using XmlSchema = System.ServiceModel.Dispatcher.XmlSchemaConstants;
using XmlSchemaFacet = System.Object;
using XmlSchemaSimpleType = System.Xml.Schema.XmlSchemaType;
// These classes provide a higher level view on reflection specific to
// Xml serialization, for example:
// - allowing one to talk about types w/o having them compiled yet
// - abstracting collections & arrays
// - abstracting classes, structs, interfaces
// - knowing about XSD primitives
// - dealing with Serializable and xmlelement
// and lots of other little details
internal enum TypeKind
{
Root,
Primitive,
Enum,
Struct,
Class,
Array,
Collection,
Enumerable,
Void,
Node,
Attribute,
Serializable
}
internal enum TypeFlags
{
None = 0x0,
Abstract = 0x1,
Reference = 0x2,
Special = 0x4,
CanBeAttributeValue = 0x8,
CanBeTextValue = 0x10,
CanBeElementValue = 0x20,
HasCustomFormatter = 0x40,
AmbiguousDataType = 0x80,
IgnoreDefault = 0x200,
HasIsEmpty = 0x400,
HasDefaultConstructor = 0x800,
XmlEncodingNotRequired = 0x1000,
UseReflection = 0x4000,
CollapseWhitespace = 0x8000,
OptionalValue = 0x10000,
CtorInaccessible = 0x20000,
UsePrivateImplementation = 0x40000,
GenericInterface = 0x80000,
Unsupported = 0x100000,
}
internal class TypeDesc
{
private string _name;
private string _fullName;
private string _cSharpName;
private TypeDesc _arrayElementTypeDesc;
private TypeDesc _arrayTypeDesc;
private TypeDesc _nullableTypeDesc;
private TypeKind _kind;
private XmlSchemaType _dataType;
private Type _type;
private TypeDesc _baseTypeDesc;
private TypeFlags _flags;
private string _formatterName;
private bool _isXsdType;
private int _weight;
private Exception _exception;
internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName)
{
_name = name.Replace('+', '.');
_fullName = fullName.Replace('+', '.');
_kind = kind;
_baseTypeDesc = baseTypeDesc;
_flags = flags;
_isXsdType = kind == TypeKind.Primitive;
if (_isXsdType)
_weight = 1;
else if (kind == TypeKind.Enum)
_weight = 2;
else if (_kind == TypeKind.Root)
_weight = -1;
else
_weight = baseTypeDesc == null ? 0 : baseTypeDesc.Weight + 1;
_dataType = dataType;
_formatterName = formatterName;
}
internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags)
: this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName)
{
_isXsdType = isXsdType;
_type = type;
}
internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc)
: this(name, fullName, null, kind, baseTypeDesc, flags, null)
{
_arrayElementTypeDesc = arrayElementTypeDesc;
_type = type;
}
public override string ToString()
{
return _fullName;
}
internal TypeFlags Flags
{
get { return _flags; }
}
internal bool IsXsdType
{
get { return _isXsdType; }
}
internal bool IsMappedType
{
get { return false; }
}
internal string Name
{
get { return _name; }
}
internal string FullName
{
get { return _fullName; }
}
internal string CSharpName
{
get
{
if (_cSharpName == null)
{
_cSharpName = _type == null ? CodeIdentifier.GetCSharpName(_fullName) : CodeIdentifier.GetCSharpName(_type);
}
return _cSharpName;
}
}
internal XmlSchemaType DataType
{
get { return _dataType; }
}
internal Type Type
{
get { return _type; }
}
internal string FormatterName
{
get { return _formatterName; }
}
internal TypeKind Kind
{
get { return _kind; }
}
internal bool IsValueType
{
get { return (_flags & TypeFlags.Reference) == 0; }
}
internal bool CanBeAttributeValue
{
get { return (_flags & TypeFlags.CanBeAttributeValue) != 0; }
}
internal bool XmlEncodingNotRequired
{
get { return (_flags & TypeFlags.XmlEncodingNotRequired) != 0; }
}
internal bool CanBeElementValue
{
get { return (_flags & TypeFlags.CanBeElementValue) != 0; }
}
internal bool CanBeTextValue
{
get { return (_flags & TypeFlags.CanBeTextValue) != 0; }
}
internal bool IsSpecial
{
get { return (_flags & TypeFlags.Special) != 0; }
}
internal bool HasCustomFormatter
{
get { return (_flags & TypeFlags.HasCustomFormatter) != 0; }
}
internal bool HasDefaultSupport
{
get { return (_flags & TypeFlags.IgnoreDefault) == 0; }
}
internal bool CollapseWhitespace
{
get { return (_flags & TypeFlags.CollapseWhitespace) != 0; }
}
internal bool HasDefaultConstructor
{
get { return (_flags & TypeFlags.HasDefaultConstructor) != 0; }
}
internal bool IsUnsupported
{
get { return (_flags & TypeFlags.Unsupported) != 0; }
}
internal bool IsGenericInterface
{
get { return (_flags & TypeFlags.GenericInterface) != 0; }
}
internal bool IsPrivateImplementation
{
get { return (_flags & TypeFlags.UsePrivateImplementation) != 0; }
}
internal bool CannotNew
{
get { return !HasDefaultConstructor || ConstructorInaccessible; }
}
internal bool IsAbstract
{
get { return (_flags & TypeFlags.Abstract) != 0; }
}
internal bool IsOptionalValue
{
get { return (_flags & TypeFlags.OptionalValue) != 0; }
}
internal bool UseReflection
{
get { return (_flags & TypeFlags.UseReflection) != 0; }
}
internal bool IsVoid
{
get { return _kind == TypeKind.Void; }
}
internal bool IsClass
{
get { return _kind == TypeKind.Class; }
}
internal bool IsStructLike
{
get { return _kind == TypeKind.Struct || _kind == TypeKind.Class; }
}
internal bool IsArrayLike
{
get { return _kind == TypeKind.Array || _kind == TypeKind.Collection || _kind == TypeKind.Enumerable; }
}
internal bool IsCollection
{
get { return _kind == TypeKind.Collection; }
}
internal bool IsEnumerable
{
get { return _kind == TypeKind.Enumerable; }
}
internal bool IsArray
{
get { return _kind == TypeKind.Array; }
}
internal bool IsPrimitive
{
get { return _kind == TypeKind.Primitive; }
}
internal bool IsEnum
{
get { return _kind == TypeKind.Enum; }
}
internal bool IsNullable
{
get { return !IsValueType; }
}
internal bool IsRoot
{
get { return _kind == TypeKind.Root; }
}
internal bool ConstructorInaccessible
{
get { return (_flags & TypeFlags.CtorInaccessible) != 0; }
}
internal Exception Exception
{
get { return _exception; }
set { _exception = value; }
}
internal TypeDesc GetNullableTypeDesc(Type type)
{
if (IsOptionalValue)
return this;
if (_nullableTypeDesc == null)
{
_nullableTypeDesc = new TypeDesc("NullableOf" + _name, "System.Nullable`1[" + _fullName + "]", null, TypeKind.Struct, this, _flags | TypeFlags.OptionalValue, _formatterName);
_nullableTypeDesc._type = type;
}
return _nullableTypeDesc;
}
internal void CheckSupported()
{
if (IsUnsupported)
{
if (Exception != null)
{
throw Exception;
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, FullName));
}
}
if (_baseTypeDesc != null)
_baseTypeDesc.CheckSupported();
if (_arrayElementTypeDesc != null)
_arrayElementTypeDesc.CheckSupported();
}
internal void CheckNeedConstructor()
{
if (!IsValueType && !IsAbstract && !HasDefaultConstructor)
{
_flags |= TypeFlags.Unsupported;
_exception = new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, FullName));
}
}
internal TypeDesc ArrayElementTypeDesc
{
get { return _arrayElementTypeDesc; }
set { _arrayElementTypeDesc = value; }
}
internal int Weight
{
get { return _weight; }
}
internal TypeDesc CreateArrayTypeDesc()
{
if (_arrayTypeDesc == null)
_arrayTypeDesc = new TypeDesc(null, _name + "[]", _fullName + "[]", TypeKind.Array, null, TypeFlags.Reference | (_flags & TypeFlags.UseReflection), this);
return _arrayTypeDesc;
}
internal TypeDesc BaseTypeDesc
{
get { return _baseTypeDesc; }
set
{
_baseTypeDesc = value;
_weight = _baseTypeDesc == null ? 0 : _baseTypeDesc.Weight + 1;
}
}
}
internal class TypeScope
{
private readonly Dictionary<Type, TypeDesc> _typeDescs = new Dictionary<Type, TypeDesc>();
private readonly Dictionary<Type, TypeDesc> _arrayTypeDescs = new Dictionary<Type, TypeDesc>();
private readonly List<TypeMapping> _typeMappings = new List<TypeMapping>();
private static readonly Dictionary<Type, TypeDesc> s_primitiveTypes = new Dictionary<Type, TypeDesc>();
private static readonly Dictionary<XmlSchemaType, TypeDesc> s_primitiveDataTypes = new Dictionary<XmlSchemaType, TypeDesc>();
private static NameTable s_primitiveNames = new NameTable();
private static string[] s_unsupportedTypes = new string[] {
"anyURI",
"duration",
"ENTITY",
"ENTITIES",
"gDay",
"gMonth",
"gMonthDay",
"gYear",
"gYearMonth",
"ID",
"IDREF",
"IDREFS",
"integer",
"language",
"negativeInteger",
"nonNegativeInteger",
"nonPositiveInteger",
//"normalizedString",
"NOTATION",
"positiveInteger",
"token"
};
static TypeScope()
{
AddPrimitive(typeof(string), "string", "String", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(int), "int", "Int32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(bool), "boolean", "Boolean", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(short), "short", "Int16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(long), "long", "Int64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(float), "float", "Single", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(double), "double", "Double", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(decimal), "decimal", "Decimal", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "dateTime", "DateTime", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(XmlQualifiedName), "QName", "XmlQualifiedName", TypeFlags.CanBeAttributeValue | TypeFlags.HasCustomFormatter | TypeFlags.HasIsEmpty | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.Reference);
AddPrimitive(typeof(byte), "unsignedByte", "Byte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(SByte), "byte", "SByte", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt16), "unsignedShort", "UInt16", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt32), "unsignedInt", "UInt32", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(UInt64), "unsignedLong", "UInt64", TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired);
// Types without direct mapping (ambiguous)
AddPrimitive(typeof(DateTime), "date", "Date", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(DateTime), "time", "Time", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.XmlEncodingNotRequired);
AddPrimitive(typeof(string), "Name", "XmlName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NCName", "XmlNCName", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKEN", "XmlNmToken", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(string), "NMTOKENS", "XmlNmTokens", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference);
AddPrimitive(typeof(byte[]), "base64Binary", "ByteArrayBase64", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
AddPrimitive(typeof(byte[]), "hexBinary", "ByteArrayHex", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.Reference | TypeFlags.IgnoreDefault | TypeFlags.XmlEncodingNotRequired | TypeFlags.HasDefaultConstructor);
// NOTE, Microsoft: byte[] can also be used to mean array of bytes. That datatype is not a primitive, so we
// can't use the AmbiguousDataType mechanism. To get an array of bytes in literal XML, apply [XmlArray] or
// [XmlArrayItem].
AddNonXsdPrimitive(typeof(Guid), "guid", UrtTypes.Namespace, "Guid", new XmlQualifiedName("string", XmlSchema.Namespace), null, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(char), "char", UrtTypes.Namespace, "Char", new XmlQualifiedName("unsignedShort", XmlSchema.Namespace), null, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.HasCustomFormatter | TypeFlags.IgnoreDefault);
AddNonXsdPrimitive(typeof(TimeSpan), "TimeSpan", UrtTypes.Namespace, "TimeSpan", new XmlQualifiedName("string", XmlSchema.Namespace), null, TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.XmlEncodingNotRequired | TypeFlags.IgnoreDefault);
// Unsuppoted types that we map to string, if in the future we decide
// to add support for them we would need to create custom formatters for them
// normalizedString is the only one unsuported type that suppose to preserve whitesapce
AddPrimitive(typeof(string), "normalizedString", "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.HasDefaultConstructor);
for (int i = 0; i < s_unsupportedTypes.Length; i++)
{
AddPrimitive(typeof(string), s_unsupportedTypes[i], "String", TypeFlags.AmbiguousDataType | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.Reference | TypeFlags.CollapseWhitespace);
}
}
internal static bool IsKnownType(Type type)
{
if (type == typeof(object))
return true;
if (type.GetTypeInfo().IsEnum)
return false;
switch (type.GetTypeCode())
{
case TypeCode.String: return true;
case TypeCode.Int32: return true;
case TypeCode.Boolean: return true;
case TypeCode.Int16: return true;
case TypeCode.Int64: return true;
case TypeCode.Single: return true;
case TypeCode.Double: return true;
case TypeCode.Decimal: return true;
case TypeCode.DateTime: return true;
case TypeCode.Byte: return true;
case TypeCode.SByte: return true;
case TypeCode.UInt16: return true;
case TypeCode.UInt32: return true;
case TypeCode.UInt64: return true;
case TypeCode.Char: return true;
default:
if (type == typeof(XmlQualifiedName))
return true;
else if (type == typeof(byte[]))
return true;
else if (type == typeof(Guid))
return true;
else if (type == typeof (TimeSpan))
return true;
else if (type == typeof(XmlNode[]))
return true;
break;
}
return false;
}
private static void AddPrimitive(Type type, string dataTypeName, string formatterName, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
TypeDesc typeDesc = new TypeDesc(type, true, dataType, formatterName, flags);
if (!s_primitiveTypes.ContainsKey(type))
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, XmlSchema.Namespace, typeDesc);
}
private static void AddNonXsdPrimitive(Type type, string dataTypeName, string ns, string formatterName, XmlQualifiedName baseTypeName, XmlSchemaFacet[] facets, TypeFlags flags)
{
XmlSchemaSimpleType dataType = new XmlSchemaSimpleType();
dataType.Name = dataTypeName;
TypeDesc typeDesc = new TypeDesc(type, false, dataType, formatterName, flags);
if (!s_primitiveTypes.ContainsKey(type))
s_primitiveTypes.Add(type, typeDesc);
s_primitiveDataTypes.Add(dataType, typeDesc);
s_primitiveNames.Add(dataTypeName, ns, typeDesc);
}
internal TypeDesc GetTypeDesc(string name, string ns)
{
return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue);
}
internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags)
{
TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns];
if (typeDesc != null)
{
if ((typeDesc.Flags & flags) != 0)
{
return typeDesc;
}
}
return null;
}
internal TypeDesc GetTypeDesc(Type type)
{
return GetTypeDesc(type, null, true, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference)
{
return GetTypeDesc(type, source, directReference, true);
}
internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError)
{
if (type.GetTypeInfo().ContainsGenericParameters)
{
throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type.ToString()));
}
TypeDesc typeDesc;
if (!s_primitiveTypes.TryGetValue(type, out typeDesc))
{
if (!_typeDescs.TryGetValue(type, out typeDesc))
{
typeDesc = ImportTypeDesc(type, source, directReference);
}
}
if (throwOnError)
typeDesc.CheckSupported();
return typeDesc;
}
internal TypeDesc GetArrayTypeDesc(Type type)
{
TypeDesc typeDesc;
if (!_arrayTypeDescs.TryGetValue(type, out typeDesc))
{
typeDesc = GetTypeDesc(type);
if (!typeDesc.IsArrayLike)
typeDesc = ImportTypeDesc(type, null, false);
typeDesc.CheckSupported();
_arrayTypeDescs.Add(type, typeDesc);
}
return typeDesc;
}
private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference)
{
TypeDesc typeDesc = null;
TypeKind kind;
Type arrayElementType = null;
Type baseType = null;
TypeFlags flags = 0;
Exception exception = null;
if (!type.GetTypeInfo().IsVisible)
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeInaccessible, type.FullName));
}
else if (directReference && (type.GetTypeInfo().IsAbstract && type.GetTypeInfo().IsSealed))
{
flags |= TypeFlags.Unsupported;
exception = new InvalidOperationException(SR.Format(SR.XmlTypeStatic, type.FullName));
}
if (!type.GetTypeInfo().IsValueType)
flags |= TypeFlags.Reference;
if (type == typeof(object))
{
kind = TypeKind.Root;
flags |= TypeFlags.HasDefaultConstructor;
}
else if (type == typeof(ValueType))
{
kind = TypeKind.Enum;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type == typeof(void))
{
kind = TypeKind.Void;
}
else if (typeof(IXmlSerializable).IsAssignableFrom(type))
{
kind = TypeKind.Serializable;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue;
flags |= GetConstructorFlags(type, ref exception);
}
else if (type.IsArray)
{
kind = TypeKind.Array;
if (type.GetArrayRank() > 1)
{
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedRank, type.FullName));
}
}
arrayElementType = type.GetElementType();
flags |= TypeFlags.HasDefaultConstructor;
}
else if (typeof(ICollection).IsAssignableFrom(type))
{
kind = TypeKind.Collection;
arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name);
flags |= GetConstructorFlags(type, ref exception);
}
else if (type == typeof(XmlQualifiedName))
{
kind = TypeKind.Primitive;
}
else if (type.GetTypeInfo().IsPrimitive)
{
kind = TypeKind.Primitive;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
else if (type.GetTypeInfo().IsEnum)
{
kind = TypeKind.Enum;
}
else if (type.GetTypeInfo().IsValueType)
{
kind = TypeKind.Struct;
if (IsOptionalValue(type))
{
baseType = type.GetGenericArguments()[0];
flags |= TypeFlags.OptionalValue;
}
else
{
baseType = type.GetTypeInfo().BaseType;
}
if (type.GetTypeInfo().IsAbstract) flags |= TypeFlags.Abstract;
}
else if (type.GetTypeInfo().IsClass)
{
if (type == typeof(XmlAttribute))
{
kind = TypeKind.Attribute;
flags |= TypeFlags.Special | TypeFlags.CanBeAttributeValue;
}
else if (typeof(XmlNode).IsAssignableFrom(type))
{
kind = TypeKind.Node;
baseType = type.GetTypeInfo().BaseType;
flags |= TypeFlags.Special | TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue;
if (typeof(XmlText).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeElementValue;
else if (typeof(XmlElement).IsAssignableFrom(type))
flags &= ~TypeFlags.CanBeTextValue;
else if (type.IsAssignableFrom(typeof(XmlAttribute)))
flags |= TypeFlags.CanBeAttributeValue;
}
else
{
kind = TypeKind.Class;
baseType = type.GetTypeInfo().BaseType;
if (type.GetTypeInfo().IsAbstract)
flags |= TypeFlags.Abstract;
}
}
else if (type.GetTypeInfo().IsInterface)
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
if (memberInfo == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterface, type.FullName));
}
else
{
exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName));
}
}
}
else
{
kind = TypeKind.Void;
flags |= TypeFlags.Unsupported;
if (exception == null)
{
exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, type.FullName));
}
}
// check to see if the type has public default constructor for classes
if (kind == TypeKind.Class && !type.GetTypeInfo().IsAbstract)
{
flags |= GetConstructorFlags(type, ref exception);
}
// check if a struct-like type is enumerable
if (kind == TypeKind.Struct || kind == TypeKind.Class)
{
if (typeof(IEnumerable).IsAssignableFrom(type))
{
arrayElementType = GetEnumeratorElementType(type, ref flags);
kind = TypeKind.Enumerable;
// GetEnumeratorElementType checks for the security attributes on the GetEnumerator(), Add() methods and Current property,
// we need to check the MoveNext() and ctor methods for the security attribues
flags |= GetConstructorFlags(type, ref exception);
}
}
typeDesc = new TypeDesc(type, CodeIdentifier.MakeValid(TypeName(type)), type.ToString(), kind, null, flags, null);
typeDesc.Exception = exception;
if (directReference && (typeDesc.IsClass || kind == TypeKind.Serializable))
typeDesc.CheckNeedConstructor();
if (typeDesc.IsUnsupported)
{
// return right away, do not check anything else
return typeDesc;
}
_typeDescs.Add(type, typeDesc);
if (arrayElementType != null)
{
TypeDesc td = GetTypeDesc(arrayElementType, memberInfo, true, false);
// explicitly disallow read-only elements, even if they are collections
if (directReference && (td.IsCollection || td.IsEnumerable) && !td.IsPrimitive)
{
td.CheckNeedConstructor();
}
typeDesc.ArrayElementTypeDesc = td;
}
if (baseType != null && baseType != typeof(object) && baseType != typeof(ValueType))
{
typeDesc.BaseTypeDesc = GetTypeDesc(baseType, memberInfo, false, false);
}
return typeDesc;
}
internal static bool IsOptionalValue(Type type)
{
if (type.GetTypeInfo().IsGenericType)
{
if (type.GetGenericTypeDefinition() == typeof(Nullable<>).GetGenericTypeDefinition())
return true;
}
return false;
}
/*
static string GetHash(string str) {
MD5 md5 = MD5.Create();
string hash = Convert.ToBase64String(md5.ComputeHash(Encoding.UTF8.GetBytes(str)), 0, 6).Replace("+", "_P").Replace("/", "_S");
return hash;
}
*/
internal static string TypeName(Type t)
{
if (t.IsArray)
{
return "ArrayOf" + TypeName(t.GetElementType());
}
else if (t.GetTypeInfo().IsGenericType)
{
StringBuilder typeName = new StringBuilder();
StringBuilder ns = new StringBuilder();
string name = t.Name;
int arity = name.IndexOf("`", StringComparison.Ordinal);
if (arity >= 0)
{
name = name.Substring(0, arity);
}
typeName.Append(name);
typeName.Append("Of");
Type[] arguments = t.GetGenericArguments();
for (int i = 0; i < arguments.Length; i++)
{
typeName.Append(TypeName(arguments[i]));
ns.Append(arguments[i].Namespace);
}
/*
if (ns.Length > 0) {
typeName.Append("_");
typeName.Append(GetHash(ns.ToString()));
}
*/
return typeName.ToString();
}
return t.Name;
}
internal static Type GetArrayElementType(Type type, string memberInfo)
{
if (type.IsArray)
return type.GetElementType();
else if (typeof(ICollection).IsAssignableFrom(type))
return GetCollectionElementType(type, memberInfo);
else if (typeof(IEnumerable).IsAssignableFrom(type))
{
TypeFlags flags = TypeFlags.None;
return GetEnumeratorElementType(type, ref flags);
}
else
return null;
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping)
{
if (mapping.BaseMapping == null)
return mapping.Members;
var list = new List<MemberMapping>();
GetAllMembers(mapping, list);
return list.ToArray();
}
internal static void GetAllMembers(StructMapping mapping, List<MemberMapping> list)
{
if (mapping.BaseMapping != null)
{
GetAllMembers(mapping.BaseMapping, list);
}
for (int i = 0; i < mapping.Members.Length; i++)
{
list.Add(mapping.Members[i]);
}
}
internal static MemberMapping[] GetAllMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetAllMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
internal static MemberMapping[] GetSettableMembers(StructMapping structMapping)
{
var list = new List<MemberMapping>();
GetSettableMembers(structMapping, list);
return list.ToArray();
}
private static void GetSettableMembers(StructMapping mapping, List<MemberMapping> list)
{
if (mapping.BaseMapping != null)
{
GetSettableMembers(mapping.BaseMapping, list);
}
if (mapping.Members != null)
{
foreach (MemberMapping memberMapping in mapping.Members)
{
MemberInfo memberInfo = memberMapping.MemberInfo;
PropertyInfo propertyInfo = memberInfo as PropertyInfo;
if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc))
{
throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name));
}
list.Add(memberMapping);
}
}
}
private static bool CanWriteProperty(PropertyInfo propertyInfo, TypeDesc typeDesc)
{
// If the property is a collection, we don't need a setter.
if (typeDesc.Kind == TypeKind.Collection || typeDesc.Kind == TypeKind.Enumerable)
{
return true;
}
// Else the property needs a public setter.
return propertyInfo.SetMethod != null && propertyInfo.SetMethod.IsPublic;
}
internal static MemberMapping[] GetSettableMembers(StructMapping mapping, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
MemberMapping[] mappings = GetSettableMembers(mapping);
PopulateMemberInfos(mapping, mappings, memberInfos);
return mappings;
}
private static void PopulateMemberInfos(StructMapping structMapping, MemberMapping[] memberMappings, System.Collections.Generic.Dictionary<string, MemberInfo> memberInfos)
{
memberInfos.Clear();
for (int i = 0; i < memberMappings.Length; ++i)
{
memberInfos[memberMappings[i].Name] = memberMappings[i].MemberInfo;
if (memberMappings[i].ChoiceIdentifier != null)
memberInfos[memberMappings[i].ChoiceIdentifier.MemberName] = memberMappings[i].ChoiceIdentifier.MemberInfo;
if (memberMappings[i].CheckSpecifiedMemberInfo != null)
memberInfos[memberMappings[i].Name + "Specified"] = memberMappings[i].CheckSpecifiedMemberInfo;
}
// The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B.
// There's one virtual property defined in A and overrided by B. Without the replacing logic below, the code generated will always
// try to access the property defined in A, rather than B.
// The logic here is to:
// 1) Check current members inside memberInfos dictionary and figure out whether there's any override or new properties defined in the derived class.
// If so, replace the one on the base class with the one on the derived class.
// 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced
// by the StructMapping of the baseclass, so updating it directly could lead to other issues.
Dictionary<string, MemberInfo> replaceList = null;
MemberInfo replacedInfo = null;
foreach (KeyValuePair<string, MemberInfo> pair in memberInfos)
{
if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo))
{
if (replaceList == null)
{
replaceList = new Dictionary<string, MemberInfo>();
}
replaceList.Add(pair.Key, replacedInfo);
}
}
if (replaceList != null)
{
foreach (KeyValuePair<string, MemberInfo> pair in replaceList)
{
memberInfos[pair.Key] = pair.Value;
}
for (int i = 0; i < memberMappings.Length; i++)
{
MemberInfo mi;
if (replaceList.TryGetValue(memberMappings[i].Name, out mi))
{
MemberMapping newMapping = memberMappings[i].Clone();
newMapping.MemberInfo = mi;
memberMappings[i] = newMapping;
}
}
}
}
private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type derivedType, out MemberInfo replacedInfo)
{
replacedInfo = memberInfoToBeReplaced;
Type currentType = derivedType;
Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType;
if (typeToBeReplaced.IsAssignableFrom(currentType))
{
while (currentType != typeToBeReplaced)
{
TypeInfo currentInfo = currentType.GetTypeInfo();
foreach (PropertyInfo info in currentInfo.DeclaredProperties)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: property names are the same but the declaring types are different
replacedInfo = info;
break;
}
}
foreach (FieldInfo info in currentInfo.DeclaredFields)
{
if (info.Name == memberInfoToBeReplaced.Name)
{
// we have a new modifier situation: field names are the same but the declaring types are different
replacedInfo = info;
break;
}
}
// we go one level down and try again
currentType = currentType.GetTypeInfo().BaseType;
}
}
return replacedInfo != memberInfoToBeReplaced;
}
private static TypeFlags GetConstructorFlags(Type type, ref Exception exception)
{
ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
if (ctor != null)
{
TypeFlags flags = TypeFlags.HasDefaultConstructor;
if (!ctor.IsPublic)
flags |= TypeFlags.CtorInaccessible;
else
{
object[] attrs = ctor.GetCustomAttributes(typeof(ObsoleteAttribute), false).ToArray();
if (attrs != null && attrs.Length > 0)
{
ObsoleteAttribute obsolete = (ObsoleteAttribute)attrs[0];
if (obsolete.IsError)
{
flags |= TypeFlags.CtorInaccessible;
}
}
}
return flags;
}
return 0;
}
private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags)
{
if (typeof(IEnumerable).IsAssignableFrom(type))
{
MethodInfo enumerator = type.GetMethod("GetEnumerator", Array.Empty<Type>());
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// try generic implementation
enumerator = null;
foreach (MemberInfo member in type.GetMember("System.Collections.Generic.IEnumerable<*", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic))
{
enumerator = member as MethodInfo;
if (enumerator != null && typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
// use the first one we find
flags |= TypeFlags.GenericInterface;
break;
}
else
{
enumerator = null;
}
}
if (enumerator == null)
{
// and finally private interface implementation
flags |= TypeFlags.UsePrivateImplementation;
enumerator = type.GetMethod("System.Collections.IEnumerable.GetEnumerator", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty<Type>());
}
}
if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType))
{
return null;
}
XmlAttributes methodAttrs = new XmlAttributes(enumerator);
if (methodAttrs.XmlIgnore) return null;
PropertyInfo p = enumerator.ReturnType.GetProperty("Current");
Type currentType = (p == null ? typeof(object) : p.PropertyType);
MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType });
if (addMethod == null && currentType != typeof(object))
{
currentType = typeof(object);
addMethod = type.GetMethod("Add", new Type[] { currentType });
}
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, currentType, "IEnumerable"));
}
return currentType;
}
else
{
return null;
}
}
internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo)
{
if (typeof(IDictionary).IsAssignableFrom(type))
{
if (memberInfo == null)
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionary, type.FullName));
}
else
{
throw new NotSupportedException(SR.Format(SR.XmlUnsupportedIDictionaryDetails, memberInfo, type.FullName));
}
}
MemberInfo[] defaultMembers = type.GetDefaultMembers();
PropertyInfo indexer = null;
if (defaultMembers != null && defaultMembers.Length > 0)
{
for (Type t = type; t != null; t = t.GetTypeInfo().BaseType)
{
for (int i = 0; i < defaultMembers.Length; i++)
{
if (defaultMembers[i] is PropertyInfo)
{
PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i];
if (defaultProp.DeclaringType != t) continue;
if (!defaultProp.CanRead) continue;
MethodInfo getMethod = defaultProp.GetMethod;
ParameterInfo[] parameters = getMethod.GetParameters();
if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int))
{
indexer = defaultProp;
break;
}
}
}
if (indexer != null) break;
}
}
if (indexer == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName));
}
MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType });
if (addMethod == null)
{
throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection"));
}
return indexer;
}
private static Type GetCollectionElementType(Type type, string memberInfo)
{
return GetDefaultIndexer(type, memberInfo).PropertyType;
}
static internal XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent)
{
string ns;
string name;
int nsLen = type.LastIndexOf(':');
if (nsLen <= 0)
{
ns = "";
}
else
{
ns = type.Substring(0, nsLen);
}
int nameLen = type.IndexOf('[', nsLen + 1);
if (nameLen <= nsLen)
{
throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayTypeSyntax, type));
}
name = type.Substring(nsLen + 1, nameLen - nsLen - 1);
dims = type.Substring(nameLen);
return new XmlQualifiedName(name, ns);
}
internal ICollection Types
{
get { return _typeDescs.Keys; }
}
internal void AddTypeMapping(TypeMapping typeMapping)
{
_typeMappings.Add(typeMapping);
}
internal ICollection TypeMappings
{
get { return _typeMappings; }
}
internal static Dictionary<Type, TypeDesc> PrimtiveTypes { get { return s_primitiveTypes; } }
}
internal class Soap
{
private Soap() { }
internal const string Encoding = "http://schemas.xmlsoap.org/soap/encoding/";
internal const string UrType = "anyType";
internal const string Array = "Array";
internal const string ArrayType = "arrayType";
}
internal class Soap12
{
private Soap12() { }
internal const string Encoding = "http://www.w3.org/2003/05/soap-encoding";
internal const string RpcNamespace = "http://www.w3.org/2003/05/soap-rpc";
internal const string RpcResult = "result";
}
internal class Wsdl
{
private Wsdl() { }
internal const string Namespace = "http://schemas.xmlsoap.org/wsdl/";
internal const string ArrayType = "arrayType";
}
internal class UrtTypes
{
private UrtTypes() { }
internal const string Namespace = "http://microsoft.com/wsdl/types/";
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// InvitesGame.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Net;
#endregion
namespace Invites
{
/// <summary>
/// Sample showing how to add invite support to a networked XNA Framework
/// game. This builds on the Peer-to-Peer sample, extending it by adding
/// an event handler which will respond to invite notifications.
/// </summary>
public class InvitesGame : Microsoft.Xna.Framework.Game
{
#region Fields
const int screenWidth = 1067;
const int screenHeight = 600;
const int maxGamers = 16;
const int maxLocalGamers = 4;
GraphicsDeviceManager graphics;
SpriteBatch spriteBatch;
SpriteFont font;
KeyboardState currentKeyboardState;
GamePadState currentGamePadState;
NetworkSession networkSession;
PacketWriter packetWriter = new PacketWriter();
PacketReader packetReader = new PacketReader();
string errorMessage;
#endregion
#region Initialization
public InvitesGame()
{
graphics = new GraphicsDeviceManager(this);
graphics.PreferredBackBufferWidth = screenWidth;
graphics.PreferredBackBufferHeight = screenHeight;
Content.RootDirectory = "Content";
Components.Add(new GamerServicesComponent(this));
// Listen for invite notification events. This handler will be called
// whenever the user accepts an invite message, or if they select the
// "Join Session In Progress" option from their Guide friends screen.
NetworkSession.InviteAccepted += InviteAcceptedEventHandler;
}
/// <summary>
/// Load your content.
/// </summary>
protected override void LoadContent()
{
spriteBatch = new SpriteBatch(GraphicsDevice);
font = Content.Load<SpriteFont>("Font");
}
#endregion
#region Update
/// <summary>
/// Allows the game to run logic.
/// </summary>
protected override void Update(GameTime gameTime)
{
HandleInput();
if (networkSession == null)
{
// If we are not in a network session, update the
// menu screen that will let us create or join one.
UpdateMenuScreen();
}
else
{
// If we are in a network session, update it.
UpdateNetworkSession();
}
base.Update(gameTime);
}
/// <summary>
/// Menu screen provides options to create or join network sessions.
/// </summary>
void UpdateMenuScreen()
{
if (IsActive)
{
if (Gamer.SignedInGamers.Count == 0)
{
// If there are no profiles signed in, we cannot proceed.
// Show the Guide so the user can sign in.
Guide.ShowSignIn(maxLocalGamers, false);
}
else if (IsPressed(Keys.A, Buttons.A))
{
// Create a new session?
CreateSession();
}
else if (IsPressed(Keys.B, Buttons.B))
{
// Join an existing session?
JoinSession();
}
}
}
/// <summary>
/// Starts hosting a new network session.
/// </summary>
void CreateSession()
{
DrawMessage("Creating session...");
try
{
networkSession = NetworkSession.Create(NetworkSessionType.PlayerMatch,
maxLocalGamers, maxGamers);
HookSessionEvents();
}
catch (Exception error)
{
errorMessage = error.Message;
}
}
/// <summary>
/// Joins an existing network session.
/// </summary>
void JoinSession()
{
DrawMessage("Joining session...");
try
{
// Search for sessions.
using (AvailableNetworkSessionCollection availableSessions =
NetworkSession.Find(NetworkSessionType.PlayerMatch,
maxLocalGamers, null))
{
if (availableSessions.Count == 0)
{
errorMessage = "No network sessions found.";
return;
}
// Join the first session we found.
networkSession = NetworkSession.Join(availableSessions[0]);
HookSessionEvents();
}
}
catch (Exception error)
{
errorMessage = error.Message;
}
}
/// <summary>
/// This event handler will be called whenever the game recieves an invite
/// notification. This can occur when the user accepts an invite that was
/// sent to them by a friend (pull mode), or if they choose the "Join
/// Session In Progress" option in their friends screen (push mode).
/// The handler should leave the current session (if any), then join the
/// session referred to by the invite. It is not necessary to prompt the
/// user before doing this, as the Guide will already have taken care of
/// the necessary confirmations before the invite was delivered to you.
/// </summary>
void InviteAcceptedEventHandler(object sender, InviteAcceptedEventArgs e)
{
DrawMessage("Joining session from invite...");
// Leave the current network session.
if (networkSession != null)
{
networkSession.Dispose();
networkSession = null;
}
try
{
// Join a new session in response to the invite.
networkSession = NetworkSession.JoinInvited(maxLocalGamers);
HookSessionEvents();
}
catch (Exception error)
{
errorMessage = error.Message;
}
}
/// <summary>
/// After creating or joining a network session, we must subscribe to
/// some events so we will be notified when the session changes state.
/// </summary>
void HookSessionEvents()
{
networkSession.GamerJoined += GamerJoinedEventHandler;
networkSession.SessionEnded += SessionEndedEventHandler;
}
/// <summary>
/// This event handler will be called whenever a new gamer joins the session.
/// We use it to allocate a Tank object, and associate it with the new gamer.
/// </summary>
void GamerJoinedEventHandler(object sender, GamerJoinedEventArgs e)
{
int gamerIndex = networkSession.AllGamers.IndexOf(e.Gamer);
e.Gamer.Tag = new Tank(gamerIndex, Content, screenWidth, screenHeight);
}
/// <summary>
/// Event handler notifies us when the network session has ended.
/// </summary>
void SessionEndedEventHandler(object sender, NetworkSessionEndedEventArgs e)
{
errorMessage = e.EndReason.ToString();
networkSession.Dispose();
networkSession = null;
}
/// <summary>
/// Updates the state of the network session, moving the tanks
/// around and synchronizing their state over the network.
/// </summary>
void UpdateNetworkSession()
{
// Update our locally controlled tanks, and send their
// latest position data to everyone in the session.
foreach (LocalNetworkGamer gamer in networkSession.LocalGamers)
{
UpdateLocalGamer(gamer);
}
// Pump the underlying session object.
networkSession.Update();
// Make sure the session has not ended.
if (networkSession == null)
return;
// Read any packets telling us the positions of remotely controlled tanks.
foreach (LocalNetworkGamer gamer in networkSession.LocalGamers)
{
ReadIncomingPackets(gamer);
}
}
/// <summary>
/// Helper for updating a locally controlled gamer.
/// </summary>
void UpdateLocalGamer(LocalNetworkGamer gamer)
{
// Look up what tank is associated with this local player.
Tank localTank = gamer.Tag as Tank;
// Update the tank.
ReadTankInputs(localTank, gamer.SignedInGamer.PlayerIndex);
localTank.Update();
// Write the tank state into a network packet.
packetWriter.Write(localTank.Position);
packetWriter.Write(localTank.TankRotation);
packetWriter.Write(localTank.TurretRotation);
// Send the data to everyone in the session.
gamer.SendData(packetWriter, SendDataOptions.InOrder);
}
/// <summary>
/// Helper for reading incoming network packets.
/// </summary>
void ReadIncomingPackets(LocalNetworkGamer gamer)
{
// Keep reading as long as incoming packets are available.
while (gamer.IsDataAvailable)
{
NetworkGamer sender;
// Read a single packet from the network.
gamer.ReceiveData(packetReader, out sender);
// Discard packets sent by local gamers: we already know their state!
if (sender.IsLocal)
continue;
// Look up the tank associated with whoever sent this packet.
Tank remoteTank = sender.Tag as Tank;
// Read the state of this tank from the network packet.
remoteTank.Position = packetReader.ReadVector2();
remoteTank.TankRotation = packetReader.ReadSingle();
remoteTank.TurretRotation = packetReader.ReadSingle();
}
}
#endregion
#region Draw
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.CornflowerBlue);
if (networkSession == null)
{
// If we are not in a network session, draw the
// menu screen that will let us create or join one.
DrawMenuScreen();
}
else
{
// If we are in a network session, draw it.
DrawNetworkSession();
}
base.Draw(gameTime);
}
/// <summary>
/// Draws the startup screen used to create and join network sessions.
/// </summary>
void DrawMenuScreen()
{
string message = string.Empty;
if (!string.IsNullOrEmpty(errorMessage))
message += "Error:\n" + errorMessage.Replace(". ", ".\n") + "\n\n";
message += "A = create session\n" +
"B = join session";
spriteBatch.Begin();
spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black);
spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White);
spriteBatch.End();
}
/// <summary>
/// Draws the state of an active network session.
/// </summary>
void DrawNetworkSession()
{
spriteBatch.Begin();
// For each person in the session...
foreach (NetworkGamer gamer in networkSession.AllGamers)
{
// Look up the tank object belonging to this network gamer.
Tank tank = gamer.Tag as Tank;
// Draw the tank.
tank.Draw(spriteBatch);
// Draw a gamertag label.
string label = gamer.Gamertag;
Color labelColor = Color.Black;
Vector2 labelOffset = new Vector2(100, 150);
if (gamer.IsHost)
label += " (host)";
// Flash the gamertag to yellow when the player is talking.
if (gamer.IsTalking)
labelColor = Color.Yellow;
spriteBatch.DrawString(font, label, tank.Position, labelColor, 0,
labelOffset, 0.6f, SpriteEffects.None, 0);
}
spriteBatch.End();
}
/// <summary>
/// Helper draws notification messages before calling blocking network methods.
/// </summary>
void DrawMessage(string message)
{
if (!BeginDraw())
return;
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.DrawString(font, message, new Vector2(161, 161), Color.Black);
spriteBatch.DrawString(font, message, new Vector2(160, 160), Color.White);
spriteBatch.End();
EndDraw();
}
#endregion
#region Handle Input
/// <summary>
/// Handles input.
/// </summary>
private void HandleInput()
{
currentKeyboardState = Keyboard.GetState();
currentGamePadState = GamePad.GetState(PlayerIndex.One);
// Check for exit.
if (IsActive && IsPressed(Keys.Escape, Buttons.Back))
{
Exit();
}
}
/// <summary>
/// Checks if the specified button is pressed on either keyboard or gamepad.
/// </summary>
bool IsPressed(Keys key, Buttons button)
{
return (currentKeyboardState.IsKeyDown(key) ||
currentGamePadState.IsButtonDown(button));
}
/// <summary>
/// Reads input data from keyboard and gamepad, and stores
/// it into the specified tank object.
/// </summary>
void ReadTankInputs(Tank tank, PlayerIndex playerIndex)
{
// Read the gamepad.
GamePadState gamePad = GamePad.GetState(playerIndex);
Vector2 tankInput = gamePad.ThumbSticks.Left;
Vector2 turretInput = gamePad.ThumbSticks.Right;
// Read the keyboard.
KeyboardState keyboard = Keyboard.GetState(playerIndex);
if (keyboard.IsKeyDown(Keys.Left))
tankInput.X = -1;
else if (keyboard.IsKeyDown(Keys.Right))
tankInput.X = 1;
if (keyboard.IsKeyDown(Keys.Up))
tankInput.Y = 1;
else if (keyboard.IsKeyDown(Keys.Down))
tankInput.Y = -1;
if (keyboard.IsKeyDown(Keys.A))
turretInput.X = -1;
else if (keyboard.IsKeyDown(Keys.D))
turretInput.X = 1;
if (keyboard.IsKeyDown(Keys.W))
turretInput.Y = 1;
else if (keyboard.IsKeyDown(Keys.S))
turretInput.Y = -1;
// Normalize the input vectors.
if (tankInput.Length() > 1)
tankInput.Normalize();
if (turretInput.Length() > 1)
turretInput.Normalize();
// Store these input values into the tank object.
tank.TankInput = tankInput;
tank.TurretInput = turretInput;
}
#endregion
}
#region Entry Point
/// <summary>
/// The main entry point for the application.
/// </summary>
static class Program
{
static void Main()
{
using (InvitesGame game = new InvitesGame())
{
game.Run();
}
}
}
#endregion
}
| |
#region Header
// Revit API .NET Labs
//
// Copyright (C) 2007-2021 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software
// for any purpose and without fee is hereby granted, provided
// that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
// History:
//
// 2008-06-03 jeremy implemented copy to clipboard
#endregion // Header
//#define CHECK_FOR_FAMILY_INSTANCE
#define CHECK_GET_TYPE_ID
#region Namespaces
using System;
using System.Diagnostics;
using WinForms = System.Windows.Forms;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.DB.Architecture;
using Autodesk.Revit.UI;
#endregion // Namespaces
namespace XtraCs
{
/// <summary>
/// List all accessible parameters on a selected element in a DataGridView.
/// </summary>
[Transaction( TransactionMode.ReadOnly )]
public class BuiltInParamsChecker : IExternalCommand
{
/// <summary>
/// A class used to manage the data of an element parameter.
/// </summary>
public class ParameterData
{
BuiltInParameter _enum;
Parameter _parameter;
string _valueString; // value string or element description in case of an element id
public ParameterData(
BuiltInParameter bip,
Parameter parameter,
string valueStringOrElementDescription )
{
_enum = bip;
_parameter = parameter;
_valueString = valueStringOrElementDescription;
}
public string Enum
{
get { return _enum.ToString(); }
}
public string Name
{
get { return _parameter.Definition.Name; }
}
public string Type
{
get
{
ParameterType pt = _parameter.Definition.ParameterType; // returns 'Invalid' for 'ElementId'
string s = ParameterType.Invalid == pt ? "" : "/" + pt.ToString();
return _parameter.StorageType.ToString() + s;
}
}
public string ReadWrite
{
get { return _parameter.IsReadOnly ? "read-only" : "read-write"; }
}
public string ValueString
{
//get { return _parameter.AsValueString(); }
get { return _valueString; }
}
public string Value
{
get
{
//return _value;
string s;
switch( _parameter.StorageType )
{
// database value, internal units, e.g. feet:
case StorageType.Double: s = LabUtils.RealString( _parameter.AsDouble() ); break;
case StorageType.Integer: s = _parameter.AsInteger().ToString(); break;
case StorageType.String: s = _parameter.AsString(); break;
case StorageType.ElementId: s = _parameter.AsElementId().IntegerValue.ToString(); break;
case StorageType.None: s = "None"; break;
default: Debug.Assert( false, "unexpected storage type" ); s = string.Empty; break;
}
return s;
}
}
//public string RowString
//{
// get
// {
// return Enum + "\t" + Name + "\t" + ReadWrite + "\t" + ValueString + "\t" + Value;
// }
//}
}
/// <summary>
/// Revit external command to list all valid built-in parameters for a given selected element.
/// </summary>
public Result Execute(
ExternalCommandData commandData,
ref string message,
ElementSet elements )
{
UIDocument uidoc = commandData.Application.ActiveUIDocument;
Document doc = uidoc.Document;
Element e
= LabUtils.GetSingleSelectedElementOrPrompt(
uidoc );
if( null == e )
{
return Result.Cancelled;
}
bool isSymbol = false;
#region Check for FamilyInstance
#if CHECK_FOR_FAMILY_INSTANCE
//
// for a family instance, ask user whether to
// display instance or type parameters;
// in a similar manner, we could add dedicated
// switches for Wall --> WallType,
// Floor --> FloorType etc. ...
//
if( e is FamilyInstance )
{
FamilyInstance inst = e as FamilyInstance;
if( null != inst.Symbol )
{
string symbol_name
= LabUtils.ElementDescription(
inst.Symbol, true );
string family_name
= LabUtils.ElementDescription(
inst.Symbol.Family, true );
string msg =
"This element is a family instance, so it "
+ "has both type and instance parameters. "
+ "By default, the instance parameters are "
+ "displayed. If you select 'No', the type "
+ "parameters will be displayed instead. "
+ "Would you like to see the instance "
+ "parameters?";
if( !LabUtils.QuestionMsg( msg ) )
{
e = inst.Symbol;
isSymbol = true;
}
}
}
#endif // CHECK_FOR_FAMILY_INSTANCE
#endregion // Check for FamilyInstance
#region Check for element type
#if CHECK_GET_TYPE_ID
ElementId idType = e.GetTypeId();
if( ElementId.InvalidElementId != idType )
{
// The selected element has a type; ask user
// whether to display instance or type
// parameters.
ElementType typ = doc.GetElement( idType )
as ElementType;
Debug.Assert( null != typ,
"expected to retrieve a valid element type" );
string type_name = LabUtils.ElementDescription(
typ, true );
string msg =
"This element has an ElementType, so it has "
+ "both type and instance parameters. By "
+ "default, the instance parameters are "
+ "displayed. If you select 'No', the type "
+ "parameters will be displayed instead. "
+ "Would you like to see the instance "
+ "parameters?";
if( !LabUtils.QuestionMsg( msg ) )
{
e = typ;
isSymbol = true;
}
}
#endif // CHECK_GET_TYPE_ID
#endregion // Check for element type
SortableBindingList<ParameterData> data = new SortableBindingList<ParameterData>();
{
WaitCursor waitCursor = new WaitCursor();
Array bips = Enum.GetValues( typeof( BuiltInParameter ) );
int n = bips.Length;
Parameter p;
foreach( BuiltInParameter a in bips )
{
try
{
p = e.get_Parameter( a );
#region Check for external definition
#if CHECK_FOR_EXTERNAL_DEFINITION
Definition d = p.Definition;
ExternalDefinition e = d as ExternalDefinition; // this is never possible
string guid = ( null == e ) ? null : e.GUID.ToString();
#endif // CHECK_FOR_EXTERNAL_DEFINITION
#endregion // Check for external definition
if( null != p )
{
//string value = LabUtils.GetParameterValue2( p, doc );
string valueString = ( StorageType.ElementId == p.StorageType )
? LabUtils.GetParameterValue2( p, doc )
: p.AsValueString();
data.Add( new ParameterData( a, p, valueString ) );
}
}
catch( Exception ex )
{
Debug.Print( "Exception retrieving built-in parameter {0}: {1}",
a, ex );
}
}
}
string description = LabUtils.ElementDescription( e, true )
+ ( isSymbol
? " Type"
: " Instance" );
using( BuiltInParamsCheckerForm form = new BuiltInParamsCheckerForm( description, data ) )
{
form.ShowDialog();
}
return Result.Succeeded;
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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.
*
*/
#endregion
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using Common.Logging;
namespace Quartz.Job
{
/// <summary>
/// Built in job for executing native executables in a separate process.
/// </summary>
/// <remarks>
/// <example>
/// JobDetail job = new JobDetail("dumbJob", null, typeof(Quartz.Jobs.NativeJob));
/// job.JobDataMap.Put(Quartz.Jobs.NativeJob.PropertyCommand, "echo \"hi\" >> foobar.txt");
/// Trigger trigger = TriggerUtils.MakeSecondlyTrigger(5);
/// trigger.Name = "dumbTrigger";
/// sched.ScheduleJob(job, trigger);
/// </example>
/// If PropertyWaitForProcess is true, then the integer exit value of the process
/// will be saved as the job execution result in the JobExecutionContext.
/// </remarks>
/// <author>Matthew Payne</author>
/// <author>James House</author>
/// <author>Steinar Overbeck Cook</author>
/// <author>Marko Lahma (.NET)</author>
public class NativeJob : IJob
{
private readonly ILog log;
/// <summary>
/// Required parameter that specifies the name of the command (executable)
/// to be ran.
/// </summary>
public const string PropertyCommand = "command";
/// <summary>
/// Optional parameter that specifies the parameters to be passed to the
/// executed command.
/// </summary>
public const string PropertyParameters = "parameters";
/// <summary>
/// Optional parameter (value should be 'true' or 'false') that specifies
/// whether the job should wait for the execution of the native process to
/// complete before it completes.
///
/// <para>Defaults to <see langword="true" />.</para>
/// </summary>
public const string PropertyWaitForProcess = "waitForProcess";
/// <summary>
/// Optional parameter (value should be 'true' or 'false') that specifies
/// whether the spawned process's stdout and stderr streams should be
/// consumed. If the process creates output, it is possible that it might
/// 'hang' if the streams are not consumed.
///
/// <para>Defaults to <see langword="false" />.</para>
/// </summary>
public const string PropertyConsumeStreams = "consumeStreams";
/// <summary>
/// Optional parameter that specifies the workling directory to be used by
/// the executed command.
/// </summary>
public const string PropertyWorkingDirectory = "workingDirectory";
private const string StreamTypeStandardOutput = "stdout";
private const string StreamTypeError = "stderr";
/// <summary>
/// Gets the log.
/// </summary>
/// <value>The log.</value>
protected ILog Log
{
get { return log; }
}
/// <summary>
/// Initializes a new instance of the <see cref="NativeJob"/> class.
/// </summary>
public NativeJob()
{
log = LogManager.GetLogger(typeof(NativeJob));
}
/// <summary>
/// Called by the <see cref="IScheduler" /> when a <see cref="ITrigger" />
/// fires that is associated with the <see cref="IJob" />.
/// <para>
/// The implementation may wish to set a result object on the
/// JobExecutionContext before this method exits. The result itself
/// is meaningless to Quartz, but may be informative to
/// <see cref="IJobListener" />s or
/// <see cref="ITriggerListener" />s that are watching the job's
/// execution.
/// </para>
/// </summary>
/// <param name="context"></param>
public virtual void Execute(IJobExecutionContext context)
{
JobDataMap data = context.MergedJobDataMap;
string command = data.GetString(PropertyCommand);
string parameters = data.GetString(PropertyParameters) ?? "";
bool wait = true;
if (data.ContainsKey(PropertyWaitForProcess))
{
wait = data.GetBooleanValue(PropertyWaitForProcess);
}
bool consumeStreams = false;
if (data.ContainsKey(PropertyConsumeStreams))
{
consumeStreams = data.GetBooleanValue(PropertyConsumeStreams);
}
string workingDirectory = data.GetString(PropertyWorkingDirectory);
int exitCode = RunNativeCommand(command, parameters, workingDirectory, wait, consumeStreams);
context.Result = exitCode;
}
private int RunNativeCommand(string command, string parameters, string workingDirectory, bool wait, bool consumeStreams)
{
string[] cmd;
string[] args = new string[2];
args[0] = command;
args[1] = parameters;
int result = -1;
try
{
//with this variable will be done the swithcing
string osName = Environment.GetEnvironmentVariable("OS");
if (osName == null)
{
throw new JobExecutionException("Could not read environment variable for OS");
}
if (osName.ToLower().IndexOf("windows") > -1)
{
cmd = new string[args.Length + 2];
cmd[0] = "cmd.exe";
cmd[1] = "/C";
for (int i = 0; i < args.Length; i++)
{
cmd[i + 2] = args[i];
}
}
else if (osName.ToLower().IndexOf("linux") > -1)
{
cmd = new String[3];
cmd[0] = "/bin/sh";
cmd[1] = "-c";
cmd[2] = args[0] + " " + args[1];
}
else
{
// try this...
cmd = args;
}
// Executes the command
string temp = "";
for (int i = 1; i < cmd.Length; i++)
{
temp += cmd[i] + " ";
}
temp = temp.Trim();
Log.Info(string.Format(CultureInfo.InvariantCulture, "About to run {0} {1}...", cmd[0], temp));
Process proc = new Process();
proc.StartInfo.FileName = cmd[0];
proc.StartInfo.Arguments = temp;
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.RedirectStandardOutput = true;
if (!String.IsNullOrEmpty(workingDirectory))
{
proc.StartInfo.WorkingDirectory = workingDirectory;
}
proc.Start();
// Consumes the stdout from the process
StreamConsumer stdoutConsumer = new StreamConsumer(this, proc.StandardOutput.BaseStream, StreamTypeStandardOutput);
// Consumes the stderr from the process
if (consumeStreams)
{
StreamConsumer stderrConsumer = new StreamConsumer(this, proc.StandardError.BaseStream, StreamTypeError);
stdoutConsumer.Start();
stderrConsumer.Start();
}
if (wait)
{
proc.WaitForExit();
result = proc.ExitCode;
}
// any error message?
}
catch (Exception x)
{
throw new JobExecutionException("Error launching native command: " + x.Message, x, false);
}
return result;
}
/// <summary>
/// Consumes data from the given input stream until EOF and prints the data to stdout
/// </summary>
/// <author>cooste</author>
/// <author>James House</author>
private class StreamConsumer : QuartzThread
{
private readonly NativeJob enclosingInstance;
private readonly Stream inputStream;
private readonly string type;
/// <summary>
/// Initializes a new instance of the <see cref="StreamConsumer"/> class.
/// </summary>
/// <param name="enclosingInstance">The enclosing instance.</param>
/// <param name="inputStream">The input stream.</param>
/// <param name="type">The type.</param>
public StreamConsumer(NativeJob enclosingInstance, Stream inputStream, string type)
{
this.enclosingInstance = enclosingInstance;
this.inputStream = inputStream;
this.type = type;
}
/// <summary>
/// Runs this object as a separate thread, printing the contents of the input stream
/// supplied during instantiation, to either Console. or stderr
/// </summary>
public override void Run()
{
try
{
using (StreamReader br = new StreamReader(inputStream))
{
string line;
while ((line = br.ReadLine()) != null)
{
if (type == StreamTypeError)
{
enclosingInstance.Log.Warn(string.Format(CultureInfo.InvariantCulture, "{0}>{1}", type, line));
}
else
{
enclosingInstance.Log.Info(string.Format(CultureInfo.InvariantCulture, "{0}>{1}", type, line));
}
}
}
}
catch (IOException ioe)
{
enclosingInstance.Log.Error(string.Format(CultureInfo.InvariantCulture, "Error consuming {0} stream of spawned process.", type), ioe);
}
}
}
}
}
| |
// 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.Globalization;
using System.Runtime.CompilerServices;
/// <summary>
/// Convert.ToString(System.Byte,System.Int32)
/// </summary>
public class ConvertToString4
{
const int flags =0x40;
const int width = -1;
const char paddingChar = ' ';
public static int Main()
{
ConvertToString4 testObj = new ConvertToString4();
TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToString(System.Byte,System.Int32)");
if (testObj.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;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
bool retVal = true;
string c_TEST_DESC = "PosTest1: Verify value is 15 and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P001";
Byte byteValue = 15;
int radix ;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "1111";
radix = 2;
String resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "17";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "15";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "f";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("005", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
string c_TEST_DESC = "PosTest2: Verify value is Byte.MaxValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P002";
Byte byteValue = Byte.MaxValue;
int radix;
String actualValue;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
actualValue = "11111111";
radix = 2;
String resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 8;
actualValue = "377";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 10;
actualValue = "255";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
radix = 16;
actualValue = "ff";
errorDesc = "";
resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("010", "unexpected exception occurs :" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
string c_TEST_DESC = "PosTest3: Verify value is Byte.MinValue and radix is 2,8,10 or 16... ";
string c_TEST_ID = "P003";
Byte byteValue = Byte.MinValue;
int[] radices ={ 2, 8, 10, 16 };
String actualValue ="0";
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
foreach (int radix in radices)
{
String resValue = Convert.ToString(byteValue, radix);
if (actualValue != resValue)
{
string errorDesc = "value is not " + resValue.ToString() + " as expected: Actual is " + actualValue.ToString();
errorDesc += DataString(byteValue, radix);
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("012", "unexpected exception occurs :" + e );
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTesting
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_DESC = "NegTest1: the radix is 32...";
const string c_TEST_ID = "N001";
Byte byteValue = TestLibrary.Generator.GetByte(-55);
int radix =32;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
Convert.ToString(byteValue, radix);
TestLibrary.TestFramework.LogError("013" + " TestId-" + c_TEST_ID, "ArgumentException is not thrown as expected ." + DataString(byteValue,radix));
retVal = false;
}
catch (ArgumentException)
{
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("014" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + DataString(byteValue, radix));
retVal = false;
}
return retVal;
}
#endregion
#region Help Methods
private string DataString(Byte byteValue, int radix)
{
string str;
str = string.Format("\n[byteValue value]\n \"{0}\"", byteValue);
str += string.Format("\n[radix value ]\n {0}", radix);
return str;
}
#endregion
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using MongoDB.Util;
namespace MongoDB
{
/// <summary>
/// Description of Document.
/// </summary>
[Serializable]
public class Document : IDictionary<string,object>, IDictionary, IXmlSerializable
{
private readonly List<string> _orderedKeys;
private readonly Dictionary<string,object > _dictionary;
private readonly IComparer<string> _keyComparer;
/// <summary>
/// Initializes a new instance of the <see cref="Document"/> class.
/// </summary>
public Document(){
_dictionary = new Dictionary<string, object>();
_orderedKeys = new List<String>();
}
/// <summary>
/// Initialize a new instance of the <see cref="Document"/> class with an optional key sorter.
/// </summary>
public Document(IComparer<string> keyComparer)
:this()
{
if(keyComparer == null)
throw new ArgumentNullException("keyComparer");
_keyComparer = keyComparer;
}
/// <summary>
/// Initializes a new instance of the <see cref="Document"/> class and
/// add's the given values to it.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
public Document(string key,object value)
: this()
{
Add(key, value);
}
/// <summary>
/// Initializes a new instance of the <see cref="Document"/> class.
/// </summary>
/// <param name="dictionary">The dictionary.</param>
public Document(IEnumerable<KeyValuePair<string, object>> dictionary)
:this()
{
if(dictionary == null)
throw new ArgumentNullException("dictionary");
foreach(var entry in dictionary)
Add(entry.Key, entry.Value);
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
public object this[string key]{
get { return Get(key); }
set { Set(key, value); }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return _dictionary.Keys; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return _dictionary.Values; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<object> Values{
get { return _dictionary.Values; }
}
/// <summary>
/// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
public ICollection<string> Keys{
get { return _orderedKeys.AsReadOnly(); }
}
/// <summary>
/// Gets or sets the mongo _id field.
/// </summary>
/// <value>The id.</value>
public object Id
{
get { return this["_id"]; }
set { this["_id"] = value; }
}
/// <summary>
/// Gets the value of the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
public object Get(string key)
{
object item;
return _dictionary.TryGetValue(key, out item) ? item : null;
}
/// <summary>
/// Gets the typed value of the specified key.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key">The key.</param>
/// <returns></returns>
public T Get<T>(string key){
var value = Get(key);
if (value == null)
return default(T);
return (T)Convert.ChangeType(value, typeof(T));
}
/// <summary>
/// Gets the value associated with the specified key.
/// </summary>
/// <param name="key">The key whose value to get.</param>
/// <param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param>
/// <returns>
/// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
public bool TryGetValue(string key, out object value){
return _dictionary.TryGetValue(key, out value);
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
public bool ContainsKey(string key){
return _dictionary.ContainsKey(key);
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public Document Add(string key, object value)
{
_dictionary.Add(key, value);
_orderedKeys.Add(key);//Relies on ArgumentException from above if key already exists.
EnsureKeyOrdering();
return this;
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </summary>
/// <param name="key">The object to use as the key of the element to add.</param>
/// <param name="value">The object to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
void IDictionary<string,object>.Add(string key, object value){
Add(key,value);
}
/// <summary>
/// Appends the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
[Obsolete("Use Add instead. This method is about to be removed in a future version.")]
public Document Append(string key, object value){
return Add(key, value);
}
/// <summary>
/// Sets the value of the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns></returns>
public Document Set(string key, object value){
if(key == null)
throw new ArgumentNullException("key");
if(!_orderedKeys.Contains(key))
_orderedKeys.Add(key);
_dictionary[key] = value;
EnsureKeyOrdering();
return this;
}
/// <summary>
/// Adds an item to the Document at the specified position
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <param name="position">The position.</param>
public void Insert(string key, object value, int position){
_dictionary.Add(key, value);//Relies on ArgumentException from above if key already exists.
_orderedKeys.Insert(position, key);
EnsureKeyOrdering();
}
/// <summary>
/// Prepends the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <param name="value">The value.</param>
/// <returns>This document</returns>
public Document Prepend(string key, object value){
Insert(key, value, 0);
return this;
}
/// <summary>
/// Merges the source document into this.
/// </summary>
/// <param name="source">The source.</param>
/// <returns>This document</returns>
public Document Merge(Document source)
{
if(source == null)
return this;
foreach(var key in source.Keys)
this[key] = source[key];
return this;
}
/// <summary>
/// Removes the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.
/// </exception>
public bool Remove(string key){
_orderedKeys.Remove(key);
return _dictionary.Remove(key);
}
/// <summary>
/// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
void ICollection<KeyValuePair<string, object>>.Add(KeyValuePair<string, object> item){
Add(item.Key, item.Value);
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="T:System.Collections.IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="T:System.Collections.IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
bool IDictionary.Contains(object key)
{
return _orderedKeys.Contains(Convert.ToString(key));
}
/// <summary>
/// Adds an element with the provided key and value to the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="T:System.Object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="T:System.Object"/> to use as the value of the element to add.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// An element with the same key already exists in the <see cref="T:System.Collections.IDictionary"/> object.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IDictionary"/> is read-only.
/// -or-
/// The <see cref="T:System.Collections.IDictionary"/> has a fixed size.
/// </exception>
void IDictionary.Add(object key, object value)
{
Add(Convert.ToString(key), value);
}
/// <summary>
/// Clears the contents of the <see cref="T:System.Collections.DictionaryBase"/> instance.
/// </summary>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public void Clear(){
_dictionary.Clear();
_orderedKeys.Clear();
}
/// <summary>
/// Returns an <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IDictionaryEnumerator"/> object for the <see cref="T:System.Collections.IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return ( (IDictionary)_dictionary ).GetEnumerator();
}
/// <summary>
/// Removes the element with the specified key from the <see cref="T:System.Collections.IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="key"/> is null.
/// </exception>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.IDictionary"/> object is read-only.
/// -or-
/// The <see cref="T:System.Collections.IDictionary"/> has a fixed size.
/// </exception>
void IDictionary.Remove(object key)
{
Remove(Convert.ToString(key));
}
/// <summary>
/// Gets or sets the <see cref="System.Object"/> with the specified key.
/// </summary>
/// <value></value>
object IDictionary.this[object key]
{
get { return Get(Convert.ToString(key)); }
set { Set(Convert.ToString(key), value); }
}
/// <summary>
/// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value.
/// </summary>
/// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false.
/// </returns>
bool ICollection<KeyValuePair<string, object>>.Contains(KeyValuePair<string, object> item){
return ((IDictionary<string, object>)_dictionary).Contains(item);
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection<KeyValuePair<string, object>>.CopyTo(KeyValuePair<string, object>[] array, int arrayIndex){
((ICollection<KeyValuePair<string, object>>)_dictionary).CopyTo(array,arrayIndex);
}
/// <summary>
/// Copies to items to destinationDocument.
/// </summary>
/// <param name="destinationDocument">The destination document.</param>
public void CopyTo(Document destinationDocument){
if(destinationDocument == null)
throw new ArgumentNullException("destinationDocument");
//Todo: Fix any accidental reordering issues.
foreach(var key in _orderedKeys){
if(destinationDocument.ContainsKey(key))
destinationDocument.Remove(key);
destinationDocument[key] = this[key];
}
}
/// <summary>
/// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param>
/// <returns>
/// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
/// <exception cref="T:System.NotSupportedException">
/// The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </exception>
public bool Remove(KeyValuePair<string, object> item){
var removed = ((ICollection<KeyValuePair<string, object>>)_dictionary).Remove(item);
if(removed)
_orderedKeys.Remove(item.Key);
return removed;
}
/// <summary>
/// Copies the elements of the <see cref="T:System.Collections.ICollection"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.ICollection"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
/// <exception cref="T:System.ArgumentNullException">
/// <paramref name="array"/> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// <paramref name="index"/> is less than zero.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// <paramref name="array"/> is multidimensional.
/// -or-
/// <paramref name="index"/> is equal to or greater than the length of <paramref name="array"/>.
/// -or-
/// The number of elements in the source <see cref="T:System.Collections.ICollection"/> is greater than the available space from <paramref name="index"/> to the end of the destination <paramref name="array"/>.
/// </exception>
/// <exception cref="T:System.ArgumentException">
/// The type of the source <see cref="T:System.Collections.ICollection"/> cannot be cast automatically to the type of the destination <paramref name="array"/>.
/// </exception>
void ICollection.CopyTo(Array array, int index)
{
((ICollection)_dictionary).CopyTo(array,index);
}
/// <summary>
/// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </summary>
/// <value></value>
/// <returns>
/// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>.
/// </returns>
public int Count{
get { return _dictionary.Count; }
}
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </summary>
/// <value></value>
/// <returns>
/// An object that can be used to synchronize access to the <see cref="T:System.Collections.ICollection"/>.
/// </returns>
object ICollection.SyncRoot
{
get { return _orderedKeys; /* no special object is need since _orderedKeys is internal.*/ }
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe).
/// </summary>
/// <value></value>
/// <returns>true if access to the <see cref="T:System.Collections.ICollection"/> is synchronized (thread safe); otherwise, false.
/// </returns>
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false.
/// </returns>
public bool IsReadOnly{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="T:System.Collections.IDictionary"/> object has a fixed size.
/// </summary>
/// <value></value>
/// <returns>true if the <see cref="T:System.Collections.IDictionary"/> object has a fixed size; otherwise, false.
/// </returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.
/// </returns>
/// <exception cref="T:System.NullReferenceException">
/// The <paramref name="obj"/> parameter is null.
/// </exception>
public override bool Equals(object obj){
if(obj is Document)
return Equals(obj as Document);
return base.Equals(obj);
}
/// <summary>
/// Equalses the specified obj.
/// </summary>
/// <param name="document">The obj.</param>
/// <returns></returns>
public bool Equals(Document document){
if(document == null)
return false;
if(_orderedKeys.Count != document._orderedKeys.Count)
return false;
return GetHashCode() == document.GetHashCode();
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode(){
var hash = 27;
foreach(var key in _orderedKeys){
var valueHashCode = GetValueHashCode(this[key]);
unchecked{
hash = (13*hash) + key.GetHashCode();
hash = (13*hash) + valueHashCode;
}
}
return hash;
}
/// <summary>
/// Gets the value hash code.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
private int GetValueHashCode(object value){
if(value == null)
return 0;
return (value is Array) ? GetArrayHashcode((Array)value) : value.GetHashCode();
}
/// <summary>
/// Gets the array hashcode.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
private int GetArrayHashcode(Array array){
var hash = 0;
foreach(var value in array){
var valueHashCode = GetValueHashCode(value);
unchecked{
hash = (13*hash) + valueHashCode;
}
}
return hash;
}
/// <summary>
/// Returns an enumerator that iterates through a collection.
/// </summary>
/// <returns>
/// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection.
/// </returns>
IEnumerator IEnumerable.GetEnumerator(){
return GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection.
/// </returns>
public IEnumerator<KeyValuePair<string, object>> GetEnumerator(){
return _orderedKeys.Select(orderedKey => new KeyValuePair<string, object>(orderedKey, _dictionary[orderedKey])).GetEnumerator();
}
/// <summary>
/// Toes the dictionary.
/// </summary>
/// <returns></returns>
public Dictionary<string,object> ToDictionary(){
return new Dictionary<string, object>(this);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString(){
return JsonFormatter.Serialize(this);
}
/// <summary>
/// Ensures the key ordering.
/// </summary>
private void EnsureKeyOrdering(){
if(_keyComparer==null)
return;
_orderedKeys.Sort(_keyComparer);
}
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>
/// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.
/// </returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
void IXmlSerializable.ReadXml(XmlReader reader)
{
reader.ReadStartElement();
while(reader.IsStartElement())
{
var key = reader.Name;
object value = null;
if(reader.MoveToAttribute("type"))
{
var type = Type.GetType(reader.Value);
reader.ReadStartElement();
var serializer = new XmlSerializer(type);
value = serializer.Deserialize(reader);
}
else
reader.Read();
Add(key, value);
}
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
void IXmlSerializable.WriteXml(XmlWriter writer)
{
foreach(var pair in this)
{
writer.WriteStartElement(pair.Key);
if(pair.Value == null)
continue;
var type = pair.Value.GetType();
writer.WriteAttributeString("type", type.AssemblyQualifiedName);
var serializer = new XmlSerializer(type);
serializer.Serialize(writer,pair.Value);
}
}
}
}
| |
using Exceptionless.Core.Configuration;
using Exceptionless.Core.Models;
using Exceptionless.Core.Models.Data;
using Exceptionless.Core.Repositories.Queries;
using Foundatio.Caching;
using Foundatio.Parsers.ElasticQueries;
using Foundatio.Parsers.ElasticQueries.Extensions;
using Foundatio.Repositories.Elasticsearch.Configuration;
using Foundatio.Repositories.Elasticsearch.Extensions;
using Foundatio.Repositories.Elasticsearch.Queries.Builders;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Nest;
namespace Exceptionless.Core.Repositories.Configuration;
public sealed class EventIndex : DailyIndex<PersistentEvent> {
private readonly ExceptionlessElasticConfiguration _configuration;
private readonly IServiceProvider _serviceProvider;
public EventIndex(ExceptionlessElasticConfiguration configuration, IServiceProvider serviceProvider, AppOptions appOptions) : base(configuration, configuration.Options.ScopePrefix + "events", 1, doc => ((PersistentEvent)doc).Date.UtcDateTime) {
_configuration = configuration;
_serviceProvider = serviceProvider;
if (appOptions.MaximumRetentionDays > 0)
MaxIndexAge = TimeSpan.FromDays(appOptions.MaximumRetentionDays);
AddAlias($"{Name}-today", TimeSpan.FromDays(1));
AddAlias($"{Name}-last3days", TimeSpan.FromDays(7));
AddAlias($"{Name}-last7days", TimeSpan.FromDays(7));
AddAlias($"{Name}-last30days", TimeSpan.FromDays(30));
AddAlias($"{Name}-last90days", TimeSpan.FromDays(90));
}
protected override void ConfigureQueryBuilder(ElasticQueryBuilder builder) {
var stacksRepository = _serviceProvider.GetRequiredService<IStackRepository>();
var cacheClient = _serviceProvider.GetRequiredService<ICacheClient>();
base.ConfigureQueryBuilder(builder);
builder.RegisterBefore<ParsedExpressionQueryBuilder>(new EventStackFilterQueryBuilder(stacksRepository, cacheClient, _configuration.LoggerFactory));
}
public override TypeMappingDescriptor<PersistentEvent> ConfigureIndexMapping(TypeMappingDescriptor<PersistentEvent> map) {
var mapping = map
.Dynamic(false)
.DynamicTemplates(dt => dt
.DynamicTemplate("idx_bool", t => t.Match("*-b").Mapping(m => m.Boolean(s => s)))
.DynamicTemplate("idx_date", t => t.Match("*-d").Mapping(m => m.Date(s => s)))
.DynamicTemplate("idx_number", t => t.Match("*-n").Mapping(m => m.Number(s => s.Type(NumberType.Double))))
.DynamicTemplate("idx_reference", t => t.Match("*-r").Mapping(m => m.Keyword(s => s.IgnoreAbove(256))))
.DynamicTemplate("idx_string", t => t.Match("*-s").Mapping(m => m.Keyword(s => s.IgnoreAbove(1024)))))
.Properties(p => p
.SetupDefaults()
.Keyword(f => f.Name(e => e.Id))
.Keyword(f => f.Name(e => e.OrganizationId))
.FieldAlias(a => a.Name(Alias.OrganizationId).Path(f => f.OrganizationId))
.Keyword(f => f.Name(e => e.ProjectId))
.FieldAlias(a => a.Name(Alias.ProjectId).Path(f => f.ProjectId))
.Keyword(f => f.Name(e => e.StackId))
.FieldAlias(a => a.Name(Alias.StackId).Path(f => f.StackId))
.Keyword(f => f.Name(e => e.ReferenceId))
.FieldAlias(a => a.Name(Alias.ReferenceId).Path(f => f.ReferenceId))
.Text(f => f.Name(e => e.Type).Analyzer(LOWER_KEYWORD_ANALYZER).AddKeywordField())
.Text(f => f.Name(e => e.Source).Analyzer(STANDARDPLUS_ANALYZER).SearchAnalyzer(WHITESPACE_LOWERCASE_ANALYZER).Boost(1.2).AddKeywordField())
.Date(f => f.Name(e => e.Date))
.Text(f => f.Name(e => e.Message))
.Text(f => f.Name(e => e.Tags).Analyzer(LOWER_KEYWORD_ANALYZER).Boost(1.2).AddKeywordField())
.FieldAlias(a => a.Name(Alias.Tags).Path(f => f.Tags))
.GeoPoint(f => f.Name(e => e.Geo))
.Scalar(f => f.Value)
.Scalar(f => f.Count)
.Boolean(f => f.Name(e => e.IsFirstOccurrence))
.FieldAlias(a => a.Name(Alias.IsFirstOccurrence).Path(f => f.IsFirstOccurrence))
.Object<object>(f => f.Name(e => e.Idx).Dynamic())
.Object<DataDictionary>(f => f.Name(e => e.Data).Properties(p2 => p2
.AddVersionMapping()
.AddLevelMapping()
.AddSubmissionMethodMapping()
.AddSubmissionClientMapping()
.AddLocationMapping()
.AddRequestInfoMapping()
.AddErrorMapping()
.AddSimpleErrorMapping()
.AddEnvironmentInfoMapping()
.AddUserDescriptionMapping()
.AddUserInfoMapping()))
.AddCopyToMappings()
.AddDataDictionaryAliases()
);
if (Options != null && Options.EnableMapperSizePlugin)
return mapping.SizeField(s => s.Enabled());
return mapping;
}
public override CreateIndexDescriptor ConfigureIndex(CreateIndexDescriptor idx) {
return base.ConfigureIndex(idx.Settings(s => s
.Analysis(BuildAnalysis)
.NumberOfShards(_configuration.Options.NumberOfShards)
.NumberOfReplicas(_configuration.Options.NumberOfReplicas)
.Setting("index.mapping.total_fields.limit", _configuration.Options.FieldsLimit)
.Setting("index.mapping.ignore_malformed", true)
.Priority(1)));
}
public override async Task ConfigureAsync() {
const string pipeline = "events-pipeline";
var response = await Configuration.Client.Ingest.PutPipelineAsync(pipeline, d => d.Processors(p => p
.Script(s => new ScriptProcessor {
Source = FLATTEN_ERRORS_SCRIPT.Replace("\r", String.Empty).Replace("\n", String.Empty).Replace(" ", " ")
})));
var logger = Configuration.LoggerFactory.CreateLogger<EventIndex>();
logger.LogRequest(response);
if (!response.IsValid) {
logger.LogError(response.OriginalException, "Error creating the pipeline {Pipeline}: {Message}", pipeline, response.GetErrorMessage());
throw new ApplicationException($"Error creating the pipeline {pipeline}: {response.GetErrorMessage()}", response.OriginalException);
}
await base.ConfigureAsync();
}
protected override void ConfigureQueryParser(ElasticQueryParserConfiguration config) {
config
.SetDefaultFields(new[] {
"id",
"source",
"message",
"tags",
"path",
"error.code",
"error.type",
"error.targettype",
"error.targetmethod",
$"data.{Event.KnownDataKeys.UserDescription}.description",
$"data.{Event.KnownDataKeys.UserDescription}.email_address",
$"data.{Event.KnownDataKeys.UserInfo}.identity",
$"data.{Event.KnownDataKeys.UserInfo}.name"
})
.AddQueryVisitor(new EventFieldsQueryVisitor())
.UseFieldMap(new Dictionary<string, string> {
{ Alias.BrowserVersion, $"data.{Event.KnownDataKeys.RequestInfo}.data.{RequestInfo.KnownDataKeys.BrowserVersion}" },
{ Alias.BrowserMajorVersion, $"data.{Event.KnownDataKeys.RequestInfo}.data.{RequestInfo.KnownDataKeys.BrowserMajorVersion}" },
{ Alias.User, $"data.{Event.KnownDataKeys.UserInfo}.identity" },
{ Alias.UserName, $"data.{Event.KnownDataKeys.UserInfo}.name" },
{ Alias.UserEmail, $"data.{Event.KnownDataKeys.UserInfo}.identity" },
{ Alias.UserDescription, $"data.{Event.KnownDataKeys.UserDescription}.description" },
{ Alias.OperatingSystemVersion, $"data.{Event.KnownDataKeys.RequestInfo}.data.{RequestInfo.KnownDataKeys.OSVersion}" },
{ Alias.OperatingSystemMajorVersion, $"data.{Event.KnownDataKeys.RequestInfo}.data.{RequestInfo.KnownDataKeys.OSMajorVersion}" }
});
}
public ElasticsearchOptions Options => (Configuration as ExceptionlessElasticConfiguration)?.Options;
private AnalysisDescriptor BuildAnalysis(AnalysisDescriptor ad) {
return ad.Analyzers(a => a
.Pattern(COMMA_WHITESPACE_ANALYZER, p => p.Pattern(@"[,\s]+"))
.Custom(EMAIL_ANALYZER, c => c.Filters(EMAIL_TOKEN_FILTER, "lowercase", TLD_STOPWORDS_TOKEN_FILTER, EDGE_NGRAM_TOKEN_FILTER, "unique").Tokenizer("keyword"))
.Custom(VERSION_INDEX_ANALYZER, c => c.Filters(VERSION_PAD1_TOKEN_FILTER, VERSION_PAD2_TOKEN_FILTER, VERSION_PAD3_TOKEN_FILTER, VERSION_PAD4_TOKEN_FILTER, VERSION_TOKEN_FILTER, "lowercase", "unique").Tokenizer("whitespace"))
.Custom(VERSION_SEARCH_ANALYZER, c => c.Filters(VERSION_PAD1_TOKEN_FILTER, VERSION_PAD2_TOKEN_FILTER, VERSION_PAD3_TOKEN_FILTER, VERSION_PAD4_TOKEN_FILTER, "lowercase").Tokenizer("whitespace"))
.Custom(WHITESPACE_LOWERCASE_ANALYZER, c => c.Filters("lowercase").Tokenizer(COMMA_WHITESPACE_TOKENIZER))
.Custom(TYPENAME_ANALYZER, c => c.Filters(TYPENAME_TOKEN_FILTER, "lowercase", "unique").Tokenizer(TYPENAME_HIERARCHY_TOKENIZER))
.Custom(STANDARDPLUS_ANALYZER, c => c.Filters(STANDARDPLUS_TOKEN_FILTER, "lowercase", "unique").Tokenizer(COMMA_WHITESPACE_TOKENIZER))
.Custom(LOWER_KEYWORD_ANALYZER, c => c.Filters("lowercase").Tokenizer("keyword"))
.Custom(HOST_ANALYZER, c => c.Filters("lowercase").Tokenizer(HOST_TOKENIZER))
.Custom(URL_PATH_ANALYZER, c => c.Filters("lowercase").Tokenizer(URL_PATH_TOKENIZER)))
.TokenFilters(f => f
.EdgeNGram(EDGE_NGRAM_TOKEN_FILTER, p => p.MaxGram(50).MinGram(2).Side(EdgeNGramSide.Front))
.PatternCapture(EMAIL_TOKEN_FILTER, p => p.PreserveOriginal().Patterns("(\\w+)", "(\\p{L}+)", "(\\d+)", "@(.+)", "@(.+)\\.", "(.+)@"))
.PatternCapture(STANDARDPLUS_TOKEN_FILTER, p => p.PreserveOriginal().Patterns(
@"([^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+)",
@"([^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+[\.\/\\][^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+)",
@"([^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+[\.\/\\][^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+[\.\/\\][^\.\(\)\[\]\/\\\{\}\?=&;:\<\>]+)"
))
.PatternCapture(TYPENAME_TOKEN_FILTER, p => p.PreserveOriginal().Patterns(@" ^ (\w+)", @"\.(\w+)", @"([^\(\)]+)"))
.PatternCapture(VERSION_TOKEN_FILTER, p => p.Patterns(@"^(\d+)\.", @"^(\d+\.\d+)", @"^(\d+\.\d+\.\d+)"))
.PatternReplace(VERSION_PAD1_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{1})(?=\.|-|$)").Replacement("$10000$2"))
.PatternReplace(VERSION_PAD2_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{2})(?=\.|-|$)").Replacement("$1000$2"))
.PatternReplace(VERSION_PAD3_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{3})(?=\.|-|$)").Replacement("$100$2"))
.PatternReplace(VERSION_PAD4_TOKEN_FILTER, p => p.Pattern(@"(\.|^)(\d{4})(?=\.|-|$)").Replacement("$10$2"))
.Stop(TLD_STOPWORDS_TOKEN_FILTER, p => p.StopWords("com", "net", "org", "info", "me", "edu", "mil", "gov", "biz", "co", "io", "dev"))
.WordDelimiter(ALL_WORDS_DELIMITER_TOKEN_FILTER, p => p.CatenateNumbers().PreserveOriginal().CatenateAll().CatenateWords()))
.Tokenizers(t => t
.CharGroup(COMMA_WHITESPACE_TOKENIZER, p => p.TokenizeOnCharacters(",", "whitespace"))
.CharGroup(URL_PATH_TOKENIZER, p => p.TokenizeOnCharacters("/", "-", "."))
.CharGroup(HOST_TOKENIZER, p => p.TokenizeOnCharacters("."))
.PathHierarchy(TYPENAME_HIERARCHY_TOKENIZER, p => p.Delimiter('.')));
}
private const string ALL_WORDS_DELIMITER_TOKEN_FILTER = "all_word_delimiter";
private const string EDGE_NGRAM_TOKEN_FILTER = "edge_ngram";
private const string EMAIL_TOKEN_FILTER = "email";
private const string TYPENAME_TOKEN_FILTER = "typename";
private const string VERSION_TOKEN_FILTER = "version";
private const string STANDARDPLUS_TOKEN_FILTER = "standardplus";
private const string VERSION_PAD1_TOKEN_FILTER = "version_pad1";
private const string VERSION_PAD2_TOKEN_FILTER = "version_pad2";
private const string VERSION_PAD3_TOKEN_FILTER = "version_pad3";
private const string VERSION_PAD4_TOKEN_FILTER = "version_pad4";
private const string TLD_STOPWORDS_TOKEN_FILTER = "tld_stopwords";
internal const string COMMA_WHITESPACE_ANALYZER = "comma_whitespace";
internal const string EMAIL_ANALYZER = "email";
internal const string VERSION_INDEX_ANALYZER = "version_index";
internal const string VERSION_SEARCH_ANALYZER = "version_search";
internal const string WHITESPACE_LOWERCASE_ANALYZER = "whitespace_lower";
internal const string TYPENAME_ANALYZER = "typename";
internal const string STANDARDPLUS_ANALYZER = "standardplus";
internal const string LOWER_KEYWORD_ANALYZER = "lowerkeyword";
internal const string URL_PATH_ANALYZER = "urlpath";
internal const string HOST_ANALYZER = "hostname";
private const string COMMA_WHITESPACE_TOKENIZER = "comma_whitespace";
private const string URL_PATH_TOKENIZER = "urlpath";
private const string HOST_TOKENIZER = "hostname";
private const string TYPENAME_HIERARCHY_TOKENIZER = "typename_hierarchy";
private const string FLATTEN_ERRORS_SCRIPT = @"
if (!ctx.containsKey('data') || !(ctx.data.containsKey('@error') || ctx.data.containsKey('@simple_error')))
return;
def types = [];
def messages = [];
def codes = [];
def err = ctx.data.containsKey('@error') ? ctx.data['@error'] : ctx.data['@simple_error'];
def curr = err;
while (curr != null) {
if (curr.containsKey('type'))
types.add(curr.type);
if (curr.containsKey('message'))
messages.add(curr.message);
if (curr.containsKey('code'))
codes.add(curr.code);
curr = curr.inner;
}
if (ctx.error == null)
ctx.error = new HashMap();
ctx.error.type = types;
ctx.error.message = messages;
ctx.error.code = codes;";
public sealed class Alias {
public const string OrganizationId = "organization";
public const string ProjectId = "project";
public const string StackId = "stack";
public const string Id = "id";
public const string ReferenceId = "reference";
public const string Date = "date";
public const string Type = "type";
public const string Source = "source";
public const string Message = "message";
public const string Tags = "tag";
public const string Geo = "geo";
public const string Value = "value";
public const string Count = "count";
public const string IsFirstOccurrence = "first";
public const string IDX = "idx";
public const string Version = "version";
public const string Level = "level";
public const string SubmissionMethod = "submission";
public const string IpAddress = "ip";
public const string RequestUserAgent = "useragent";
public const string RequestPath = "path";
public const string Browser = "browser";
public const string BrowserVersion = "browser.version";
public const string BrowserMajorVersion = "browser.major";
public const string RequestIsBot = "bot";
public const string ClientVersion = "client.version";
public const string ClientUserAgent = "client.useragent";
public const string Device = "device";
public const string OperatingSystem = "os";
public const string OperatingSystemVersion = "os.version";
public const string OperatingSystemMajorVersion = "os.major";
public const string CommandLine = "cmd";
public const string MachineName = "machine";
public const string MachineArchitecture = "architecture";
public const string User = "user";
public const string UserName = "user.name";
public const string UserEmail = "user.email";
public const string UserDescription = "user.description";
public const string LocationCountry = "country";
public const string LocationLevel1 = "level1";
public const string LocationLevel2 = "level2";
public const string LocationLocality = "locality";
public const string ErrorCode = "error.code";
public const string ErrorType = "error.type";
public const string ErrorMessage = "error.message";
public const string ErrorTargetType = "error.targettype";
public const string ErrorTargetMethod = "error.targetmethod";
}
}
internal static class EventIndexExtensions {
public static PropertiesDescriptor<PersistentEvent> AddCopyToMappings(this PropertiesDescriptor<PersistentEvent> descriptor) {
return descriptor
.Text(f => f.Name(EventIndex.Alias.IpAddress).Analyzer(EventIndex.COMMA_WHITESPACE_ANALYZER))
.Text(f => f.Name(EventIndex.Alias.OperatingSystem).Analyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).AddKeywordField())
.Object<object>(f => f.Name("error").Properties(p1 => p1
.Keyword(f3 => f3.Name("code").IgnoreAbove(1024).Boost(1.1))
.Text(f3 => f3.Name("message").AddKeywordField())
.Text(f3 => f3.Name("type").Analyzer(EventIndex.TYPENAME_ANALYZER).SearchAnalyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).Boost(1.1).AddKeywordField())
.Text(f6 => f6.Name("targettype").Analyzer(EventIndex.TYPENAME_ANALYZER).SearchAnalyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).Boost(1.2).AddKeywordField())
.Text(f6 => f6.Name("targetmethod").Analyzer(EventIndex.TYPENAME_ANALYZER).SearchAnalyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).Boost(1.2).AddKeywordField())));
}
public static PropertiesDescriptor<PersistentEvent> AddDataDictionaryAliases(this PropertiesDescriptor<PersistentEvent> descriptor) {
return descriptor
.FieldAlias(a => a.Name(EventIndex.Alias.Version).Path(f => (string)f.Data[Event.KnownDataKeys.Version]))
.FieldAlias(a => a.Name(EventIndex.Alias.Level).Path(f => (string)f.Data[Event.KnownDataKeys.Level]))
.FieldAlias(a => a.Name(EventIndex.Alias.SubmissionMethod).Path(f => (string)f.Data[Event.KnownDataKeys.SubmissionMethod]))
.FieldAlias(a => a.Name(EventIndex.Alias.ClientUserAgent).Path(f => ((SubmissionClient)f.Data[Event.KnownDataKeys.SubmissionClient]).UserAgent))
.FieldAlias(a => a.Name(EventIndex.Alias.ClientVersion).Path(f => ((SubmissionClient)f.Data[Event.KnownDataKeys.SubmissionClient]).Version))
.FieldAlias(a => a.Name(EventIndex.Alias.LocationCountry).Path(f => ((Location)f.Data[Event.KnownDataKeys.Location]).Country))
.FieldAlias(a => a.Name(EventIndex.Alias.LocationLevel1).Path(f => ((Location)f.Data[Event.KnownDataKeys.Location]).Level1))
.FieldAlias(a => a.Name(EventIndex.Alias.LocationLevel2).Path(f => ((Location)f.Data[Event.KnownDataKeys.Location]).Level2))
.FieldAlias(a => a.Name(EventIndex.Alias.LocationLocality).Path(f => ((Location)f.Data[Event.KnownDataKeys.Location]).Locality))
.FieldAlias(a => a.Name(EventIndex.Alias.Browser).Path(f => ((RequestInfo)f.Data[Event.KnownDataKeys.RequestInfo]).Data[RequestInfo.KnownDataKeys.Browser]))
.FieldAlias(a => a.Name(EventIndex.Alias.Device).Path(f => ((RequestInfo)f.Data[Event.KnownDataKeys.RequestInfo]).Data[RequestInfo.KnownDataKeys.Device]))
.FieldAlias(a => a.Name(EventIndex.Alias.RequestIsBot).Path(f => ((RequestInfo)f.Data[Event.KnownDataKeys.RequestInfo]).Data[RequestInfo.KnownDataKeys.IsBot]))
.FieldAlias(a => a.Name(EventIndex.Alias.RequestPath).Path(f => ((RequestInfo)f.Data[Event.KnownDataKeys.RequestInfo]).Path))
.FieldAlias(a => a.Name(EventIndex.Alias.RequestUserAgent).Path(f => ((RequestInfo)f.Data[Event.KnownDataKeys.RequestInfo]).UserAgent))
.FieldAlias(a => a.Name(EventIndex.Alias.CommandLine).Path(f => ((EnvironmentInfo)f.Data[Event.KnownDataKeys.EnvironmentInfo]).CommandLine))
.FieldAlias(a => a.Name(EventIndex.Alias.MachineArchitecture).Path(f => ((EnvironmentInfo)f.Data[Event.KnownDataKeys.EnvironmentInfo]).Architecture))
.FieldAlias(a => a.Name(EventIndex.Alias.MachineName).Path(f => ((EnvironmentInfo)f.Data[Event.KnownDataKeys.EnvironmentInfo]).MachineName));
}
public static PropertiesDescriptor<DataDictionary> AddVersionMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Text(f2 => f2.Name(Event.KnownDataKeys.Version).Analyzer(EventIndex.VERSION_INDEX_ANALYZER).SearchAnalyzer(EventIndex.VERSION_SEARCH_ANALYZER).AddKeywordField());
}
public static PropertiesDescriptor<DataDictionary> AddLevelMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Text(f2 => f2.Name(Event.KnownDataKeys.Level).Analyzer(EventIndex.LOWER_KEYWORD_ANALYZER).AddKeywordField());
}
public static PropertiesDescriptor<DataDictionary> AddSubmissionMethodMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Keyword(f2 => f2.Name(Event.KnownDataKeys.SubmissionMethod).IgnoreAbove(1024));
}
public static PropertiesDescriptor<DataDictionary> AddSubmissionClientMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<SubmissionClient>(f2 => f2.Name(Event.KnownDataKeys.SubmissionClient).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.IpAddress).Analyzer(EventIndex.COMMA_WHITESPACE_ANALYZER).CopyTo(fd => fd.Field(EventIndex.Alias.IpAddress)))
.Text(f3 => f3.Name(r => r.UserAgent).Analyzer(EventIndex.LOWER_KEYWORD_ANALYZER).AddKeywordField())
.Keyword(f3 => f3.Name(r => r.Version).IgnoreAbove(1024))));
}
public static PropertiesDescriptor<DataDictionary> AddLocationMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<Location>(f2 => f2.Name(Event.KnownDataKeys.Location).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.Country).Analyzer(EventIndex.LOWER_KEYWORD_ANALYZER).AddKeywordField())
.Keyword(f3 => f3.Name(r => r.Level1).IgnoreAbove(1024))
.Keyword(f3 => f3.Name(r => r.Level2).IgnoreAbove(1024))
.Keyword(f3 => f3.Name(r => r.Locality).IgnoreAbove(1024))));
}
public static PropertiesDescriptor<DataDictionary> AddRequestInfoMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<RequestInfo>(f2 => f2.Name(Event.KnownDataKeys.RequestInfo).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.ClientIpAddress).Analyzer(EventIndex.COMMA_WHITESPACE_ANALYZER).CopyTo(fd => fd.Field(EventIndex.Alias.IpAddress)))
.Text(f3 => f3.Name(r => r.UserAgent).AddKeywordField())
.Text(f3 => f3.Name(r => r.Path).Analyzer(EventIndex.URL_PATH_ANALYZER).AddKeywordField())
.Text(f3 => f3.Name(r => r.Host).Analyzer(EventIndex.HOST_ANALYZER).AddKeywordField())
.Scalar(r => r.Port)
.Keyword(f3 => f3.Name(r => r.HttpMethod))
.Object<DataDictionary>(f3 => f3.Name(e => e.Data).Properties(p4 => p4
.Text(f4 => f4.Name(RequestInfo.KnownDataKeys.Browser).Analyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).AddKeywordField())
.Keyword(f4 => f4.Name(RequestInfo.KnownDataKeys.BrowserVersion).IgnoreAbove(1024))
.Keyword(f4 => f4.Name(RequestInfo.KnownDataKeys.BrowserMajorVersion).IgnoreAbove(1024))
.Text(f4 => f4.Name(RequestInfo.KnownDataKeys.Device).Analyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).AddKeywordField())
.Text(f4 => f4.Name(RequestInfo.KnownDataKeys.OS).Analyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).AddKeywordField().CopyTo(fd => fd.Field(EventIndex.Alias.OperatingSystem)).Index(false))
.Keyword(f4 => f4.Name(RequestInfo.KnownDataKeys.OSVersion).IgnoreAbove(1024))
.Keyword(f4 => f4.Name(RequestInfo.KnownDataKeys.OSMajorVersion).IgnoreAbove(1024))
.Boolean(f4 => f4.Name(RequestInfo.KnownDataKeys.IsBot))))));
}
public static PropertiesDescriptor<DataDictionary> AddErrorMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<Error>(f2 => f2.Name(Event.KnownDataKeys.Error).Properties(p3 => p3
.Object<DataDictionary>(f4 => f4.Name(e => e.Data).Properties(p4 => p4
.Object<object>(f5 => f5.Name(Error.KnownDataKeys.TargetInfo).Properties(p5 => p5
.Keyword(f6 => f6.Name("ExceptionType").IgnoreAbove(1024).CopyTo(fd => fd.Field(EventIndex.Alias.ErrorTargetType)))
.Keyword(f6 => f6.Name("Method").IgnoreAbove(1024).CopyTo(fd => fd.Field(EventIndex.Alias.ErrorTargetMethod)))))))));
}
public static PropertiesDescriptor<DataDictionary> AddSimpleErrorMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<SimpleError>(f2 => f2.Name(Event.KnownDataKeys.SimpleError).Properties(p3 => p3
.Object<DataDictionary>(f4 => f4.Name(e => e.Data).Properties(p4 => p4
.Object<object>(f5 => f5.Name(Error.KnownDataKeys.TargetInfo).Properties(p5 => p5
.Keyword(f6 => f6.Name("ExceptionType").IgnoreAbove(1024).CopyTo(fd => fd.Field(EventIndex.Alias.ErrorTargetType)))))))));
}
public static PropertiesDescriptor<DataDictionary> AddEnvironmentInfoMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<EnvironmentInfo>(f2 => f2.Name(Event.KnownDataKeys.EnvironmentInfo).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.IpAddress).Analyzer(EventIndex.COMMA_WHITESPACE_ANALYZER).CopyTo(fd => fd.Field(EventIndex.Alias.IpAddress)))
.Text(f3 => f3.Name(r => r.MachineName).Analyzer(EventIndex.LOWER_KEYWORD_ANALYZER).AddKeywordField().Boost(1.1))
.Text(f3 => f3.Name(r => r.OSName).Analyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).AddKeywordField().CopyTo(fd => fd.Field(EventIndex.Alias.OperatingSystem)))
.Keyword(f3 => f3.Name(r => r.CommandLine).IgnoreAbove(1024))
.Keyword(f3 => f3.Name(r => r.Architecture).IgnoreAbove(1024))));
}
public static PropertiesDescriptor<DataDictionary> AddUserDescriptionMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<UserDescription>(f2 => f2.Name(Event.KnownDataKeys.UserDescription).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.Description))
.Text(f3 => f3.Name(r => r.EmailAddress).Analyzer(EventIndex.EMAIL_ANALYZER).SearchAnalyzer("simple").Boost(1.1).AddKeywordField().CopyTo(f4 => f4.Field($"data.{Event.KnownDataKeys.UserInfo}.identity")))));
}
public static PropertiesDescriptor<DataDictionary> AddUserInfoMapping(this PropertiesDescriptor<DataDictionary> descriptor) {
return descriptor.Object<UserInfo>(f2 => f2.Name(Event.KnownDataKeys.UserInfo).Properties(p3 => p3
.Text(f3 => f3.Name(r => r.Identity).Analyzer(EventIndex.EMAIL_ANALYZER).SearchAnalyzer(EventIndex.WHITESPACE_LOWERCASE_ANALYZER).Boost(1.1).AddKeywordField())
.Text(f3 => f3.Name(r => r.Name).Analyzer(EventIndex.LOWER_KEYWORD_ANALYZER).AddKeywordField())));
}
}
| |
// 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.
// =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
//
// Central spin logic used across the entire code-base.
//
// =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
using System.Diagnostics;
namespace System.Threading
{
// SpinWait is just a little value type that encapsulates some common spinning
// logic. It ensures we always yield on single-proc machines (instead of using busy
// waits), and that we work well on HT. It encapsulates a good mixture of spinning
// and real yielding. It's a value type so that various areas of the engine can use
// one by allocating it on the stack w/out unnecessary GC allocation overhead, e.g.:
//
// void f() {
// SpinWait wait = new SpinWait();
// while (!p) { wait.SpinOnce(); }
// ...
// }
//
// Internally it just maintains a counter that is used to decide when to yield, etc.
//
// A common usage is to spin before blocking. In those cases, the NextSpinWillYield
// property allows a user to decide to fall back to waiting once it returns true:
//
// void f() {
// SpinWait wait = new SpinWait();
// while (!p) {
// if (wait.NextSpinWillYield) { /* block! */ }
// else { wait.SpinOnce(); }
// }
// ...
// }
/// <summary>
/// Provides support for spin-based waiting.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="SpinWait"/> encapsulates common spinning logic. On single-processor machines, yields are
/// always used instead of busy waits, and on computers with Intel(R) processors employing Hyper-Threading
/// technology, it helps to prevent hardware thread starvation. SpinWait encapsulates a good mixture of
/// spinning and true yielding.
/// </para>
/// <para>
/// <see cref="SpinWait"/> is a value type, which means that low-level code can utilize SpinWait without
/// fear of unnecessary allocation overheads. SpinWait is not generally useful for ordinary applications.
/// In most cases, you should use the synchronization classes provided by the .NET Framework, such as
/// <see cref="System.Threading.Monitor"/>. For most purposes where spin waiting is required, however,
/// the <see cref="SpinWait"/> type should be preferred over the <see
/// cref="System.Threading.Thread.SpinWait"/> method.
/// </para>
/// <para>
/// While SpinWait is designed to be used in concurrent applications, it is not designed to be
/// used from multiple threads concurrently. SpinWait's members are not thread-safe. If multiple
/// threads must spin, each should use its own instance of SpinWait.
/// </para>
/// </remarks>
public struct SpinWait
{
// These constants determine the frequency of yields versus spinning. The
// numbers may seem fairly arbitrary, but were derived with at least some
// thought in the design document. I fully expect they will need to change
// over time as we gain more experience with performance.
internal const int YieldThreshold = 10; // When to switch over to a true yield.
private const int Sleep0EveryHowManyYields = 5; // After how many yields should we Sleep(0)?
internal const int DefaultSleep1Threshold = 20; // After how many yields should we Sleep(1) frequently?
/// <summary>
/// A suggested number of spin iterations before doing a proper wait, such as waiting on an event that becomes signaled
/// when the resource becomes available.
/// </summary>
/// <remarks>
/// These numbers were arrived at by experimenting with different numbers in various cases that currently use it. It's
/// only a suggested value and typically works well when the proper wait is something like an event.
///
/// Spinning less can lead to early waiting and more context switching, spinning more can decrease latency but may use
/// up some CPU time unnecessarily. Depends on the situation too, for instance SemaphoreSlim uses more iterations
/// because the waiting there is currently a lot more expensive (involves more spinning, taking a lock, etc.). It also
/// depends on the likelihood of the spin being successful and how long the wait would be but those are not accounted
/// for here.
/// </remarks>
internal static readonly int SpinCountforSpinBeforeWait = Environment.IsSingleProcessor ? 1 : 35;
// The number of times we've spun already.
private int _count;
/// <summary>
/// Gets the number of times <see cref="SpinOnce()"/> has been called on this instance.
/// </summary>
public int Count
{
get => _count;
internal set
{
Debug.Assert(value >= 0);
_count = value;
}
}
/// <summary>
/// Gets whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
/// forced context switch.
/// </summary>
/// <value>Whether the next call to <see cref="SpinOnce()"/> will yield the processor, triggering a
/// forced context switch.</value>
/// <remarks>
/// On a single-CPU machine, <see cref="SpinOnce()"/> always yields the processor. On machines with
/// multiple CPUs, <see cref="SpinOnce()"/> may yield after an unspecified number of calls.
/// </remarks>
public bool NextSpinWillYield => _count >= YieldThreshold || Environment.IsSingleProcessor;
/// <summary>
/// Performs a single spin.
/// </summary>
/// <remarks>
/// This is typically called in a loop, and may change in behavior based on the number of times a
/// <see cref="SpinOnce()"/> has been called thus far on this instance.
/// </remarks>
public void SpinOnce()
{
SpinOnceCore(DefaultSleep1Threshold);
}
/// <summary>
/// Performs a single spin.
/// </summary>
/// <param name="sleep1Threshold">
/// A minimum spin count after which <code>Thread.Sleep(1)</code> may be used. A value of <code>-1</code> may be used to
/// disable the use of <code>Thread.Sleep(1)</code>.
/// </param>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="sleep1Threshold"/> is less than <code>-1</code>.
/// </exception>
/// <remarks>
/// This is typically called in a loop, and may change in behavior based on the number of times a
/// <see cref="SpinOnce()"/> has been called thus far on this instance.
/// </remarks>
public void SpinOnce(int sleep1Threshold)
{
if (sleep1Threshold < -1)
{
throw new ArgumentOutOfRangeException(nameof(sleep1Threshold), sleep1Threshold, SR.ArgumentOutOfRange_NeedNonNegOrNegative1);
}
if (sleep1Threshold >= 0 && sleep1Threshold < YieldThreshold)
{
sleep1Threshold = YieldThreshold;
}
SpinOnceCore(sleep1Threshold);
}
private void SpinOnceCore(int sleep1Threshold)
{
Debug.Assert(sleep1Threshold >= -1);
Debug.Assert(sleep1Threshold < 0 || sleep1Threshold >= YieldThreshold);
// (_count - YieldThreshold) % 2 == 0: The purpose of this check is to interleave Thread.Yield/Sleep(0) with
// Thread.SpinWait. Otherwise, the following issues occur:
// - When there are no threads to switch to, Yield and Sleep(0) become no-op and it turns the spin loop into a
// busy-spin that may quickly reach the max spin count and cause the thread to enter a wait state, or may
// just busy-spin for longer than desired before a Sleep(1). Completing the spin loop too early can cause
// excessive context switcing if a wait follows, and entering the Sleep(1) stage too early can cause
// excessive delays.
// - If there are multiple threads doing Yield and Sleep(0) (typically from the same spin loop due to
// contention), they may switch between one another, delaying work that can make progress.
if ((
_count >= YieldThreshold &&
((_count >= sleep1Threshold && sleep1Threshold >= 0) || (_count - YieldThreshold) % 2 == 0)
) ||
Environment.IsSingleProcessor)
{
//
// We must yield.
//
// We prefer to call Thread.Yield first, triggering a SwitchToThread. This
// unfortunately doesn't consider all runnable threads on all OS SKUs. In
// some cases, it may only consult the runnable threads whose ideal processor
// is the one currently executing code. Thus we occasionally issue a call to
// Sleep(0), which considers all runnable threads at equal priority. Even this
// is insufficient since we may be spin waiting for lower priority threads to
// execute; we therefore must call Sleep(1) once in a while too, which considers
// all runnable threads, regardless of ideal processor and priority, but may
// remove the thread from the scheduler's queue for 10+ms, if the system is
// configured to use the (default) coarse-grained system timer.
//
if (_count >= sleep1Threshold && sleep1Threshold >= 0)
{
Thread.Sleep(1);
}
else
{
int yieldsSoFar = _count >= YieldThreshold ? (_count - YieldThreshold) / 2 : _count;
if ((yieldsSoFar % Sleep0EveryHowManyYields) == (Sleep0EveryHowManyYields - 1))
{
Thread.Sleep(0);
}
else
{
Thread.Yield();
}
}
}
else
{
//
// Otherwise, we will spin.
//
// We do this using the CLR's SpinWait API, which is just a busy loop that
// issues YIELD/PAUSE instructions to ensure multi-threaded CPUs can react
// intelligently to avoid starving. (These are NOOPs on other CPUs.) We
// choose a number for the loop iteration count such that each successive
// call spins for longer, to reduce cache contention. We cap the total
// number of spins we are willing to tolerate to reduce delay to the caller,
// since we expect most callers will eventually block anyway.
//
// Also, cap the maximum spin count to a value such that many thousands of CPU cycles would not be wasted doing
// the equivalent of YieldProcessor(), as at that point SwitchToThread/Sleep(0) are more likely to be able to
// allow other useful work to run. Long YieldProcessor() loops can help to reduce contention, but Sleep(1) is
// usually better for that.
//
// Thread.OptimalMaxSpinWaitsPerSpinIteration:
// - See Thread::InitializeYieldProcessorNormalized(), which describes and calculates this value.
//
int n = Thread.OptimalMaxSpinWaitsPerSpinIteration;
if (_count <= 30 && (1 << _count) < n)
{
n = 1 << _count;
}
Thread.SpinWait(n);
}
// Finally, increment our spin counter.
_count = (_count == int.MaxValue ? YieldThreshold : _count + 1);
}
/// <summary>
/// Resets the spin counter.
/// </summary>
/// <remarks>
/// This makes <see cref="SpinOnce()"/> and <see cref="NextSpinWillYield"/> behave as though no calls
/// to <see cref="SpinOnce()"/> had been issued on this instance. If a <see cref="SpinWait"/> instance
/// is reused many times, it may be useful to reset it to avoid yielding too soon.
/// </remarks>
public void Reset()
{
_count = 0;
}
#region Static Methods
/// <summary>
/// Spins until the specified condition is satisfied.
/// </summary>
/// <param name="condition">A delegate to be executed over and over until it returns true.</param>
/// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
public static void SpinUntil(Func<bool> condition)
{
#if DEBUG
bool result =
#endif
SpinUntil(condition, Timeout.Infinite);
#if DEBUG
Debug.Assert(result);
#endif
}
/// <summary>
/// Spins until the specified condition is satisfied or until the specified timeout is expired.
/// </summary>
/// <param name="condition">A delegate to be executed over and over until it returns true.</param>
/// <param name="timeout">
/// A <see cref="TimeSpan"/> that represents the number of milliseconds to wait,
/// or a TimeSpan that represents -1 milliseconds to wait indefinitely.</param>
/// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
/// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative number
/// other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater than
/// <see cref="int.MaxValue"/>.</exception>
public static bool SpinUntil(Func<bool> condition, TimeSpan timeout)
{
// Validate the timeout
long totalMilliseconds = (long)timeout.TotalMilliseconds;
if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue)
{
throw new System.ArgumentOutOfRangeException(
nameof(timeout), timeout, SR.SpinWait_SpinUntil_TimeoutWrong);
}
// Call wait with the timeout milliseconds
return SpinUntil(condition, (int)totalMilliseconds);
}
/// <summary>
/// Spins until the specified condition is satisfied or until the specified timeout is expired.
/// </summary>
/// <param name="condition">A delegate to be executed over and over until it returns true.</param>
/// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see
/// cref="System.Threading.Timeout.Infinite"/> (-1) to wait indefinitely.</param>
/// <returns>True if the condition is satisfied within the timeout; otherwise, false</returns>
/// <exception cref="ArgumentNullException">The <paramref name="condition"/> argument is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a
/// negative number other than -1, which represents an infinite time-out.</exception>
public static bool SpinUntil(Func<bool> condition, int millisecondsTimeout)
{
if (millisecondsTimeout < Timeout.Infinite)
{
throw new ArgumentOutOfRangeException(
nameof(millisecondsTimeout), millisecondsTimeout, SR.SpinWait_SpinUntil_TimeoutWrong);
}
if (condition == null)
{
throw new ArgumentNullException(nameof(condition), SR.SpinWait_SpinUntil_ArgumentNull);
}
uint startTime = 0;
if (millisecondsTimeout != 0 && millisecondsTimeout != Timeout.Infinite)
{
startTime = TimeoutHelper.GetTime();
}
SpinWait spinner = new SpinWait();
while (!condition())
{
if (millisecondsTimeout == 0)
{
return false;
}
spinner.SpinOnce();
if (millisecondsTimeout != Timeout.Infinite && spinner.NextSpinWillYield)
{
if (millisecondsTimeout <= (TimeoutHelper.GetTime() - startTime))
{
return false;
}
}
}
return true;
}
#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 Internal.Runtime.CompilerServices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace System.Runtime.InteropServices
{
[Flags]
public enum McgInterfaceFlags : byte
{
None = 0x00,
isIInspectable = 0x01, // this interface derives from IInspectable
isDelegate = 0x02, // this entry is for a WinRT delegate type, ItfType is the type of a managed delegate type
isInternal = 0x04,
useSharedCCW = 0x08, // this entry uses shared ccwVTable + thunk function
SharedCCWMask = 0xF8,
useSharedCCW_IVector = 0x08, // 4-bit shared ccw index: 16 max, 8 used
useSharedCCW_IVectorView = 0x18,
useSharedCCW_IIterable = 0x28,
useSharedCCW_IIterator = 0x38,
useSharedCCW_AsyncOperationCompletedHandler = 0x48,
useSharedCCW_IVectorBlittable = 0x58,
useSharedCCW_IVectorViewBlittable = 0x68,
useSharedCCW_IIteratorBlittable = 0x78,
}
[Flags]
public enum McgClassFlags : int
{
None = 0,
/// <summary>
/// This represents the types MarshalingBehavior.
/// </summary>
MarshalingBehavior_Inhibit = 1,
MarshalingBehavior_Free = 2,
MarshalingBehavior_Standard = 3,
MarshalingBehavior_Mask = 3,
/// <summary>
/// GCPressureRange
/// </summary>
GCPressureRange_WinRT_Default = 1 << 2,
GCPressureRange_WinRT_Low = 2 << 2,
GCPressureRange_WinRT_Medium = 3 << 2,
GCPressureRange_WinRT_High = 4 << 2,
GCPressureRange_Mask = 7 << 2,
/// <summary>
/// Either a WinRT value type, or a projected class type
/// In either case, it is not a __ComObject and we can't create it using CreateComObject
/// </summary>
NotComObject = 32,
/// <summary>
/// This type is sealed
/// </summary>
IsSealed = 64,
/// <summary>
/// This type is a WinRT type and we'll return Kind=Metadata in type name marshalling
/// </summary>
IsWinRT = 128
}
/// <summary>
/// Per-native-interface information generated by MCG
/// </summary>
[CLSCompliant(false)]
public struct McgInterfaceData // 36 bytes on 32-bit platforms
{
/// <summary>
/// NOTE: Managed debugger depends on field name: "FixupItfType" and field type must be FixupRuntimeTypeHandle
/// Update managed debugger whenever field name/field type is changed.
/// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp
/// </summary>
public FixupRuntimeTypeHandle FixupItfType; // 1 pointer
// Optional fields(FixupDispatchClassType and FixupDynamicAdapterClassType)
public FixupRuntimeTypeHandle FixupDispatchClassType; // 1 pointer, around 80% usage
public FixupRuntimeTypeHandle FixupDynamicAdapterClassType; // 1 pointer, around 20% usage
public RuntimeTypeHandle ItfType
{
get
{
return FixupItfType.RuntimeTypeHandle;
}
set
{
FixupItfType = new FixupRuntimeTypeHandle(value);
}
}
public RuntimeTypeHandle DispatchClassType
{
get
{
return FixupDispatchClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle DynamicAdapterClassType
{
get
{
return FixupDynamicAdapterClassType.RuntimeTypeHandle;
}
}
// Fixed fields
public Guid ItfGuid; // 16 bytes
/// <summary>
/// NOTE: Managed debugger depends on field name: "Flags" and field type must be an enum type
/// Update managed debugger whenever field name/field type is changed.
/// See CordbObjectValue::WalkPtrAndTypeData in debug\dbi\values.cpp
/// </summary>
public McgInterfaceFlags Flags; // 1 byte
/// <summary>
/// Whether this type is a IInspectable type
/// </summary>
internal bool IsIInspectable
{
get
{
return (Flags & McgInterfaceFlags.isIInspectable) != McgInterfaceFlags.None;
}
}
internal bool IsIInspectableOrDelegate
{
get
{
return (Flags & (McgInterfaceFlags.isIInspectable | McgInterfaceFlags.isDelegate)) != McgInterfaceFlags.None;
}
}
public short MarshalIndex; // 2 bytes: Index into InterfaceMarshalData array for shared CCW, also used for internal module sequential type index
// Optional fields(CcwVtable)
// TODO fyuan define larger McgInterfaceData for merging interop code (shared CCW, default eventhandler)
public IntPtr CcwVtable; // 1 pointer, around 20-40% usage
public IntPtr DelegateInvokeStub; // only used for RCW delegate
}
[CLSCompliant(false)]
public struct McgGenericArgumentMarshalInfo // Marshal information for generic argument T
{
// sizeOf(T)
public uint ElementSize;
// Class Type Handle for sealed T winrt class
public FixupRuntimeTypeHandle FixupElementClassType;
// Interface Type Handle for T interface type
public FixupRuntimeTypeHandle FixupElementInterfaceType;
// Type Handle for IAsyncOperation<T>
public FixupRuntimeTypeHandle FixupAsyncOperationType;
// Type Handle for Iterator<T>
public FixupRuntimeTypeHandle FixupIteratorType;
// Type Handle for VectorView<T>
public FixupRuntimeTypeHandle FixupVectorViewType;
public RuntimeTypeHandle AsyncOperationType
{
get
{
return FixupAsyncOperationType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle ElementClassType
{
get
{
return FixupElementClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle ElementInterfaceType
{
get
{
return FixupElementInterfaceType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle IteratorType
{
get
{
return FixupIteratorType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle VectorViewType
{
get
{
return FixupVectorViewType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Per-WinRT-class information generated by MCG. This is used for TypeName marshalling and for
/// CreateComObject. For the TypeName marshalling case, we have Nullable<T> / KeyValuePair<K,V> value
/// classes as the ClassType field and WinRT names like Windows.Foundation.IReference`1<blah> in the name
/// field. These entries are filtered out by CreateComObject using the Flags field.
/// </summary>
[CLSCompliant(false)]
public struct McgClassData
{
public FixupRuntimeTypeHandle FixupClassType; // FixupRuntimeTypeHandle for type in CLR (projected) view
public RuntimeTypeHandle ClassType // RuntimeTypeHandle of FixupRuntimeTypeHandle
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
public McgClassFlags Flags; // Flags (whether it is a ComObject, whether it can be boxed, etc)
internal GCPressureRange GCPressureRange
{
get
{
switch (Flags & McgClassFlags.GCPressureRange_Mask)
{
case McgClassFlags.GCPressureRange_WinRT_Default:
return GCPressureRange.WinRT_Default;
case McgClassFlags.GCPressureRange_WinRT_Low:
return GCPressureRange.WinRT_Low;
case McgClassFlags.GCPressureRange_WinRT_Medium:
return GCPressureRange.WinRT_Medium;
case McgClassFlags.GCPressureRange_WinRT_High:
return GCPressureRange.WinRT_High;
default:
return GCPressureRange.None;
}
}
}
internal ComMarshalingType MarshalingType
{
get
{
switch (Flags & McgClassFlags.MarshalingBehavior_Mask)
{
case McgClassFlags.MarshalingBehavior_Inhibit:
return ComMarshalingType.Inhibit;
case McgClassFlags.MarshalingBehavior_Free:
return ComMarshalingType.Free;
case McgClassFlags.MarshalingBehavior_Standard:
return ComMarshalingType.Standard;
default:
return ComMarshalingType.Unknown;
}
}
}
/// <summary>
/// The type handle for its base class
///
/// There are two ways to access base class: RuntimeTypeHandle or Index
/// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain
/// - therefore we would only use index for "same module" and type handle for "cross module"
///
/// Code Pattern:
/// if (BaseClassIndex >=0) { // same module }
/// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module}
/// else { // it doesn't have base}
/// </summary>
public FixupRuntimeTypeHandle FixupBaseClassType; // FixupRuntimeTypeHandle for Base class type in CLR (projected) view
public RuntimeTypeHandle BaseClassType // RuntimeTypeHandle of BaseClass
{
get
{
return FixupBaseClassType.RuntimeTypeHandle;
}
}
public short BaseClassIndex; // Index to the base class;
/// <summary>
/// The type handle for its default Interface
/// The comment above for BaseClassType applies for DefaultInterface as well
/// </summary>
public FixupRuntimeTypeHandle FixupDefaultInterfaceType; // FixupRuntimeTypeHandle for DefaultInterface type in CLR (projected) view
public RuntimeTypeHandle DefaultInterfaceType // RuntimeTypeHandle of DefaultInterface
{
get
{
return FixupDefaultInterfaceType.RuntimeTypeHandle;
}
}
public short DefaultInterfaceIndex; // Index to the default interface
}
[CLSCompliant(false)]
public struct McgHashcodeVerifyEntry
{
public FixupRuntimeTypeHandle FixupTypeHandle;
public RuntimeTypeHandle TypeHandle
{
get
{
return FixupTypeHandle.RuntimeTypeHandle;
}
}
public uint HashCode;
}
/// <summary>
/// Mcg data used for boxing
/// Boxing refers to IReference/IReferenceArray boxing, as well as projection support when marshalling
/// IInspectable, such as IKeyValuePair, System.Uri, etc.
/// So this supports boxing in a broader sense that it supports WinRT type <-> native type projection
/// There are 3 cases:
/// 1. IReference<T> / IReferenceArray<T>. It is boxed to a managed wrapper and unboxed either from the wrapper or from native IReference/IReferenceArray RCW (through unboxing stub)
/// 2. IKeyValuePair<K, V>. Very similiar to #1 except that it does not have propertyType
/// 3. All other cases, including System.Uri, NotifyCollectionChangedEventArgs, etc. They go through boxing stub and unboxing stub.
///
/// NOTE: Even though this struct doesn't have a name in itself, there is a parallel array
/// m_boxingDataNameMap that holds the corresponding class names for each boxing data
/// </summary>
[CLSCompliant(false)]
public struct McgBoxingData
{
/// <summary>
/// The target type that triggers the boxing. Used in search
/// </summary>
public FixupRuntimeTypeHandle FixupManagedClassType;
/// <summary>
/// HIDDEN
/// This is actually saved in m_boxingDataNameMap
/// The runtime class name that triggers the unboxing. Used in search.
/// </summary>
/// public string Name;
/// <summary>
/// A managed wrapper for IReference/IReferenceArray/IKeyValuePair boxing
/// We create the wrapper directly instead of going through a boxing stub. This saves us some
/// disk space (300+ boxing stub in a typical app), but we need to see whether this trade off
/// makes sense long term.
/// </summary>
public FixupRuntimeTypeHandle FixupCLRBoxingWrapperType;
public RuntimeTypeHandle ManagedClassType
{
get
{
return FixupManagedClassType.RuntimeTypeHandle;
}
}
public RuntimeTypeHandle CLRBoxingWrapperType
{
get
{
return FixupCLRBoxingWrapperType.RuntimeTypeHandle;
}
}
/// <summary>
/// General boxing stub - boxing an managed object instance into a native object instance (RCW)
/// This is used for special cases where managed wrappers aren't suitable, mainly for projected types
/// such as System.Uri.
///
/// Prototype:
/// object Boxing_Stub(object target)
/// </summary>
public IntPtr BoxingStub;
/// <summary>
/// General unboxing stub - unbox a native object instance (RCW) into a managed object (interestingly,
/// can be boxed in the managed sense)
///
/// object UnboxingStub(object target)
/// </summary>
public IntPtr UnboxingStub;
/// <summary>
/// Corresponding PropertyType
/// Only used when boxing into a managed wrapper - because it is only meaningful in IReference
/// & IReferenceArray
/// </summary>
public short PropertyType;
}
/// <summary>
/// This information is separate from the McgClassData[]
/// as its captures the types which are not imported by the MCG.
/// </summary>
[CLSCompliant(false)]
public struct McgTypeNameMarshalingData
{
public FixupRuntimeTypeHandle FixupClassType;
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Base class for KeyValuePairImpl<T>
/// </summary>
public abstract class BoxedKeyValuePair : IManagedWrapper
{
// Called by public object McgModule.Box(object obj, int boxingIndex) after allocating instance
public abstract object Initialize(object val);
public abstract object GetTarget();
}
/// <summary>
/// Supports unboxing managed wrappers such as ReferenceImpl / KeyValuePair
/// </summary>
public interface IManagedWrapper
{
object GetTarget();
}
/// <summary>
/// Base class for ReferenceImpl<T>/ReferenceArrayImpl<T>
/// </summary>
public class BoxedValue : IManagedWrapper
{
protected object m_data; // boxed value
protected short m_type; // Windows.Foundation.PropertyType
protected bool m_unboxed; // false if T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed
public BoxedValue(object val, int type)
{
m_data = val;
m_type = (short)type;
}
// Called by public object Box(object obj, int boxingIndex) after allocating instance
// T ReferenceImpl<T>.m_value needs to be unboxed from m_data when needed
virtual public void Initialize(object val, int type)
{
m_data = val;
m_type = (short)type;
}
public object GetTarget()
{
return m_data;
}
public override string ToString()
{
if (m_data != null)
{
return m_data.ToString();
}
else
{
return "null";
}
}
}
/// <summary>
/// Entries for WinRT classes that MCG didn't see in user code
/// We need to make sure when we are marshalling these types, we need to hand out the closest match
/// For example, if MCG only sees DependencyObject but native is passing MatrixTransform, we need
/// to give user the next best thing - dependencyObject, so that user can cast it to DependencyObject
///
/// MatrixTransform -> DependencyObject
/// </summary>
[CLSCompliant(false)]
public struct McgAdditionalClassData
{
public int ClassDataIndex; // Pointing to the "next best" class (DependencyObject, for example)
public FixupRuntimeTypeHandle FixupClassType; // Pointing to the "next best" class (DependencyObject, for example)
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Maps from an ICollection or IReadOnlyCollection type to the corresponding entries in m_interfaceTypeInfo
/// for IList, IDictionary, IReadOnlyList, IReadOnlyDictionary
/// </summary>
[CLSCompliant(false)]
public struct McgCollectionData
{
public FixupRuntimeTypeHandle FixupCollectionType;
public RuntimeTypeHandle CollectionType
{
get
{
return FixupCollectionType.RuntimeTypeHandle;
}
}
public FixupRuntimeTypeHandle FixupFirstType;
public RuntimeTypeHandle FirstType
{
get
{
return FixupFirstType.RuntimeTypeHandle;
}
}
public FixupRuntimeTypeHandle FixupSecondType;
public RuntimeTypeHandle SecondType
{
get
{
return FixupSecondType.RuntimeTypeHandle;
}
}
}
[CLSCompliant(false)]
public struct McgCCWFactoryInfoEntry
{
public FixupRuntimeTypeHandle FixupFactoryType;
public RuntimeTypeHandle FactoryType
{
get
{
return FixupFactoryType.RuntimeTypeHandle;
}
}
}
/// <summary>
/// Static per-type CCW information
/// </summary>
[CLSCompliant(false)]
public struct CCWTemplateData
{
/// <summary>
/// RuntimeTypeHandle of the class that this CCWTemplateData is for
/// </summary>
public FixupRuntimeTypeHandle FixupClassType;
public RuntimeTypeHandle ClassType
{
get
{
return FixupClassType.RuntimeTypeHandle;
}
}
/// <summary>
/// The type handle for its base class (that is also a managed type)
///
/// There are two ways to access base class: RuntimeTypeHandle or Index
/// Ideally we want to use typehandle for everything - but DR throws it away and breaks the inheritance chain
/// - therefore we would only use index for "same module" and type handle for "cross module"
///
/// Code Pattern:
/// if (ParentCCWTemplateIndex >=0) { // same module }
/// else if(!BaseClassType.Equals(default(RuntimeTypeHandle)) { // cross module}
/// else { // it doesn't have base}
/// </summary>
public FixupRuntimeTypeHandle FixupBaseType;
public RuntimeTypeHandle BaseType
{
get
{
return FixupBaseType.RuntimeTypeHandle;
}
}
/// <summary>
/// The index of the CCWTemplateData for its base class (that is also a managed type)
/// < 0 if does not exist or there are multiple module involved(use its BaseType property instead)
/// </summary>
public int ParentCCWTemplateIndex;
/// <summary>
/// The beginning index of list of supported interface
/// NOTE: The list for this specific type only, excluding base classes
/// </summary>
public int SupportedInterfaceListBeginIndex;
/// <summary>
/// The total number of supported interface
/// NOTE: The list for this specific type only, excluding base classes
/// </summary>
public int NumberOfSupportedInterface;
/// <summary>
/// Whether this CCWTemplateData belongs to a WinRT type
/// Typically this only happens when we import a managed class that implements a WinRT type and
/// we'll import the base WinRT type as CCW template too, as a way to capture interfaces in the class
/// hierarchy and also know which are the ones implemented by managed class
/// </summary>
public bool IsWinRTType;
}
}
| |
namespace android.widget
{
[global::MonoJavaBridge.JavaClass()]
public partial class HorizontalScrollView : android.widget.FrameLayout
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static HorizontalScrollView()
{
InitJNI();
}
protected HorizontalScrollView(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _onTouchEvent11395;
public override bool onTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onTouchEvent11395, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onTouchEvent11395, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _dispatchKeyEvent11396;
public override bool dispatchKeyEvent(android.view.KeyEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._dispatchKeyEvent11396, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._dispatchKeyEvent11396, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addView11397;
public override void addView(android.view.View arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._addView11397, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._addView11397, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _addView11398;
public override void addView(android.view.View arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._addView11398, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._addView11398, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addView11399;
public override void addView(android.view.View arg0, android.view.ViewGroup.LayoutParams arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._addView11399, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._addView11399, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _addView11400;
public override void addView(android.view.View arg0, int arg1, android.view.ViewGroup.LayoutParams arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._addView11400, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._addView11400, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onSizeChanged11401;
protected override void onSizeChanged(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onSizeChanged11401, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onSizeChanged11401, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _scrollTo11402;
public override void scrollTo(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._scrollTo11402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._scrollTo11402, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _computeScroll11403;
public override void computeScroll()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._computeScroll11403);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._computeScroll11403);
}
internal static global::MonoJavaBridge.MethodId _getLeftFadingEdgeStrength11404;
protected override float getLeftFadingEdgeStrength()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._getLeftFadingEdgeStrength11404);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._getLeftFadingEdgeStrength11404);
}
internal static global::MonoJavaBridge.MethodId _getRightFadingEdgeStrength11405;
protected override float getRightFadingEdgeStrength()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallFloatMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._getRightFadingEdgeStrength11405);
else
return @__env.CallNonVirtualFloatMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._getRightFadingEdgeStrength11405);
}
internal static global::MonoJavaBridge.MethodId _computeHorizontalScrollRange11406;
protected override int computeHorizontalScrollRange()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._computeHorizontalScrollRange11406);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._computeHorizontalScrollRange11406);
}
internal static global::MonoJavaBridge.MethodId _computeHorizontalScrollOffset11407;
protected override int computeHorizontalScrollOffset()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._computeHorizontalScrollOffset11407);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._computeHorizontalScrollOffset11407);
}
internal static global::MonoJavaBridge.MethodId _onLayout11408;
protected override void onLayout(bool arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onLayout11408, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onLayout11408, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _requestLayout11409;
public override void requestLayout()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._requestLayout11409);
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._requestLayout11409);
}
internal static global::MonoJavaBridge.MethodId _onMeasure11410;
protected override void onMeasure(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onMeasure11410, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onMeasure11410, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _requestChildFocus11411;
public override void requestChildFocus(android.view.View arg0, android.view.View arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._requestChildFocus11411, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._requestChildFocus11411, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _requestChildRectangleOnScreen11412;
public override bool requestChildRectangleOnScreen(android.view.View arg0, android.graphics.Rect arg1, bool arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._requestChildRectangleOnScreen11412, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._requestChildRectangleOnScreen11412, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _onInterceptTouchEvent11413;
public override bool onInterceptTouchEvent(android.view.MotionEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onInterceptTouchEvent11413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onInterceptTouchEvent11413, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _onRequestFocusInDescendants11414;
protected override bool onRequestFocusInDescendants(int arg0, android.graphics.Rect arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._onRequestFocusInDescendants11414, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._onRequestFocusInDescendants11414, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _measureChild11415;
protected override void measureChild(android.view.View arg0, int arg1, int arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._measureChild11415, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._measureChild11415, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _measureChildWithMargins11416;
protected override void measureChildWithMargins(android.view.View arg0, int arg1, int arg2, int arg3, int arg4)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._measureChildWithMargins11416, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._measureChildWithMargins11416, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg4));
}
internal static global::MonoJavaBridge.MethodId _getMaxScrollAmount11417;
public virtual int getMaxScrollAmount()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._getMaxScrollAmount11417);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._getMaxScrollAmount11417);
}
internal static global::MonoJavaBridge.MethodId _smoothScrollBy11418;
public virtual void smoothScrollBy(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._smoothScrollBy11418, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._smoothScrollBy11418, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _fling11419;
public virtual void fling(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._fling11419, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._fling11419, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isFillViewport11420;
public virtual bool isFillViewport()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._isFillViewport11420);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._isFillViewport11420);
}
internal static global::MonoJavaBridge.MethodId _setFillViewport11421;
public virtual void setFillViewport(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._setFillViewport11421, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._setFillViewport11421, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _isSmoothScrollingEnabled11422;
public virtual bool isSmoothScrollingEnabled()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._isSmoothScrollingEnabled11422);
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._isSmoothScrollingEnabled11422);
}
internal static global::MonoJavaBridge.MethodId _setSmoothScrollingEnabled11423;
public virtual void setSmoothScrollingEnabled(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._setSmoothScrollingEnabled11423, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._setSmoothScrollingEnabled11423, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _executeKeyEvent11424;
public virtual bool executeKeyEvent(android.view.KeyEvent arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._executeKeyEvent11424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._executeKeyEvent11424, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _pageScroll11425;
public virtual bool pageScroll(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._pageScroll11425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._pageScroll11425, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _fullScroll11426;
public virtual bool fullScroll(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._fullScroll11426, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._fullScroll11426, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _arrowScroll11427;
public virtual bool arrowScroll(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._arrowScroll11427, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._arrowScroll11427, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _smoothScrollTo11428;
public virtual void smoothScrollTo(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._smoothScrollTo11428, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._smoothScrollTo11428, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
internal static global::MonoJavaBridge.MethodId _computeScrollDeltaToGetChildRectOnScreen11429;
protected virtual int computeScrollDeltaToGetChildRectOnScreen(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView._computeScrollDeltaToGetChildRectOnScreen11429, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._computeScrollDeltaToGetChildRectOnScreen11429, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _HorizontalScrollView11430;
public HorizontalScrollView(android.content.Context arg0, android.util.AttributeSet arg1) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._HorizontalScrollView11430, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _HorizontalScrollView11431;
public HorizontalScrollView(android.content.Context arg0, android.util.AttributeSet arg1, int arg2) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._HorizontalScrollView11431, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _HorizontalScrollView11432;
public HorizontalScrollView(android.content.Context arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.widget.HorizontalScrollView.staticClass, global::android.widget.HorizontalScrollView._HorizontalScrollView11432, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.widget.HorizontalScrollView.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/widget/HorizontalScrollView"));
global::android.widget.HorizontalScrollView._onTouchEvent11395 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.HorizontalScrollView._dispatchKeyEvent11396 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "dispatchKeyEvent", "(Landroid/view/KeyEvent;)Z");
global::android.widget.HorizontalScrollView._addView11397 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;)V");
global::android.widget.HorizontalScrollView._addView11398 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;I)V");
global::android.widget.HorizontalScrollView._addView11399 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;Landroid/view/ViewGroup$LayoutParams;)V");
global::android.widget.HorizontalScrollView._addView11400 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "addView", "(Landroid/view/View;ILandroid/view/ViewGroup$LayoutParams;)V");
global::android.widget.HorizontalScrollView._onSizeChanged11401 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onSizeChanged", "(IIII)V");
global::android.widget.HorizontalScrollView._scrollTo11402 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "scrollTo", "(II)V");
global::android.widget.HorizontalScrollView._computeScroll11403 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "computeScroll", "()V");
global::android.widget.HorizontalScrollView._getLeftFadingEdgeStrength11404 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "getLeftFadingEdgeStrength", "()F");
global::android.widget.HorizontalScrollView._getRightFadingEdgeStrength11405 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "getRightFadingEdgeStrength", "()F");
global::android.widget.HorizontalScrollView._computeHorizontalScrollRange11406 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "computeHorizontalScrollRange", "()I");
global::android.widget.HorizontalScrollView._computeHorizontalScrollOffset11407 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "computeHorizontalScrollOffset", "()I");
global::android.widget.HorizontalScrollView._onLayout11408 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onLayout", "(ZIIII)V");
global::android.widget.HorizontalScrollView._requestLayout11409 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "requestLayout", "()V");
global::android.widget.HorizontalScrollView._onMeasure11410 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onMeasure", "(II)V");
global::android.widget.HorizontalScrollView._requestChildFocus11411 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "requestChildFocus", "(Landroid/view/View;Landroid/view/View;)V");
global::android.widget.HorizontalScrollView._requestChildRectangleOnScreen11412 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "requestChildRectangleOnScreen", "(Landroid/view/View;Landroid/graphics/Rect;Z)Z");
global::android.widget.HorizontalScrollView._onInterceptTouchEvent11413 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onInterceptTouchEvent", "(Landroid/view/MotionEvent;)Z");
global::android.widget.HorizontalScrollView._onRequestFocusInDescendants11414 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "onRequestFocusInDescendants", "(ILandroid/graphics/Rect;)Z");
global::android.widget.HorizontalScrollView._measureChild11415 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "measureChild", "(Landroid/view/View;II)V");
global::android.widget.HorizontalScrollView._measureChildWithMargins11416 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "measureChildWithMargins", "(Landroid/view/View;IIII)V");
global::android.widget.HorizontalScrollView._getMaxScrollAmount11417 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "getMaxScrollAmount", "()I");
global::android.widget.HorizontalScrollView._smoothScrollBy11418 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "smoothScrollBy", "(II)V");
global::android.widget.HorizontalScrollView._fling11419 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "fling", "(I)V");
global::android.widget.HorizontalScrollView._isFillViewport11420 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "isFillViewport", "()Z");
global::android.widget.HorizontalScrollView._setFillViewport11421 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "setFillViewport", "(Z)V");
global::android.widget.HorizontalScrollView._isSmoothScrollingEnabled11422 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "isSmoothScrollingEnabled", "()Z");
global::android.widget.HorizontalScrollView._setSmoothScrollingEnabled11423 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "setSmoothScrollingEnabled", "(Z)V");
global::android.widget.HorizontalScrollView._executeKeyEvent11424 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "executeKeyEvent", "(Landroid/view/KeyEvent;)Z");
global::android.widget.HorizontalScrollView._pageScroll11425 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "pageScroll", "(I)Z");
global::android.widget.HorizontalScrollView._fullScroll11426 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "fullScroll", "(I)Z");
global::android.widget.HorizontalScrollView._arrowScroll11427 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "arrowScroll", "(I)Z");
global::android.widget.HorizontalScrollView._smoothScrollTo11428 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "smoothScrollTo", "(II)V");
global::android.widget.HorizontalScrollView._computeScrollDeltaToGetChildRectOnScreen11429 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "computeScrollDeltaToGetChildRectOnScreen", "(Landroid/graphics/Rect;)I");
global::android.widget.HorizontalScrollView._HorizontalScrollView11430 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;)V");
global::android.widget.HorizontalScrollView._HorizontalScrollView11431 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;Landroid/util/AttributeSet;I)V");
global::android.widget.HorizontalScrollView._HorizontalScrollView11432 = @__env.GetMethodIDNoThrow(global::android.widget.HorizontalScrollView.staticClass, "<init>", "(Landroid/content/Context;)V");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Plang.Compiler.Backend.ASTExt;
using Plang.Compiler.TypeChecker;
using Plang.Compiler.TypeChecker.AST;
using Plang.Compiler.TypeChecker.AST.Declarations;
using Plang.Compiler.TypeChecker.AST.Expressions;
using Plang.Compiler.TypeChecker.AST.Statements;
using Plang.Compiler.TypeChecker.AST.States;
using Plang.Compiler.TypeChecker.Types;
using Antlr4.Runtime;
namespace Plang.Compiler.Backend.Symbolic
{
class TransformASTPass
{
static private int continuationNumber = 0;
static private int whileNumber = 0;
static private int callNum = 0;
static public List<IPDecl> GetTransformedDecls(Scope globalScope)
{
continuationNumber = 0;
callNum = 0;
List<IPDecl> decls = new List<IPDecl>();
foreach (var decl in globalScope.AllDecls)
{
IPDecl result = TransformDecl(decl);
if (result != null)
decls.Add(result);
}
continuationNumber = 0;
callNum = 0;
return decls;
}
static private IPDecl TransformDecl(IPDecl decl)
{
switch (decl)
{
case Function function:
if (function.IsForeign)
return function;
else
return null;
case Machine machine:
if (machine.Receives.Events.GetEnumerator().MoveNext())
return TransformMachine(machine);
else return machine;
default:
return decl;
}
}
static private Machine TransformMachine(Machine machine)
{
Machine transformedMachine = new Machine(machine.Name, machine.SourceLocation);
transformedMachine.Assume = machine.Assume;
transformedMachine.Assert = machine.Assert;
transformedMachine.Receives = machine.Receives;
transformedMachine.Sends = machine.Sends;
transformedMachine.Creates = machine.Creates;
foreach (var field in machine.Fields) transformedMachine.AddField(field);
Dictionary<Function, Function> functionMap = new Dictionary<Function, Function>();
foreach (var method in machine.Methods)
{
InlineInFunction(method);
}
foreach (var method in machine.Methods)
{
Function transformedFunction = TransformFunction(method, transformedMachine);
functionMap.Add(method, transformedFunction);
transformedMachine.AddMethod(transformedFunction);
}
transformedMachine.StartState = machine.StartState;
transformedMachine.Observes = machine.Observes;
transformedMachine.PayloadType = machine.PayloadType;
transformedMachine.Scope = machine.Scope;
foreach (var state in machine.States)
{
transformedMachine.AddState(TransformState(state, functionMap));
}
foreach (var method in machine.Methods)
{
foreach (var callee in method.Callees)
{
if (functionMap.ContainsKey(callee))
functionMap[method].AddCallee(functionMap[callee]);
else functionMap[method].AddCallee(callee);
}
}
return transformedMachine;
}
static private State TransformState(State state, IDictionary<Function, Function> functionMap)
{
State transformedState = new State(state.SourceLocation, state.Name);
transformedState.Temperature = state.Temperature;
transformedState.IsStart = state.IsStart;
if (state.Entry != null)
transformedState.Entry = functionMap[state.Entry];
if (state.Exit != null)
transformedState.Exit = functionMap[state.Exit];
transformedState.OwningMachine = state.OwningMachine;
transformedState.Container = state.Container;
foreach (var handler in state.AllEventHandlers)
{
transformedState[handler.Key] = TransformAction(handler.Value, functionMap);
}
return transformedState;
}
static private IStateAction TransformAction(IStateAction action, IDictionary<Function, Function> functionMap)
{
switch (action)
{
case EventDoAction doAction:
return new EventDoAction(doAction.SourceLocation, doAction.Trigger, functionMap[doAction.Target]);
case EventGotoState gotoState:
Function transition = null;
if(gotoState.TransitionFunction != null) transition = functionMap[gotoState.TransitionFunction];
return new EventGotoState(gotoState.SourceLocation, gotoState.Trigger, gotoState.Target, transition);
default:
return action;
}
}
static private void GenerateInline(Function caller, Function callee, IReadOnlyList<IPExpr> argsList, List<IPStmt> body, ParserRuleContext sourceLocation)
{
Dictionary<Variable,Variable> newVarMap = new Dictionary<Variable,Variable>();
for (int i = 0; i < callee.Signature.Parameters.Count; i++)
{
IPExpr expr = argsList[i];
Variable newVar = new Variable($"inline_{callNum}_{callee.Signature.Parameters[i].Name}", sourceLocation, VariableRole.Temp);
newVar.Type = expr.Type;
body.Add(new AssignStmt(sourceLocation, new VariableAccessExpr(sourceLocation, newVar), expr));
newVarMap.Add(callee.Signature.Parameters[i], newVar);
caller.AddLocalVariable(newVar);
}
foreach(var local in callee.LocalVariables)
{
Variable newVar = new Variable($"local_{callNum}_{local.Name}", sourceLocation, VariableRole.Temp);
newVar.Type = local.Type;
newVarMap.Add(local, newVar);
caller.AddLocalVariable(newVar);
}
foreach(var funStmt in callee.Body.Statements)
body.Add(ReplaceVars(funStmt, newVarMap));
callNum++;
}
static private List<IPStmt> ReplaceReturn(IReadOnlyList<IPStmt> body, IPExpr location)
{
List<IPStmt> newBody = new List<IPStmt>();
foreach (IPStmt stmt in body)
{
switch (stmt)
{
case ReturnStmt returnStmt:
newBody.Add(new AssignStmt(returnStmt.SourceLocation, location, returnStmt.ReturnValue));
break;
case CompoundStmt compoundStmt:
List<IPStmt> replace = ReplaceReturn(compoundStmt.Statements, location);
foreach (var statement in replace) newBody.Add(statement);
break;
case IfStmt ifStmt:
IPStmt thenStmt = null;
if (ifStmt.ThenBranch != null)
{
List<IPStmt> replaceThen = ReplaceReturn(ifStmt.ThenBranch.Statements, location);
thenStmt = new CompoundStmt(ifStmt.ThenBranch.SourceLocation, replaceThen);
}
IPStmt elseStmt = null;
if (ifStmt.ElseBranch != null)
{
List<IPStmt> replaceElse = ReplaceReturn(ifStmt.ElseBranch.Statements, location);
elseStmt = new CompoundStmt(ifStmt.ElseBranch.SourceLocation, replaceElse);
}
newBody.Add(new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, thenStmt, elseStmt));
break;
case ReceiveStmt receiveStmt:
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
entry.Value.Body = new CompoundStmt(entry.Value.Body.SourceLocation, ReplaceReturn(entry.Value.Body.Statements, location));
entry.Value.Signature.ReturnType = null;
}
break;
case WhileStmt whileStmt:
List<IPStmt> bodyList = new List<IPStmt>();
bodyList.Add(whileStmt.Body);
List<IPStmt> replaceWhile = ReplaceReturn(bodyList, location);
newBody.Add(new WhileStmt(whileStmt.SourceLocation, whileStmt.Condition, new CompoundStmt(whileStmt.Body.SourceLocation, replaceWhile)));
break;
default:
newBody.Add(stmt);
break;
}
}
return newBody;
}
static private void InlineStmt(Function function, IPStmt stmt, List<IPStmt> body)
{
switch (stmt)
{
case AssignStmt assign:
if (assign.Value is FunCallExpr)
{
InlineInFunction(((FunCallExpr) assign.Value).Function);
List<IPStmt> appendToBody = new List<IPStmt>();
GenerateInline(function, ((FunCallExpr) assign.Value).Function, ((FunCallExpr) assign.Value).Arguments, appendToBody, assign.SourceLocation);
appendToBody = ReplaceReturn(appendToBody, assign.Location);
foreach (var statement in appendToBody) body.Add(statement);
}
else
{
body.Add(assign);
}
break;
case CompoundStmt compound:
foreach (var statement in compound.Statements) InlineStmt(function, statement, body);
break;
case FunCallStmt call:
if (call.Function.CanReceive ?? true)
{
InlineInFunction(call.Function);
GenerateInline(function, call.Function, call.ArgsList, body, call.SourceLocation);
}
else
{
body.Add(call);
}
break;
case IfStmt ifStmt:
IPStmt thenStmt = null;
if (ifStmt.ThenBranch != null)
{
List<IPStmt> thenBranch = new List<IPStmt>();
InlineStmt(function, ifStmt.ThenBranch, thenBranch);
thenStmt = new CompoundStmt(ifStmt.ThenBranch.SourceLocation, thenBranch);
}
IPStmt elseStmt = null;
if (ifStmt.ElseBranch != null)
{
List<IPStmt> elseBranch = new List<IPStmt>();
InlineStmt(function, ifStmt.ElseBranch, elseBranch);
elseStmt = new CompoundStmt(ifStmt.ElseBranch.SourceLocation, elseBranch);
}
body.Add(new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, thenStmt, elseStmt));
break;
case WhileStmt whileStmt:
List<IPStmt> bodyList = new List<IPStmt>();
InlineStmt(function, whileStmt.Body, bodyList);
body.Add(new WhileStmt(whileStmt.SourceLocation, whileStmt.Condition, new CompoundStmt(whileStmt.Body.SourceLocation, bodyList)));
break;
default:
body.Add(stmt);
break;
}
}
static private void InlineInFunction(Function function)
{
List<IPStmt> body = new List<IPStmt>();
foreach (var stmt in function.Body.Statements)
{
InlineStmt(function, stmt, body);
}
function.Body = new CompoundStmt(function.Body.SourceLocation, body);
return;
}
static private IPStmt ReplaceVars(IPStmt stmt, Dictionary<Variable,Variable> varMap)
{
if (stmt == null) return null;
switch(stmt)
{
case AddStmt addStmt:
return new AddStmt(addStmt.SourceLocation, ReplaceVars(addStmt.Variable, varMap), ReplaceVars(addStmt.Value, varMap));
case AnnounceStmt announceStmt:
return new AnnounceStmt(announceStmt.SourceLocation, ReplaceVars(announceStmt.PEvent, varMap), ReplaceVars(announceStmt.Payload, varMap));
case AssertStmt assertStmt:
return new AssertStmt(assertStmt.SourceLocation, ReplaceVars(assertStmt.Assertion, varMap), ReplaceVars(assertStmt.Message, varMap));
case AssignStmt assignStmt:
return new AssignStmt(assignStmt.SourceLocation, ReplaceVars(assignStmt.Location, varMap), ReplaceVars(assignStmt.Value, varMap));
case CompoundStmt compoundStmt:
List<IPStmt> statements = new List<IPStmt>();
foreach (var inner in compoundStmt.Statements) statements.Add(ReplaceVars(inner, varMap));
return new CompoundStmt(compoundStmt.SourceLocation, statements);
case CtorStmt ctorStmt:
List<IPExpr> arguments = new List<IPExpr>();
foreach (var arg in ctorStmt.Arguments) arguments.Add(ReplaceVars(arg, varMap));
return new CtorStmt(ctorStmt.SourceLocation, ctorStmt.Interface, arguments);
case FunCallStmt funCallStmt:
List<IPExpr> newArgs = new List<IPExpr>();
foreach (var arg in funCallStmt.ArgsList) newArgs.Add(ReplaceVars(arg, varMap));
return new FunCallStmt(funCallStmt.SourceLocation, funCallStmt.Function, new List<IPExpr>(newArgs));
case GotoStmt gotoStmt:
return new GotoStmt(gotoStmt.SourceLocation, gotoStmt.State, ReplaceVars(gotoStmt.Payload, varMap));
case IfStmt ifStmt:
return new IfStmt(ifStmt.SourceLocation, ReplaceVars(ifStmt.Condition, varMap), ReplaceVars(ifStmt.ThenBranch, varMap), ReplaceVars(ifStmt.ElseBranch, varMap));
case InsertStmt insertStmt:
return new InsertStmt(insertStmt.SourceLocation, ReplaceVars(insertStmt.Variable, varMap), ReplaceVars(insertStmt.Index, varMap), ReplaceVars(insertStmt.Value, varMap));
case MoveAssignStmt moveAssignStmt:
Variable fromVar = moveAssignStmt.FromVariable;
if (varMap.ContainsKey(moveAssignStmt.FromVariable)) fromVar = varMap[moveAssignStmt.FromVariable];
return new MoveAssignStmt(moveAssignStmt.SourceLocation, ReplaceVars(moveAssignStmt.ToLocation, varMap), fromVar);
case PrintStmt printStmt:
return new PrintStmt(printStmt.SourceLocation, ReplaceVars(printStmt.Message, varMap));
case RaiseStmt raiseStmt:
List<IPExpr> payload = new List<IPExpr>();
foreach(var p in raiseStmt.Payload) payload.Add(ReplaceVars(p, varMap));
return new RaiseStmt(raiseStmt.SourceLocation, raiseStmt.PEvent, payload);
case ReceiveStmt receiveStmt:
Dictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
Function replacement = new Function(entry.Value.Name, entry.Value.SourceLocation);
replacement.Owner = entry.Value.Owner;
replacement.ParentFunction = entry.Value.ParentFunction;
replacement.CanReceive = entry.Value.CanReceive;
replacement.Role = entry.Value.Role;
replacement.Scope = entry.Value.Scope;
foreach (var local in entry.Value.LocalVariables) replacement.AddLocalVariable(local);
foreach (var i in entry.Value.CreatesInterfaces) replacement.AddCreatesInterface(i);
foreach (var param in entry.Value.Signature.Parameters) replacement.Signature.Parameters.Add(param);
replacement.Signature.ReturnType = entry.Value.Signature.ReturnType;
foreach (var callee in entry.Value.Callees) replacement.AddCallee(callee);
replacement.Body = (CompoundStmt) ReplaceVars(entry.Value.Body, varMap);
cases.Add(entry.Key, replacement);
}
return new ReceiveStmt(receiveStmt.SourceLocation, cases);
case RemoveStmt removeStmt:
return new RemoveStmt(removeStmt.SourceLocation, ReplaceVars(removeStmt.Variable, varMap), ReplaceVars(removeStmt.Value, varMap));
case ReturnStmt returnStmt:
return new ReturnStmt(returnStmt.SourceLocation, ReplaceVars(returnStmt.ReturnValue, varMap));
case SendStmt sendStmt:
List<IPExpr> sendArgs = new List<IPExpr>();
foreach (var arg in sendStmt.Arguments) sendArgs.Add(ReplaceVars(arg, varMap));
return new SendStmt(sendStmt.SourceLocation, ReplaceVars(sendStmt.MachineExpr, varMap), ReplaceVars(sendStmt.Evt, varMap), sendArgs);
case WhileStmt whileStmt:
return new WhileStmt(whileStmt.SourceLocation, ReplaceVars(whileStmt.Condition, varMap), ReplaceVars(whileStmt.Body, varMap));
default:
return stmt;
}
}
static private IPExpr ReplaceVars(IPExpr expr, Dictionary<Variable,Variable> varMap)
{
switch(expr)
{
case BinOpExpr binOpExpr:
return new BinOpExpr(binOpExpr.SourceLocation, binOpExpr.Operation, ReplaceVars(binOpExpr.Lhs, varMap), ReplaceVars(binOpExpr.Rhs, varMap));
case CastExpr castExpr:
return new CastExpr(castExpr.SourceLocation, ReplaceVars(castExpr.SubExpr, varMap), castExpr.Type);
case ChooseExpr chooseExpr:
return new ChooseExpr(chooseExpr.SourceLocation, ReplaceVars(chooseExpr.SubExpr, varMap), chooseExpr.Type);
case CloneExpr cloneExpr:
return ReplaceVars(cloneExpr.Term, varMap);
case CoerceExpr coerceExpr:
return new CoerceExpr(coerceExpr.SourceLocation, ReplaceVars(coerceExpr.SubExpr, varMap), coerceExpr.NewType);
case ContainsExpr containsExpr:
return new ContainsExpr(containsExpr.SourceLocation, ReplaceVars(containsExpr.Item, varMap), ReplaceVars(containsExpr.Collection, varMap));
case CtorExpr ctorExpr:
List<IPExpr> newArguments = new List<IPExpr>();
foreach (var arg in ctorExpr.Arguments) newArguments.Add(ReplaceVars(arg, varMap));
return new CtorExpr(ctorExpr.SourceLocation, ctorExpr.Interface, new List<IPExpr>(newArguments));
case FunCallExpr funCallExpr:
List<IPExpr> newArgs = new List<IPExpr>();
foreach (var arg in funCallExpr.Arguments) newArgs.Add(ReplaceVars(arg, varMap));
return new FunCallExpr(funCallExpr.SourceLocation, funCallExpr.Function, new List<IPExpr>(newArgs));
case KeysExpr keysExpr:
return new KeysExpr(keysExpr.SourceLocation, ReplaceVars(keysExpr.Expr, varMap), keysExpr.Type);
case MapAccessExpr mapAccessExpr:
return new MapAccessExpr(mapAccessExpr.SourceLocation, ReplaceVars(mapAccessExpr.MapExpr, varMap), ReplaceVars(mapAccessExpr.IndexExpr, varMap), mapAccessExpr.Type);
case NamedTupleAccessExpr namedTupleAccessExpr:
return new NamedTupleAccessExpr(namedTupleAccessExpr.SourceLocation, ReplaceVars(namedTupleAccessExpr.SubExpr, varMap), namedTupleAccessExpr.Entry);
case NamedTupleExpr namedTupleExpr:
List<IPExpr> newFields = new List<IPExpr>();
foreach (var field in namedTupleExpr.TupleFields) newFields.Add(ReplaceVars(field, varMap));
return new NamedTupleExpr(namedTupleExpr.SourceLocation, new List<IPExpr>(newFields), namedTupleExpr.Type);
case SeqAccessExpr seqAccessExpr:
return new SeqAccessExpr(seqAccessExpr.SourceLocation, ReplaceVars(seqAccessExpr.SeqExpr, varMap), ReplaceVars(seqAccessExpr.IndexExpr, varMap), seqAccessExpr.Type);
case SetAccessExpr setAccessExpr:
return new SetAccessExpr(setAccessExpr.SourceLocation, ReplaceVars(setAccessExpr.SetExpr, varMap), ReplaceVars(setAccessExpr.IndexExpr, varMap), setAccessExpr.Type);
case SizeofExpr sizeofExpr:
return new SizeofExpr(sizeofExpr.SourceLocation, ReplaceVars(sizeofExpr.Expr, varMap));
case StringExpr stringExpr:
List<IPExpr> newListArgs = new List<IPExpr>();
foreach (var arg in stringExpr.Args) newListArgs.Add(ReplaceVars(arg, varMap));
return new StringExpr(stringExpr.SourceLocation, stringExpr.BaseString, newListArgs);
case TupleAccessExpr tupleAccessExpr:
return new TupleAccessExpr(tupleAccessExpr.SourceLocation, ReplaceVars(tupleAccessExpr.SubExpr, varMap), tupleAccessExpr.FieldNo, tupleAccessExpr.Type);
case UnaryOpExpr unaryOpExpr:
return new UnaryOpExpr(unaryOpExpr.SourceLocation, unaryOpExpr.Operation, ReplaceVars(unaryOpExpr.SubExpr, varMap));
case UnnamedTupleExpr unnamedTupleExpr:
List<IPExpr> newUnnamedFields = new List<IPExpr>();
foreach (var field in unnamedTupleExpr.TupleFields) newUnnamedFields.Add(ReplaceVars(field, varMap));
return new UnnamedTupleExpr(unnamedTupleExpr.SourceLocation, new List<IPExpr>(newUnnamedFields));
case ValuesExpr valuesExpr:
return new ValuesExpr(valuesExpr.SourceLocation, ReplaceVars(valuesExpr.Expr, varMap), valuesExpr.Type);
case VariableAccessExpr variableAccessExpr:
if (varMap.ContainsKey(variableAccessExpr.Variable))
return new VariableAccessExpr(variableAccessExpr.SourceLocation, varMap[variableAccessExpr.Variable]);
else return variableAccessExpr;
default:
return expr;
}
}
static private Function TransformFunction(Function function, Machine machine)
{
if (function.CanReceive != true) {
return function;
}
if (machine == null)
throw new NotImplementedException($"Async functions {function.Name} are not supported");
Function transformedFunction = new Function(function.Name, function.SourceLocation);
transformedFunction.Owner = function.Owner;
transformedFunction.ParentFunction = function.ParentFunction;
foreach (var local in function.LocalVariables) transformedFunction.AddLocalVariable(local);
foreach (var i in function.CreatesInterfaces) transformedFunction.AddCreatesInterface(i);
transformedFunction.Role = function.Role;
transformedFunction.Body = (CompoundStmt) HandleReceives(function.Body, function, machine);
transformedFunction.Scope = function.Scope;
transformedFunction.CanChangeState = function.CanChangeState;
transformedFunction.CanRaiseEvent = function.CanRaiseEvent;
transformedFunction.CanReceive = function.CanReceive;
transformedFunction.IsNondeterministic = function.IsNondeterministic;
foreach (var param in function.Signature.Parameters) transformedFunction.Signature.Parameters.Add(param);
transformedFunction.Signature.ReturnType = function.Signature.ReturnType;
return transformedFunction;
}
static private IPStmt ReplaceBreaks(IPStmt stmt)
{
if (stmt == null) return null;
switch(stmt)
{
case CompoundStmt compoundStmt:
List<IPStmt> statements = new List<IPStmt>();
foreach (var inner in compoundStmt.Statements)
{
statements.Add(ReplaceBreaks(inner));
}
return new CompoundStmt(compoundStmt.SourceLocation, statements);
case IfStmt ifStmt:
return new IfStmt(ifStmt.SourceLocation, ifStmt.Condition, ReplaceBreaks(ifStmt.ThenBranch), ReplaceBreaks(ifStmt.ElseBranch));
case ReceiveStmt receiveStmt:
Dictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach(KeyValuePair<PEvent, Function> entry in receiveStmt.Cases)
{
Function replacement = new Function(entry.Value.Name, entry.Value.SourceLocation);
replacement.Owner = entry.Value.Owner;
replacement.ParentFunction = entry.Value.ParentFunction;
replacement.CanReceive = entry.Value.CanReceive;
replacement.Role = entry.Value.Role;
replacement.Scope = entry.Value.Scope;
foreach (var local in entry.Value.LocalVariables) replacement.AddLocalVariable(local);
foreach (var i in entry.Value.CreatesInterfaces) replacement.AddCreatesInterface(i);
foreach (var param in entry.Value.Signature.Parameters) replacement.Signature.Parameters.Add(param);
replacement.Signature.ReturnType = entry.Value.Signature.ReturnType;
foreach (var callee in entry.Value.Callees) replacement.AddCallee(callee);
replacement.Body = (CompoundStmt) ReplaceBreaks(entry.Value.Body);
cases.Add(entry.Key, replacement);
}
return new ReceiveStmt(receiveStmt.SourceLocation, cases);
case BreakStmt _:
return new ReturnStmt(stmt.SourceLocation, null);
default:
return stmt;
}
}
static private IPStmt HandleReceives(IPStmt statement, Function function, Machine machine)
{
switch (statement)
{
case CompoundStmt compound:
IEnumerator<IPStmt> enumerator = compound.Statements.GetEnumerator();
if (enumerator.MoveNext())
{
IPStmt first = enumerator.Current;
List<IPStmt> afterStmts = new List<IPStmt>();
while (enumerator.MoveNext())
{
afterStmts.Add(enumerator.Current);
}
CompoundStmt after = null;
if (afterStmts.Count > 0)
{
after = new CompoundStmt(afterStmts[0].SourceLocation, afterStmts);
after = (CompoundStmt) HandleReceives(after, function, machine);
}
List<IPStmt> result = new List<IPStmt>();
switch (first)
{
case CompoundStmt nestedCompound:
List<IPStmt> compoundStmts = new List<IPStmt>(nestedCompound.Statements);
foreach (var stmt in afterStmts)
{
compoundStmts.Add(stmt);
}
result.Add(HandleReceives(new CompoundStmt(nestedCompound.SourceLocation, compoundStmts), function, machine));
break;
case IfStmt cond:
List<IPStmt> thenStmts = new List<IPStmt>();
List<IPStmt> elseStmts = new List<IPStmt>();
if (cond.ThenBranch != null)
thenStmts = new List<IPStmt>(cond.ThenBranch.Statements);
if (cond.ElseBranch != null)
elseStmts = new List<IPStmt>(cond.ElseBranch.Statements);
foreach (var stmt in afterStmts)
{
thenStmts.Add(stmt);
elseStmts.Add(stmt);
}
CompoundStmt thenBody = new CompoundStmt(cond.SourceLocation, thenStmts);
CompoundStmt elseBody = new CompoundStmt(cond.SourceLocation, elseStmts);
result.Add(new IfStmt(cond.SourceLocation, cond.Condition, HandleReceives(thenBody, function, machine), HandleReceives(elseBody, function, machine)));
break;
case ReceiveStmt recv:
IDictionary<PEvent, Function> cases = new Dictionary<PEvent, Function>();
foreach (KeyValuePair<PEvent, Function> c in recv.Cases)
{
c.Value.AddLocalVariables(function.Signature.Parameters);
c.Value.AddLocalVariables(function.LocalVariables);
cases.Add(c.Key, TransformFunction(c.Value, machine));
}
Continuation continuation = GetContinuation(function, cases, after, recv.SourceLocation);
if (machine != null) machine.AddMethod(continuation);
foreach (Variable v in continuation.StoreParameters)
{
machine.AddField(v);
}
foreach (AssignStmt store in continuation.StoreStmts)
{
result.Add(store);
}
ReceiveSplitStmt split = new ReceiveSplitStmt(compound.SourceLocation, continuation);
result.Add(split);
break;
case WhileStmt loop:
// turn the while statement into a recursive function
WhileFunction rec = new WhileFunction(loop.SourceLocation);
rec.Owner = function.Owner;
rec.ParentFunction = function;
foreach (var param in function.Signature.Parameters) rec.AddParameter(param);
Dictionary<Variable,Variable> newVarMap = new Dictionary<Variable,Variable>();
foreach (var local in function.LocalVariables)
{
Variable machineVar = new Variable($"while_{whileNumber}_{local.Name}", local.SourceLocation, local.Role);
machineVar.Type = local.Type;
machine.AddField(machineVar);
newVarMap.Add(local, machineVar);
}
foreach (var i in function.CreatesInterfaces) rec.AddCreatesInterface(i);
rec.CanChangeState = function.CanChangeState;
rec.CanRaiseEvent = function.CanRaiseEvent;
rec.CanReceive = function.CanReceive;
rec.IsNondeterministic = function.IsNondeterministic;
// make while loop body
List<IPStmt> loopBody = new List<IPStmt>();
IEnumerator<IPStmt> bodyEnumerator = loop.Body.Statements.GetEnumerator();
while (bodyEnumerator.MoveNext())
{
IPStmt stmt = bodyEnumerator.Current;
IPStmt replaceBreak = ReplaceBreaks(stmt);
if (replaceBreak != null) {
loopBody.Add(ReplaceVars(replaceBreak, newVarMap));
}
}
List<VariableAccessExpr> recArgs = new List<VariableAccessExpr>();
foreach (var param in rec.Signature.Parameters)
{
recArgs.Add(new VariableAccessExpr(rec.SourceLocation, param));
}
// call the function
FunCallStmt recCall = new FunCallStmt(loop.SourceLocation, rec, recArgs);
loopBody = new List<IPStmt>(((CompoundStmt) HandleReceives(new CompoundStmt(rec.SourceLocation, loopBody), rec, machine)).Statements);
rec.Body = new CompoundStmt(rec.SourceLocation, loopBody);
if (machine != null) machine.AddMethod(rec);
// assign local variables
foreach (var local in function.LocalVariables)
{
result.Add(new AssignStmt(local.SourceLocation, new VariableAccessExpr(local.SourceLocation, newVarMap[local]), new VariableAccessExpr(local.SourceLocation, local)));
}
// replace the while statement with a function call
result.Add(recCall);
if (after != null)
{
foreach (var stmt in after.Statements)
{
result.Add(ReplaceVars(stmt, newVarMap));
}
}
whileNumber++;
break;
default:
if (after == null) return compound;
result.Add(first);
foreach (IPStmt stmt in after.Statements) result.Add(HandleReceives(stmt, function, machine));
break;
}
return new CompoundStmt(compound.SourceLocation, result);
}
return compound;
/*
case FunCallStmt call:
Function callee = TransformFunction(callee, machine);
FunCallStmt newCall = new FunCallStmt(SourceLocation, callee, call.ArgsList);
function.AddCallee(callee);
return newCall;
*/
default:
return statement;
}
}
static private Continuation GetContinuation(Function function, IDictionary<PEvent, Function> cases, IPStmt after, ParserRuleContext location)
{
Continuation continuation = new Continuation(new Dictionary<PEvent, Function>(cases), after, location);
continuation.ParentFunction = function;
function.AddCallee(continuation);
function.Role = FunctionRole.Method;
foreach (var v in function.Signature.Parameters) {
Variable local = new Variable(v.Name, v.SourceLocation, v.Role);
Variable store = new Variable($"continuation_{continuationNumber}_{v.Name}", v.SourceLocation, v.Role);
local.Type = v.Type;
store.Type = v.Type;
continuation.AddParameter(local, store);
}
foreach (var v in function.LocalVariables)
{
Variable local = new Variable(v.Name, v.SourceLocation, v.Role);
Variable store = new Variable($"continuation_{continuationNumber}_{v.Name}", v.SourceLocation, v.Role);
local.Type = v.Type;
store.Type = v.Type;
continuation.AddParameter(local, store);
}
continuation.CanChangeState = function.CanChangeState;
continuation.CanRaiseEvent = function.CanRaiseEvent;
continuation.Signature.ReturnType = function.Signature.ReturnType;
continuationNumber++;
return continuation;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
namespace Apache.Ignite.Core.Tests.Process
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Defines forked Ignite node.
/// </summary>
public class IgniteProcess
{
/** Executable file name. */
private static readonly string ExeName = "Apache.Ignite.exe";
/** Executable process name. */
private static readonly string ExeProcName = ExeName.Substring(0, ExeName.LastIndexOf('.'));
/** Executable configuration file name. */
private static readonly string ExeCfgName = ExeName + ".config";
/** Executable backup configuration file name. */
private static readonly string ExeCfgBakName = ExeCfgName + ".bak";
/** Directory where binaries are stored. */
private static readonly string ExeDir;
/** Full path to executable. */
private static readonly string ExePath;
/** Full path to executable configuration file. */
private static readonly string ExeCfgPath;
/** Full path to executable configuration file backup. */
private static readonly string ExeCfgBakPath;
/** Default process output reader. */
private static readonly IIgniteProcessOutputReader DfltOutReader = new IgniteProcessConsoleOutputReader();
/** Process. */
private readonly Process _proc;
/// <summary>
/// Static initializer.
/// </summary>
static IgniteProcess()
{
// 1. Locate executable file and related stuff.
DirectoryInfo dir = new FileInfo(new Uri(typeof(IgniteProcess).Assembly.CodeBase).LocalPath).Directory;
// ReSharper disable once PossibleNullReferenceException
ExeDir = dir.FullName;
var exe = dir.GetFiles(ExeName);
if (exe.Length == 0)
throw new Exception(ExeName + " is not found in test output directory: " + dir.FullName);
ExePath = exe[0].FullName;
var exeCfg = dir.GetFiles(ExeCfgName);
if (exeCfg.Length == 0)
throw new Exception(ExeCfgName + " is not found in test output directory: " + dir.FullName);
ExeCfgPath = exeCfg[0].FullName;
ExeCfgBakPath = Path.Combine(ExeDir, ExeCfgBakName);
File.Delete(ExeCfgBakPath);
}
/// <summary>
/// Save current configuration to backup.
/// </summary>
public static void SaveConfigurationBackup()
{
File.Copy(ExeCfgPath, ExeCfgBakPath, true);
}
/// <summary>
/// Restore configuration from backup.
/// </summary>
public static void RestoreConfigurationBackup()
{
File.Copy(ExeCfgBakPath, ExeCfgPath, true);
}
/// <summary>
/// Replace application configuration with another one.
/// </summary>
/// <param name="relPath">Path to config relative to executable directory.</param>
public static void ReplaceConfiguration(string relPath)
{
File.Copy(Path.Combine(ExeDir, relPath), ExeCfgPath, true);
}
/// <summary>
/// Kill all Ignite processes.
/// </summary>
public static void KillAll()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(ExeProcName))
{
proc.Kill();
proc.WaitForExit();
}
}
}
/// <summary>
/// Construector.
/// </summary>
/// <param name="args">Arguments</param>
public IgniteProcess(params string[] args) : this(DfltOutReader, args) { }
/// <summary>
/// Construector.
/// </summary>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
public IgniteProcess(IIgniteProcessOutputReader outReader, params string[] args)
{
// Add test dll path
args = args.Concat(new[] {"-assembly=" + GetType().Assembly.Location}).ToArray();
_proc = Start(ExePath, IgniteHome.Resolve(null), outReader, args);
}
/// <summary>
/// Starts a grid process.
/// </summary>
/// <param name="exePath">Exe path.</param>
/// <param name="ggHome">Ignite home.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
/// <returns>Started process.</returns>
public static Process Start(string exePath, string ggHome, IIgniteProcessOutputReader outReader = null,
params string[] args)
{
Debug.Assert(!string.IsNullOrEmpty(exePath));
Debug.Assert(!string.IsNullOrEmpty(ggHome));
// 1. Define process start configuration.
var sb = new StringBuilder();
foreach (string arg in args)
sb.Append('\"').Append(arg).Append("\" ");
var procStart = new ProcessStartInfo
{
FileName = exePath,
Arguments = sb.ToString()
};
if (!string.IsNullOrEmpty(ggHome))
procStart.EnvironmentVariables[IgniteHome.EnvIgniteHome] = ggHome;
procStart.EnvironmentVariables[Classpath.EnvIgniteNativeTestClasspath] = "true";
procStart.CreateNoWindow = true;
procStart.UseShellExecute = false;
procStart.RedirectStandardOutput = true;
procStart.RedirectStandardError = true;
var workDir = Path.GetDirectoryName(exePath);
if (workDir != null)
procStart.WorkingDirectory = workDir;
Console.WriteLine("About to run Apache.Ignite.exe process [exePath=" + exePath + ", arguments=" + sb + ']');
// 2. Start.
var proc = Process.Start(procStart);
Debug.Assert(proc != null);
// 3. Attach output readers to avoid hangs.
outReader = outReader ?? DfltOutReader;
Attach(proc, proc.StandardOutput, outReader, false);
Attach(proc, proc.StandardError, outReader, true);
return proc;
}
/// <summary>
/// Whether the process is still alive.
/// </summary>
public bool Alive
{
get { return !_proc.HasExited; }
}
/// <summary>
/// Kill process.
/// </summary>
public void Kill()
{
_proc.Kill();
}
/// <summary>
/// Suspends the process.
/// </summary>
public void Suspend()
{
_proc.Suspend();
}
/// <summary>
/// Resumes the process.
/// </summary>
public void Resume()
{
_proc.Resume();
}
/// <summary>
/// Join process.
/// </summary>
/// <returns>Exit code.</returns>
public int Join()
{
_proc.WaitForExit();
return _proc.ExitCode;
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout)
{
return _proc.WaitForExit(timeout);
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <param name="exitCode">Exit code.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout, out int exitCode)
{
if (_proc.WaitForExit(timeout))
{
exitCode = _proc.ExitCode;
return true;
}
exitCode = 0;
return false;
}
/// <summary>
/// Attach output reader to the process.
/// </summary>
/// <param name="proc">Process.</param>
/// <param name="reader">Process stream reader.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="err">Whether this is error stream.</param>
private static void Attach(Process proc, StreamReader reader, IIgniteProcessOutputReader outReader, bool err)
{
new Thread(() =>
{
while (!proc.HasExited)
outReader.OnOutput(proc, reader.ReadLine(), err);
}) {IsBackground = true}.Start();
}
}
}
| |
#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// Subtext WebLog
//
// Subtext is an open source weblog system that is a fork of the .TEXT
// weblog system.
//
// For updated news and information please visit http://subtextproject.com/
// Subtext is hosted at Google Code at http://code.google.com/p/subtext/
// The development mailing list is at subtext@googlegroups.com
//
// This project is licensed under the BSD license. See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MbUnit.Framework;
using Subtext.Framework;
using Subtext.Framework.Components;
using Subtext.Framework.Configuration;
using Subtext.Framework.Providers;
namespace UnitTests.Subtext.Framework
{
/// <summary>
/// Unit tests of Subtext.Framework.Links class methods
/// </summary>
[TestFixture]
public class LinksTests
{
[Test]
[RollBack2]
public void CanGetCategoriesByPostId()
{
UnitTestHelper.SetupBlog();
int category1Id =
Links.CreateLinkCategory(CreateCategory("Post Category 1", "Cody roolz!", CategoryType.PostCollection,
true));
int category2Id =
Links.CreateLinkCategory(CreateCategory("Post Category 2", "Cody roolz again!",
CategoryType.PostCollection, true));
Links.CreateLinkCategory(CreateCategory("Post Category 3", "Cody roolz and again!",
CategoryType.PostCollection, true));
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("phil", "title", "body");
int entryId = UnitTestHelper.Create(entry);
ObjectProvider.Instance().SetEntryCategoryList(entryId, new[] { category1Id, category2Id });
ICollection<LinkCategory> categories = Links.GetLinkCategoriesByPostId(entryId);
Assert.AreEqual(2, categories.Count, "Expected two of the three categories");
Assert.AreEqual(category1Id, categories.First().Id);
Assert.AreEqual(category2Id, categories.ElementAt(1).Id);
Assert.AreEqual(Config.CurrentBlog.Id, categories.First().BlogId);
}
[Test]
[RollBack2]
public void CanGetActiveCategories()
{
UnitTestHelper.SetupBlog();
int[] categoryIds = CreateSomeLinkCategories();
CreateLink("Link one", categoryIds[0], null);
CreateLink("Link two", categoryIds[0], null);
CreateLink("Link one-two", categoryIds[1], null);
ICollection<LinkCategory> linkCollections = ObjectProvider.Instance().GetActiveCategories();
//Test ordering by title
Assert.AreEqual("Google Blogs", linkCollections.First().Title);
Assert.AreEqual("My Favorite Feeds", linkCollections.ElementAt(1).Title);
//Check link counts
Assert.AreEqual(1, linkCollections.First().Links.Count);
Assert.AreEqual(2, linkCollections.ElementAt(1).Links.Count);
}
[Test]
[RollBack2]
public void CanUpdateLink()
{
UnitTestHelper.SetupBlog();
// Create the categories
CreateSomeLinkCategories();
int categoryId =
Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
CategoryType.LinkCollection, true));
Link link = CreateLink("Test", categoryId, null);
int linkId = link.Id;
Link loaded = ObjectProvider.Instance().GetLink(linkId);
Assert.AreEqual("Test", loaded.Title);
Entry entry = UnitTestHelper.CreateEntryInstanceForSyndication("test", "test", "test");
//Make changes then update.
link.PostId = entry.Id;
link.Title = "Another title";
link.NewWindow = true;
ObjectProvider.Instance().UpdateLink(link);
loaded = ObjectProvider.Instance().GetLink(linkId);
Assert.AreEqual("Another title", loaded.Title);
Assert.IsTrue(loaded.NewWindow);
Assert.AreEqual(entry.Id, loaded.PostId);
}
[Test]
[RollBack2]
public void CanCreateAndDeleteLink()
{
UnitTestHelper.SetupBlog();
int categoryId =
Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
CategoryType.LinkCollection, true));
Link link = CreateLink("Title", categoryId, null);
int linkId = link.Id;
Link loaded = ObjectProvider.Instance().GetLink(linkId);
Assert.AreEqual("Title", loaded.Title);
Assert.AreEqual(NullValue.NullInt32, loaded.PostId);
Assert.AreEqual(Config.CurrentBlog.Id, loaded.BlogId);
Links.DeleteLink(linkId);
Assert.IsNull(ObjectProvider.Instance().GetLink(linkId));
}
[Test]
[RollBack2]
public void CanCreateAndDeleteLinkCategory()
{
UnitTestHelper.SetupBlog();
// Create some categories
int categoryId =
Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
CategoryType.LinkCollection, true));
LinkCategory category = ObjectProvider.Instance().GetLinkCategory(categoryId, true);
Assert.AreEqual(Config.CurrentBlog.Id, category.BlogId);
Assert.AreEqual("My Favorite Feeds", category.Title);
Assert.AreEqual("Some of my favorite RSS feeds", category.Description);
Assert.IsTrue(category.HasDescription);
Assert.IsFalse(category.HasLinks);
Assert.IsFalse(category.HasImages);
Assert.IsTrue(category.IsActive);
Assert.AreEqual(CategoryType.LinkCollection, category.CategoryType);
Assert.IsNotNull(category);
Links.DeleteLinkCategory(categoryId);
Assert.IsNull(ObjectProvider.Instance().GetLinkCategory(categoryId, true));
}
/// <summary>
/// Ensures CreateLinkCategory assigns unique CatIDs
/// </summary>
[Test]
[RollBack2]
public void CreateLinkCategoryAssignsUniqueCatIDs()
{
UnitTestHelper.SetupBlog();
// Create some categories
CreateSomeLinkCategories();
ICollection<LinkCategory> linkCategoryCollection = Links.GetCategories(CategoryType.LinkCollection,
ActiveFilter.None);
LinkCategory first = null;
LinkCategory second = null;
LinkCategory third = null;
foreach(LinkCategory linkCategory in linkCategoryCollection)
{
if(first == null)
{
first = linkCategory;
continue;
}
if(second == null)
{
second = linkCategory;
continue;
}
if(third == null)
{
third = linkCategory;
continue;
}
}
// Ensure the CategoryIDs are unique
UnitTestHelper.AssertAreNotEqual(first.Id, second.Id);
UnitTestHelper.AssertAreNotEqual(first.Id, third.Id);
UnitTestHelper.AssertAreNotEqual(second.Id, third.Id);
}
[Test]
[RollBack2]
public void CanGetPostCollectionCategories()
{
UnitTestHelper.SetupBlog();
CreateSomePostCategories();
// Retrieve the categories, grab the first one and update it
ICollection<LinkCategory> originalCategories = Links.GetCategories(CategoryType.PostCollection,
ActiveFilter.None);
Assert.IsTrue(originalCategories.Count > 0);
}
/// <summary>
/// Ensure UpdateLInkCategory updates the correct link category
/// </summary>
[Test]
[RollBack2]
public void UpdateLinkCategoryIsFine()
{
UnitTestHelper.SetupBlog();
// Create the categories
CreateSomeLinkCategories();
// Retrieve the categories, grab the first one and update it
ICollection<LinkCategory> originalCategories = Links.GetCategories(CategoryType.LinkCollection,
ActiveFilter.None);
Assert.Greater(originalCategories.Count, 0, "Expected some categories in there.");
LinkCategory linkCat = null;
foreach(LinkCategory linkCategory in originalCategories)
{
linkCat = linkCategory;
break;
}
LinkCategory originalCategory = linkCat;
originalCategory.Description = "New Description";
originalCategory.IsActive = false;
bool updated = ObjectProvider.Instance().UpdateLinkCategory(originalCategory);
// Retrieve the categories and find the one we updated
ICollection<LinkCategory> updatedCategories = Links.GetCategories(CategoryType.LinkCollection,
ActiveFilter.None);
LinkCategory updatedCategory = null;
foreach(LinkCategory lc in updatedCategories)
{
if(lc.Id == originalCategory.Id)
{
updatedCategory = lc;
}
}
// Ensure the update was successful
Assert.IsTrue(updated);
Assert.IsNotNull(updatedCategory);
Assert.AreEqual("New Description", updatedCategory.Description);
Assert.AreEqual(false, updatedCategory.IsActive);
}
static int[] CreateSomeLinkCategories()
{
var categoryIds = new int[3];
categoryIds[0] =
Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
CategoryType.LinkCollection, true));
categoryIds[1] =
Links.CreateLinkCategory(CreateCategory("Google Blogs", "My favorite Google blogs",
CategoryType.LinkCollection, true));
categoryIds[2] =
Links.CreateLinkCategory(CreateCategory("Microsoft Blogs", "My favorite Microsoft blogs",
CategoryType.LinkCollection, false));
return categoryIds;
}
static int[] CreateSomePostCategories()
{
var categoryIds = new int[3];
categoryIds[0] =
Links.CreateLinkCategory(CreateCategory("My Favorite Feeds", "Some of my favorite RSS feeds",
CategoryType.PostCollection, true));
categoryIds[1] =
Links.CreateLinkCategory(CreateCategory("Google Blogs", "My favorite Google blogs",
CategoryType.PostCollection, true));
categoryIds[2] =
Links.CreateLinkCategory(CreateCategory("Microsoft Blogs", "My favorite Microsoft blogs",
CategoryType.PostCollection, false));
return categoryIds;
}
static LinkCategory CreateCategory(string title, string description, CategoryType categoryType, bool isActive)
{
var linkCategory = new LinkCategory();
linkCategory.BlogId = Config.CurrentBlog.Id;
linkCategory.Title = title;
linkCategory.Description = description;
linkCategory.CategoryType = categoryType;
linkCategory.IsActive = isActive;
return linkCategory;
}
static Link CreateLink(string title, int? categoryId, int? postId)
{
var link = new Link();
link.IsActive = true;
link.BlogId = Config.CurrentBlog.Id;
if(categoryId != null)
{
link.CategoryId = (int)categoryId;
}
link.Title = title;
if(postId != null)
{
link.PostId = (int)postId;
}
int linkId = Links.CreateLink(link);
Assert.AreEqual(linkId, link.Id);
return link;
}
/// <summary>
/// Sets the up test fixture. This is called once for
/// this test fixture before all the tests run.
/// </summary>
[TestFixtureSetUp]
public void SetUpTestFixture()
{
//Confirm app settings
UnitTestHelper.AssertAppSettings();
}
[TearDown]
public void TearDown()
{
HttpContext.Current = null;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
namespace System.Collections.Immutable
{
/// <content>
/// Contains the inner <see cref="ImmutableSortedDictionary{TKey, TValue}.Builder"/> class.
/// </content>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
public sealed partial class ImmutableSortedDictionary<TKey, TValue>
{
/// <summary>
/// A sorted dictionary that mutates with little or no memory allocations,
/// can produce and/or build on immutable sorted dictionary instances very efficiently.
/// </summary>
/// <remarks>
/// <para>
/// This class allows multiple combinations of changes to be made to a set with equal efficiency.
/// </para>
/// <para>
/// Instance members of this class are <em>not</em> thread-safe.
/// </para>
/// </remarks>
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")]
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Ignored")]
[DebuggerDisplay("Count = {Count}")]
[DebuggerTypeProxy(typeof(ImmutableSortedDictionaryBuilderDebuggerProxy<,>))]
public sealed class Builder : IDictionary<TKey, TValue>, IReadOnlyDictionary<TKey, TValue>, IDictionary
{
/// <summary>
/// The binary tree used to store the contents of the map. Contents are typically not entirely frozen.
/// </summary>
private Node _root = Node.EmptyNode;
/// <summary>
/// The key comparer.
/// </summary>
private IComparer<TKey> _keyComparer = Comparer<TKey>.Default;
/// <summary>
/// The value comparer.
/// </summary>
private IEqualityComparer<TValue> _valueComparer = EqualityComparer<TValue>.Default;
/// <summary>
/// The number of entries in the map.
/// </summary>
private int _count;
/// <summary>
/// Caches an immutable instance that represents the current state of the collection.
/// </summary>
/// <value>Null if no immutable view has been created for the current version.</value>
private ImmutableSortedDictionary<TKey, TValue> _immutable;
/// <summary>
/// A number that increments every time the builder changes its contents.
/// </summary>
private int _version;
/// <summary>
/// The object callers may use to synchronize access to this collection.
/// </summary>
private object _syncRoot;
/// <summary>
/// Initializes a new instance of the <see cref="Builder"/> class.
/// </summary>
/// <param name="map">A map to act as the basis for a new map.</param>
internal Builder(ImmutableSortedDictionary<TKey, TValue> map)
{
Requires.NotNull(map, "map");
_root = map._root;
_keyComparer = map.KeyComparer;
_valueComparer = map.ValueComparer;
_count = map.Count;
_immutable = map;
}
#region IDictionary<TKey, TValue> Properties and Indexer
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TKey> IDictionary<TKey, TValue>.Keys
{
get { return this.Root.Keys.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TKey> Keys
{
get { return this.Root.Keys; }
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
ICollection<TValue> IDictionary<TKey, TValue>.Values
{
get { return this.Root.Values.ToArray(this.Count); }
}
/// <summary>
/// See <see cref="IReadOnlyDictionary{TKey, TValue}"/>
/// </summary>
public IEnumerable<TValue> Values
{
get { return this.Root.Values; }
}
/// <summary>
/// Gets the number of elements in this map.
/// </summary>
public int Count
{
get { return _count; }
}
/// <summary>
/// Gets a value indicating whether this instance is read-only.
/// </summary>
/// <value>Always <c>false</c>.</value>
bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Gets the current version of the contents of this builder.
/// </summary>
internal int Version
{
get { return _version; }
}
/// <summary>
/// Gets or sets the root node that represents the data in this collection.
/// </summary>
private Node Root
{
get
{
return _root;
}
set
{
// We *always* increment the version number because some mutations
// may not create a new value of root, although the existing root
// instance may have mutated.
_version++;
if (_root != value)
{
_root = value;
// Clear any cached value for the immutable view since it is now invalidated.
_immutable = null;
}
}
}
#region IDictionary<TKey, TValue> Indexer
/// <summary>
/// Gets or sets the value for a given key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>The value associated with the given key.</returns>
public TValue this[TKey key]
{
get
{
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
throw new KeyNotFoundException();
}
set
{
bool replacedExistingValue, mutated;
this.Root = _root.SetItem(key, value, _keyComparer, _valueComparer, out replacedExistingValue, out mutated);
if (mutated && !replacedExistingValue)
{
_count++;
}
}
}
#endregion
#region IDictionary Properties
/// <summary>
/// Gets a value indicating whether the <see cref="IDictionary"/> object has a fixed size.
/// </summary>
/// <returns>true if the <see cref="IDictionary"/> object has a fixed size; otherwise, false.</returns>
bool IDictionary.IsFixedSize
{
get { return false; }
}
/// <summary>
/// Gets a value indicating whether the <see cref="ICollection{T}"/> is read-only.
/// </summary>
/// <returns>true if the <see cref="ICollection{T}"/> is read-only; otherwise, false.
/// </returns>
bool IDictionary.IsReadOnly
{
get { return false; }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the keys of the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the keys of the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Keys
{
get { return this.Keys.ToArray(this.Count); }
}
/// <summary>
/// Gets an <see cref="ICollection{T}"/> containing the values in the <see cref="IDictionary{TKey, TValue}"/>.
/// </summary>
/// <returns>
/// An <see cref="ICollection{T}"/> containing the values in the object that implements <see cref="IDictionary{TKey, TValue}"/>.
/// </returns>
ICollection IDictionary.Values
{
get { return this.Values.ToArray(this.Count); }
}
#endregion
#region ICollection Properties
/// <summary>
/// Gets an object that can be used to synchronize access to the <see cref="ICollection"/>.
/// </summary>
/// <returns>An object that can be used to synchronize access to the <see cref="ICollection"/>.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
object ICollection.SyncRoot
{
get
{
if (_syncRoot == null)
{
Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null);
}
return _syncRoot;
}
}
/// <summary>
/// Gets a value indicating whether access to the <see cref="ICollection"/> is synchronized (thread safe).
/// </summary>
/// <returns>true if access to the <see cref="ICollection"/> is synchronized (thread safe); otherwise, false.</returns>
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
bool ICollection.IsSynchronized
{
get { return false; }
}
/// <summary>
/// Gets or sets the key comparer.
/// </summary>
/// <value>
/// The key comparer.
/// </value>
public IComparer<TKey> KeyComparer
{
get
{
return _keyComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != _keyComparer)
{
var newRoot = Node.EmptyNode;
int count = 0;
foreach (var item in this)
{
bool mutated;
newRoot = newRoot.Add(item.Key, item.Value, value, _valueComparer, out mutated);
if (mutated)
{
count++;
}
}
_keyComparer = value;
this.Root = newRoot;
_count = count;
}
}
}
/// <summary>
/// Gets or sets the value comparer.
/// </summary>
/// <value>
/// The value comparer.
/// </value>
public IEqualityComparer<TValue> ValueComparer
{
get
{
return _valueComparer;
}
set
{
Requires.NotNull(value, "value");
if (value != _valueComparer)
{
// When the key comparer is the same but the value comparer is different, we don't need a whole new tree
// because the structure of the tree does not depend on the value comparer.
// We just need a new root node to store the new value comparer.
_valueComparer = value;
_immutable = null; // invalidate cached immutable
}
}
}
#endregion
#region IDictionary Methods
/// <summary>
/// Adds an element with the provided key and value to the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The <see cref="object"/> to use as the key of the element to add.</param>
/// <param name="value">The <see cref="object"/> to use as the value of the element to add.</param>
void IDictionary.Add(object key, object value)
{
this.Add((TKey)key, (TValue)value);
}
/// <summary>
/// Determines whether the <see cref="IDictionary"/> object contains an element with the specified key.
/// </summary>
/// <param name="key">The key to locate in the <see cref="IDictionary"/> object.</param>
/// <returns>
/// true if the <see cref="IDictionary"/> contains an element with the key; otherwise, false.
/// </returns>
bool IDictionary.Contains(object key)
{
return this.ContainsKey((TKey)key);
}
/// <summary>
/// Returns an <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </summary>
/// <returns>
/// An <see cref="IDictionaryEnumerator"/> object for the <see cref="IDictionary"/> object.
/// </returns>
IDictionaryEnumerator IDictionary.GetEnumerator()
{
return new DictionaryEnumerator<TKey, TValue>(this.GetEnumerator());
}
/// <summary>
/// Removes the element with the specified key from the <see cref="IDictionary"/> object.
/// </summary>
/// <param name="key">The key of the element to remove.</param>
void IDictionary.Remove(object key)
{
this.Remove((TKey)key);
}
/// <summary>
/// Gets or sets the element with the specified key.
/// </summary>
/// <param name="key">The key.</param>
/// <returns></returns>
object IDictionary.this[object key]
{
get { return this[(TKey)key]; }
set { this[(TKey)key] = (TValue)value; }
}
#endregion
#region ICollection methods
/// <summary>
/// Copies the elements of the <see cref="ICollection"/> to an <see cref="Array"/>, starting at a particular <see cref="Array"/> index.
/// </summary>
/// <param name="array">The one-dimensional <see cref="Array"/> that is the destination of the elements copied from <see cref="ICollection"/>. The <see cref="Array"/> must have zero-based indexing.</param>
/// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param>
void ICollection.CopyTo(Array array, int index)
{
this.Root.CopyTo(array, index, this.Count);
}
#endregion
#region IDictionary<TKey, TValue> Methods
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(TKey key, TValue value)
{
bool mutated;
this.Root = this.Root.Add(key, value, _keyComparer, _valueComparer, out mutated);
if (mutated)
{
_count++;
}
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool ContainsKey(TKey key)
{
return this.Root.ContainsKey(key, _keyComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(TKey key)
{
bool mutated;
this.Root = this.Root.Remove(key, _keyComparer, out mutated);
if (mutated)
{
_count--;
}
return mutated;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool TryGetValue(TKey key, out TValue value)
{
return this.Root.TryGetValue(key, _keyComparer, out value);
}
/// <summary>
/// See the <see cref="IImmutableDictionary{TKey, TValue}"/> interface.
/// </summary>
public bool TryGetKey(TKey equalKey, out TKey actualKey)
{
Requires.NotNullAllowStructs(equalKey, "equalKey");
return this.Root.TryGetKey(equalKey, _keyComparer, out actualKey);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Add(KeyValuePair<TKey, TValue> item)
{
this.Add(item.Key, item.Value);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public void Clear()
{
this.Root = ImmutableSortedDictionary<TKey, TValue>.Node.EmptyNode;
_count = 0;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Contains(KeyValuePair<TKey, TValue> item)
{
return this.Root.Contains(item, _keyComparer, _valueComparer);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex)
{
this.Root.CopyTo(array, arrayIndex, this.Count);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public bool Remove(KeyValuePair<TKey, TValue> item)
{
if (this.Contains(item))
{
return this.Remove(item.Key);
}
return false;
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
public ImmutableSortedDictionary<TKey, TValue>.Enumerator GetEnumerator()
{
return this.Root.GetEnumerator(this);
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator()
{
return this.GetEnumerator();
}
/// <summary>
/// See <see cref="IDictionary{TKey, TValue}"/>
/// </summary>
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
#endregion
#region Public methods
/// <summary>
/// Determines whether the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>
/// contains an element with the specified value.
/// </summary>
/// <param name="value">
/// The value to locate in the <see cref="ImmutableSortedDictionary{TKey, TValue}"/>.
/// The value can be null for reference types.
/// </param>
/// <returns>
/// true if the <see cref="ImmutableSortedDictionary{TKey, TValue}"/> contains
/// an element with the specified value; otherwise, false.
/// </returns>
[Pure]
public bool ContainsValue(TValue value)
{
return _root.ContainsValue(value, _valueComparer);
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="items">The keys for entries to remove from the dictionary.</param>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")]
public void AddRange(IEnumerable<KeyValuePair<TKey, TValue>> items)
{
Requires.NotNull(items, "items");
foreach (var pair in items)
{
this.Add(pair);
}
}
/// <summary>
/// Removes any entries from the dictionaries with keys that match those found in the specified sequence.
/// </summary>
/// <param name="keys">The keys for entries to remove from the dictionary.</param>
public void RemoveRange(IEnumerable<TKey> keys)
{
Requires.NotNull(keys, "keys");
foreach (var key in keys)
{
this.Remove(key);
}
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <returns>The value for the key, or the default value for type <typeparamref name="TValue"/> if no matching key was found.</returns>
[Pure]
public TValue GetValueOrDefault(TKey key)
{
return this.GetValueOrDefault(key, default(TValue));
}
/// <summary>
/// Gets the value for a given key if a matching key exists in the dictionary.
/// </summary>
/// <param name="key">The key to search for.</param>
/// <param name="defaultValue">The default value to return if no matching key is found in the dictionary.</param>
/// <returns>
/// The value for the key, or <paramref name="defaultValue"/> if no matching key was found.
/// </returns>
[Pure]
public TValue GetValueOrDefault(TKey key, TValue defaultValue)
{
Requires.NotNullAllowStructs(key, "key");
TValue value;
if (this.TryGetValue(key, out value))
{
return value;
}
return defaultValue;
}
/// <summary>
/// Creates an immutable sorted dictionary based on the contents of this instance.
/// </summary>
/// <returns>An immutable map.</returns>
/// <remarks>
/// This method is an O(n) operation, and approaches O(1) time as the number of
/// actual mutations to the set since the last call to this method approaches 0.
/// </remarks>
public ImmutableSortedDictionary<TKey, TValue> ToImmutable()
{
// Creating an instance of ImmutableSortedMap<T> with our root node automatically freezes our tree,
// ensuring that the returned instance is immutable. Any further mutations made to this builder
// will clone (and unfreeze) the spine of modified nodes until the next time this method is invoked.
if (_immutable == null)
{
_immutable = Wrap(this.Root, _count, _keyComparer, _valueComparer);
}
return _immutable;
}
#endregion
}
}
/// <summary>
/// A simple view of the immutable collection that the debugger can show to the developer.
/// </summary>
internal class ImmutableSortedDictionaryBuilderDebuggerProxy<TKey, TValue>
{
/// <summary>
/// The collection to be enumerated.
/// </summary>
private readonly ImmutableSortedDictionary<TKey, TValue>.Builder _map;
/// <summary>
/// The simple view of the collection.
/// </summary>
private KeyValuePair<TKey, TValue>[] _contents;
/// <summary>
/// Initializes a new instance of the <see cref="ImmutableSortedDictionaryBuilderDebuggerProxy{TKey, TValue}"/> class.
/// </summary>
/// <param name="map">The collection to display in the debugger</param>
public ImmutableSortedDictionaryBuilderDebuggerProxy(ImmutableSortedDictionary<TKey, TValue>.Builder map)
{
Requires.NotNull(map, "map");
_map = map;
}
/// <summary>
/// Gets a simple debugger-viewable collection.
/// </summary>
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public KeyValuePair<TKey, TValue>[] Contents
{
get
{
if (_contents == null)
{
_contents = _map.ToArray(_map.Count);
}
return _contents;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
using bv.common.Core;
using bv.common.Resources;
using bv.model.BLToolkit;
using bv.model.Model.Core;
using bv.winclient.Core;
using DevExpress.Utils;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraPrinting;
using eidss.model.Resources;
using EIDSS.Reports.Barcode;
using EIDSS.Reports.Barcode.Designer;
using EIDSS.Reports.BaseControls.Report;
namespace EIDSS.Reports.BaseControls.Keeper
{
public partial class BaseBarcodeKeeper : BvXtraUserControl
{
public const float BarcodeZoom = 2.0f;
private const string ColumnNumberName = "strNumberName";
private const string ColumnNumberId = "idfsNumberName";
private BarcodeKeeperMode m_Mode = BarcodeKeeperMode.New;
private IList<long> m_ObjectIdList = new List<long>();
private IList<SampleBarcodeDTO> m_SamplesList = new List<SampleBarcodeDTO>();
private DesignController m_DesignController;
public BaseBarcodeKeeper()
{
InitializeComponent();
if (WinUtils.IsComponentInDesignMode(this))
{
return;
}
BindCbTemplateTypes();
reportView1.OnReportEdit += ReportViewOnReportEdit;
reportView1.OnReportLoadDefault += ReportView1OnReportLoadDefault;
}
public void SetObject(NumberingObject type, IList<long> idList)
{
m_ObjectIdList = idList ?? new List<long>();
if (m_ObjectIdList.Count > 0)
{
m_Mode = BarcodeKeeperMode.Existing;
}
InitBarcodeTypeLookup(type);
}
public void SetObject(IList<SampleBarcodeDTO> samples)
{
m_SamplesList = samples ?? new List<SampleBarcodeDTO>();
m_Mode = BarcodeKeeperMode.SampleNewOrExisting;
InitBarcodeTypeLookup(NumberingObject.Sample);
}
private void InitBarcodeTypeLookup(NumberingObject type)
{
var dataView = ((DataView) cbTemplateTypes.Properties.DataSource);
dataView.Sort = "idfsNumberName";
DataRowView[] found = dataView.FindRows((long) type);
if (found.Length > 0)
{
cbTemplateTypes.EditValue = found[0][ColumnNumberId];
}
}
private void ReportView1OnReportLoadDefault(object sender, EventArgs e)
{
if (m_DesignController == null)
{
throw new ApplicationException("Report Design Controller is not initialized.");
}
DialogResult dialogResult = MessageForm.Show(BvMessages.Get("msgLoadDefaultReport", "Load default report?"),
BvMessages.Get("Confirmation"),
MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
m_DesignController.DeleteReportLayout();
ReloadReport();
}
}
private void ReportViewOnReportEdit(object sender, EventArgs e)
{
if (m_DesignController == null)
{
throw new ApplicationException("Report Design Controller is not initialized.");
}
m_DesignController.SwowDesigner();
ReloadReport();
}
private void cbTemplateTypes_EditValueChanged(object sender, EventArgs e)
{
ReloadReport();
}
private void numQuantity_ValueChanged(object sender, EventArgs e)
{
ReloadReport();
}
private void ReloadReport()
{
grcHeader.Visible = m_Mode == BarcodeKeeperMode.New;
if (Utils.IsEmpty(cbTemplateTypes.EditValue))
{
return;
}
var itemId = (long) (cbTemplateTypes.EditValue);
BaseBarcodeReport defaultReport = BarcodeReportGenerator.GenerateBarcodeReport(itemId);
m_DesignController = new DesignController(itemId, defaultReport, FindForm());
BaseBarcodeReport report = m_DesignController.GetClonedReport();
report.InitPrinterSettings();
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
switch (m_Mode)
{
case BarcodeKeeperMode.New:
report.GetNewBarcode(manager, itemId, (int) numQuantity.Value);
break;
case BarcodeKeeperMode.Existing:
report.GetBarcodeById(manager, itemId, m_ObjectIdList);
break;
case BarcodeKeeperMode.SampleNewOrExisting:
((SampleBarcodeReport) report).GetBarcodeBySampleData(m_SamplesList);
break;
}
}
if (reportView1.Report != null)
{
reportView1.Report.PrintingSystem.StartPrint -= PrintingSystem_StartPrint;
}
reportView1.SetReport(report, true);
reportView1.Report.PrintingSystem.StartPrint += PrintingSystem_StartPrint;
reportView1.Zoom = BarcodeZoom;
}
private void PrintingSystem_StartPrint(object sender, PrintDocumentEventArgs e)
{
if (numCopies.Value > 3)
{
numCopies.Value = 3;
}
if (numCopies.Value < 1)
{
numCopies.Value = 1;
}
e.PrintDocument.PrinterSettings.Copies = (short) numCopies.Value;
}
private void BindCbTemplateTypes()
{
cbTemplateTypes.Properties.Columns.Clear();
string caption = EidssMessages.Get("colBarcodeType", "Barcode type");
cbTemplateTypes.Properties.Columns.Add(new LookUpColumnInfo(ColumnNumberName, caption, 200, FormatType.None,
"", true, HorzAlignment.Near));
cbTemplateTypes.Properties.DataSource = GetNumberNamesTable();
cbTemplateTypes.Properties.DisplayMember = ColumnNumberName;
cbTemplateTypes.Properties.ValueMember = ColumnNumberId;
}
private static DataView GetNumberNamesTable()
{
using (DbManagerProxy manager = DbManagerFactory.Factory.Create(ModelUserContext.Instance))
{
using (var adapter = new SqlDataAdapter())
{
SqlCommand command = ((SqlConnection) manager.Connection).CreateCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = "spRepGetNumberNameList";
command.Parameters.Add(new SqlParameter("@LangID",
ModelUserContext.CurrentLanguage));
adapter.SelectCommand = command;
var dataSet = new DataSet();
adapter.Fill(dataSet);
DataTable dataTable = dataSet.Tables[0];
dataTable.PrimaryKey = new[] {dataTable.Columns[ColumnNumberId]};
var dataView = new DataView(dataTable) {Sort = ColumnNumberName};
return dataView;
}
}
}
}
}
| |
using System.Collections.ObjectModel;
using EspaceClient.BackOffice.Silverlight.Business.Interfaces;
using EspaceClient.BackOffice.Silverlight.ViewModels.DtoViewModels;
using nRoute.Components.Composition;
using nRoute.ViewModels;
using OGDC.Silverlight.Toolkit.Services.Services;
using OGDC.Silverlight.Toolkit.ViewModels;
namespace EspaceClient.BackOffice.Silverlight.ViewModels.GestionContenu.Bloc
{
public partial class BlocEntityViewModel : ViewModelBase
{
private readonly IApplicationContext _applicationContext;
private readonly IMessenging _messengingService;
private BlocDtoViewModel _bloc;
private TypeBlocDtoViewModel _typeBloc;
private BlocDtoViewModel _blocVisibilite;
private ObservableCollection<BlocContenuDtoViewModel> _blocContenus;
private ObservableCollection<BlocContenuDtoViewModel> _deletedBlocContenus;
private ObservableCollection<Lien_Bloc_ReferentielDtoViewModel> _blocReferentiels;
private ObservableCollection<Lien_Bloc_ReferentielDtoViewModel> _deletedBlocReferentiels;
private ObservableCollection<Lien_Bloc_CategorieClientDtoViewModel> _blocCategorieClients;
private ObservableCollection<Lien_Bloc_CategorieClientDtoViewModel> _deletedBlocCategorieClients;
[TrackProperty]
public ObservableCollection<Lien_Bloc_CategorieClientDtoViewModel> DeletedBlocCategorieClients
{
get
{
return _deletedBlocCategorieClients;
}
set
{
if (_deletedBlocCategorieClients != value)
{
_deletedBlocCategorieClients = value;
NotifyPropertyChanged(() => DeletedBlocCategorieClients);
}
}
}
[TrackProperty]
public ObservableCollection<Lien_Bloc_CategorieClientDtoViewModel> BlocCategorieClients
{
get
{
return _blocCategorieClients;
}
set
{
if (_blocCategorieClients != value)
{
_blocCategorieClients = value;
NotifyPropertyChanged(() => BlocCategorieClients);
}
}
}
[TrackProperty]
public ObservableCollection<Lien_Bloc_ReferentielDtoViewModel> DeletedBlocReferentiels
{
get
{
return _deletedBlocReferentiels;
}
set
{
if (_deletedBlocReferentiels != value)
{
_deletedBlocReferentiels = value;
NotifyPropertyChanged(() => DeletedBlocReferentiels);
}
}
}
[TrackProperty]
public ObservableCollection<Lien_Bloc_ReferentielDtoViewModel> BlocReferentiels
{
get
{
return _blocReferentiels;
}
set
{
if (_blocReferentiels != value)
{
_blocReferentiels = value;
NotifyPropertyChanged(() => BlocReferentiels);
}
}
}
[TrackProperty]
public ObservableCollection<BlocContenuDtoViewModel> DeletedBlocContenus
{
get
{
return _deletedBlocContenus;
}
set
{
if (_deletedBlocContenus != value)
{
_deletedBlocContenus = value;
NotifyPropertyChanged(() => DeletedBlocContenus);
}
}
}
[TrackProperty]
public ObservableCollection<BlocContenuDtoViewModel> BlocContenus
{
get
{
return _blocContenus;
}
set
{
if (_blocContenus != value)
{
_blocContenus = value;
NotifyPropertyChanged(() => BlocContenus);
}
}
}
[TrackProperty]
public BlocDtoViewModel Bloc
{
get
{
return _bloc;
}
set
{
if (_bloc != value)
{
_bloc = value;
NotifyPropertyChanged(() => Bloc);
}
}
}
[TrackProperty]
public TypeBlocDtoViewModel TypeBloc
{
get
{
return _typeBloc;
}
set
{
if (_typeBloc != value)
{
_typeBloc = value;
NotifyPropertyChanged(() => TypeBloc);
}
}
}
[TrackProperty]
public BlocDtoViewModel BlocVisibilite
{
get
{
return _blocVisibilite;
}
set
{
if (_blocVisibilite != value)
{
_blocVisibilite = value;
NotifyPropertyChanged(() => BlocVisibilite);
}
}
}
[ResolveConstructor]
public BlocEntityViewModel(IApplicationContext applicationContext, IMessenging messengingService)
{
_applicationContext = applicationContext;
_messengingService = messengingService;
InitializeChangeTracker();
}
}
}
| |
/*
* DISCLAIMER
*
* Copyright 2016 ArangoDB GmbH, Cologne, Germany
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Copyright holder is ArangoDB GmbH, Cologne, Germany
*/
namespace ArangoDB.Velocypack
{
using System.Collections.Generic;
using global::ArangoDB.Velocypack.Exceptions;
/// <author>Mark - mark at arangodb.com</author>
public class VPackParser
{
private const char OBJECT_OPEN = '{';
private const char OBJECT_CLOSE = '}';
private const char ARRAY_OPEN = '[';
private const char ARRAY_CLOSE = ']';
private const char FIELD = ':';
private const char SEPARATOR = ',';
private const string NULL = "null";
private const string NON_REPRESENTABLE_TYPE = "(non-representable type)";
private readonly System.Collections.Generic.IDictionary<ValueType
, VPackJsonDeserializer> deserializers;
private readonly System.Collections.Generic.IDictionary<string, IDictionary<ValueType, VPackJsonDeserializer>> deserializersByName;
public VPackParser()
: base()
{
this.deserializers = new System.Collections.Generic.Dictionary<ValueType
, VPackJsonDeserializer>();
this.deserializersByName = new System.Collections.Generic.Dictionary<string, IDictionary<ValueType, VPackJsonDeserializer>>();
}
/// <exception cref="VPackException"/>
public virtual string toJson(VPackSlice vpack)
{
return this.toJson(vpack, false);
}
/// <exception cref="VPackException"/>
public virtual string toJson(VPackSlice vpack, bool includeNullValues
)
{
java.lang.StringBuilder json = new java.lang.StringBuilder();
this.parse(null, null, vpack, json, includeNullValues);
return json.ToString();
}
public virtual VPackParser registerDeserializer(string attribute
, ValueType type, VPackJsonDeserializer
deserializer)
{
System.Collections.Generic.IDictionary<ValueType, VPackJsonDeserializer
> byName = this.deserializersByName[attribute];
if (byName == null)
{
byName = new System.Collections.Generic.Dictionary<ValueType
, VPackJsonDeserializer>();
this.deserializersByName[attribute] = byName;
}
byName[type] = deserializer;
return this;
}
public virtual VPackParser registerDeserializer(ValueType
type, VPackJsonDeserializer deserializer)
{
this.deserializers[type] = deserializer;
return this;
}
private VPackJsonDeserializer getDeserializer(string attribute
, ValueType type)
{
VPackJsonDeserializer deserializer = null;
System.Collections.Generic.IDictionary<ValueType, VPackJsonDeserializer
> byName = this.deserializersByName[attribute];
if (byName != null)
{
deserializer = byName[type];
}
if (deserializer == null)
{
deserializer = this.deserializers[type];
}
return deserializer;
}
/// <exception cref="VPackException"/>
private void parse(VPackSlice parent, string attribute, VPackSlice
value, java.lang.StringBuilder json, bool includeNullValues)
{
VPackJsonDeserializer deserializer = null;
if (attribute != null)
{
appendField(attribute, json);
deserializer = this.getDeserializer(attribute, value.type());
}
if (deserializer != null)
{
deserializer.deserialize(parent, attribute, value, json);
}
else
{
if (value.isObject())
{
this.parseObject(value, json, includeNullValues);
}
else
{
if (value.isArray())
{
this.parseArray(value, json, includeNullValues);
}
else
{
if (value.isBoolean())
{
json.Append(value.getAsBoolean());
}
else
{
if (value.isString())
{
json.Append(org.json.simple.JSONValue.toJSONString(value.getAsString()));
}
else
{
if (value.isNumber())
{
json.Append(value.getAsNumber());
}
else
{
if (value.isNull())
{
json.Append(NULL);
}
else
{
json.Append(org.json.simple.JSONValue.toJSONString(NON_REPRESENTABLE_TYPE));
}
}
}
}
}
}
}
}
private static void appendField(string attribute, java.lang.StringBuilder json)
{
json.Append(org.json.simple.JSONValue.toJSONString(attribute));
json.Append(FIELD);
}
/// <exception cref="VPackException"/>
private void parseObject(VPackSlice value, java.lang.StringBuilder
json, bool includeNullValues)
{
json.Append(OBJECT_OPEN);
int added = 0;
for (System.Collections.Generic.IEnumerator<KeyValuePair<string, VPackSlice>> iterator = value.objectIterator();
iterator.MoveNext();)
{
System.Collections.Generic.KeyValuePair<string, VPackSlice
> next = iterator.Current;
VPackSlice nextValue = next.Value;
if (!nextValue.isNull() || includeNullValues)
{
if (added++ > 0)
{
json.Append(SEPARATOR);
}
this.parse(value, next.Key, nextValue, json, includeNullValues);
}
}
json.Append(OBJECT_CLOSE);
}
/// <exception cref="VPackException"/>
private void parseArray(VPackSlice value, java.lang.StringBuilder
json, bool includeNullValues)
{
json.Append(ARRAY_OPEN);
int added = 0;
for (int i = 0; i < value.getLength(); i++)
{
VPackSlice valueAt = value.get(i);
if (!valueAt.isNull() || includeNullValues)
{
if (added++ > 0)
{
json.Append(SEPARATOR);
}
this.parse(value, null, valueAt, json, includeNullValues);
}
}
json.Append(ARRAY_CLOSE);
}
/// <exception cref="VPackException"/>
public virtual VPackSlice fromJson(string json)
{
return this.fromJson(json, false);
}
/// <exception cref="VPackException"/>
public virtual VPackSlice fromJson(string json, bool includeNullValues
)
{
VPackBuilder builder = new VPackBuilder
();
org.json.simple.parser.JSONParser parser = new org.json.simple.parser.JSONParser(
);
org.json.simple.parser.ContentHandler contentHandler = new VPackParser.VPackContentHandler
(builder, includeNullValues);
try
{
parser.parse(json, contentHandler);
}
catch (org.json.simple.parser.ParseException e)
{
throw new VPackBuilderException(e);
}
return builder.Slice();
}
private class VPackContentHandler : org.json.simple.parser.ContentHandler
{
private readonly VPackBuilder builder;
private string attribute;
private readonly bool includeNullValues;
public VPackContentHandler(VPackBuilder builder, bool includeNullValues
)
{
this.builder = builder;
this.includeNullValues = includeNullValues;
this.attribute = null;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void add(ValueType value)
{
try
{
this.builder.Add(this.attribute, value);
this.attribute = null;
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void add(string value)
{
try
{
this.builder.Add(this.attribute, value);
this.attribute = null;
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void add(bool value)
{
try
{
this.builder.Add(this.attribute, value);
this.attribute = null;
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void add(double value)
{
try
{
this.builder.Add(this.attribute, value);
this.attribute = null;
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void add(long value)
{
try
{
this.builder.Add(this.attribute, value);
this.attribute = null;
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
private void close()
{
try
{
this.builder.Close();
}
catch (VPackBuilderException)
{
throw new org.json.simple.parser.ParseException(org.json.simple.parser.ParseException
.ERROR_UNEXPECTED_EXCEPTION);
}
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual void startJSON()
{
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual void endJSON()
{
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool startObject()
{
this.add(ValueType.OBJECT);
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool endObject()
{
this.close();
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool startObjectEntry(string key)
{
this.attribute = key;
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool endObjectEntry()
{
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool startArray()
{
this.add(ValueType.ARRAY);
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool endArray()
{
this.close();
return true;
}
/// <exception cref="org.json.simple.parser.ParseException"/>
/// <exception cref="System.IO.IOException"/>
public virtual bool primitive(object value)
{
if (value == null)
{
if (this.includeNullValues)
{
this.add(ValueType.NULL);
}
}
else
{
if (typeof(string).isAssignableFrom(Sharpen.Runtime.getClassForObject
(value)))
{
add(typeof(string).cast(value));
}
else
{
if (typeof(bool).isAssignableFrom(Sharpen.Runtime.getClassForObject
(value)))
{
add(typeof(bool).cast(value));
}
else
{
if (typeof(double).isAssignableFrom(Sharpen.Runtime.getClassForObject
(value)))
{
add(typeof(double).cast(value));
}
else
{
if (typeof(java.lang.Number).isAssignableFrom(Sharpen.Runtime.getClassForObject
(value)))
{
add(typeof(long).cast(value));
}
}
}
}
}
return true;
}
}
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.UnitTests
{
using System;
using System.Collections.Generic;
using System.Threading;
using NLog.Common;
using Xunit;
public class AsyncHelperTests : NLogTestBase
{
[Fact]
public void OneTimeOnlyTest1()
{
var exceptions = new List<Exception>();
AsyncContinuation cont = exceptions.Add;
cont = AsyncHelpers.PreventMultipleCalls(cont);
// OneTimeOnly(OneTimeOnly(x)) == OneTimeOnly(x)
var cont2 = AsyncHelpers.PreventMultipleCalls(cont);
Assert.Same(cont, cont2);
var sampleException = new InvalidOperationException("some message");
cont(null);
cont(sampleException);
cont(null);
cont(sampleException);
Assert.Equal(1, exceptions.Count);
Assert.Null(exceptions[0]);
}
[Fact]
public void OneTimeOnlyTest2()
{
var exceptions = new List<Exception>();
AsyncContinuation cont = exceptions.Add;
cont = AsyncHelpers.PreventMultipleCalls(cont);
var sampleException = new InvalidOperationException("some message");
cont(sampleException);
cont(null);
cont(sampleException);
cont(null);
Assert.Equal(1, exceptions.Count);
Assert.Same(sampleException, exceptions[0]);
}
[Fact]
public void OneTimeOnlyExceptionInHandlerTest()
{
LogManager.ThrowExceptions = false;
var exceptions = new List<Exception>();
var sampleException = new InvalidOperationException("some message");
AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; };
cont = AsyncHelpers.PreventMultipleCalls(cont);
cont(null);
cont(null);
cont(null);
Assert.Equal(1, exceptions.Count);
Assert.Null(exceptions[0]);
}
[Fact]
public void OneTimeOnlyExceptionInHandlerTest_RethrowExceptionEnabled()
{
LogManager.ThrowExceptions = true;
var exceptions = new List<Exception>();
var sampleException = new InvalidOperationException("some message");
AsyncContinuation cont = ex => { exceptions.Add(ex); throw sampleException; };
cont = AsyncHelpers.PreventMultipleCalls(cont);
try
{
cont(null);
}
catch{}
try
{
cont(null);
}
catch { }
try
{
cont(null);
}
catch { }
// cleanup
LogManager.ThrowExceptions = false;
Assert.Equal(1, exceptions.Count);
Assert.Null(exceptions[0]);
}
[Fact]
public void ContinuationTimeoutTest()
{
var resetEvent = new ManualResetEvent(false);
var exceptions = new List<Exception>();
// set up a timer to strike in 1 second
var cont = AsyncHelpers.WithTimeout(ex =>
{
exceptions.Add(ex);
resetEvent.Set();
}, TimeSpan.FromMilliseconds(1));
resetEvent.WaitOne(TimeSpan.FromSeconds(1));
// make sure we got timeout exception
Assert.Equal(1, exceptions.Count);
Assert.IsType(typeof(TimeoutException), exceptions[0]);
Assert.Equal("Timeout.", exceptions[0].Message);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.Equal(1, exceptions.Count);
}
[Fact]
public void ContinuationTimeoutNotHitTest()
{
var exceptions = new List<Exception>();
// set up a timer to strike in 1 second
var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromMilliseconds(500));
// call success quickly, hopefully before the timer comes
cont(null);
// sleep 2 seconds to make sure timer event comes
Thread.Sleep(1000);
// make sure we got success, not a timer exception
Assert.Equal(1, exceptions.Count);
Assert.Null(exceptions[0]);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.Equal(1, exceptions.Count);
Assert.Null(exceptions[0]);
}
[Fact]
public void ContinuationErrorTimeoutNotHitTest()
{
var exceptions = new List<Exception>();
// set up a timer to strike in 3 second
var cont = AsyncHelpers.WithTimeout(AsyncHelpers.PreventMultipleCalls(exceptions.Add), TimeSpan.FromSeconds(500));
var exception = new InvalidOperationException("Foo");
// call success quickly, hopefully before the timer comes
cont(exception);
// sleep 2 seconds to make sure timer event comes
Thread.Sleep(1000);
// make sure we got success, not a timer exception
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
Assert.Same(exception, exceptions[0]);
// those will be ignored
cont(null);
cont(new InvalidOperationException("Some exception"));
cont(null);
cont(new InvalidOperationException("Some exception"));
Assert.Equal(1, exceptions.Count);
Assert.NotNull(exceptions[0]);
}
[Fact]
public void RepeatTest1()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
cont(null);
});
Assert.True(finalContinuationInvoked);
Assert.Null(lastException);
Assert.Equal(10, callCount);
}
[Fact]
public void RepeatTest2()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
cont(sampleException);
cont(sampleException);
});
Assert.True(finalContinuationInvoked);
Assert.Same(sampleException, lastException);
Assert.Equal(1, callCount);
}
[Fact]
public void RepeatTest3()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int callCount = 0;
AsyncHelpers.Repeat(10, finalContinuation,
cont =>
{
callCount++;
throw sampleException;
});
Assert.True(finalContinuationInvoked);
Assert.Same(sampleException, lastException);
Assert.Equal(1, callCount);
}
[Fact]
public void ForEachItemSequentiallyTest1()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
cont(null);
cont(null);
});
Assert.True(finalContinuationInvoked);
Assert.Null(lastException);
Assert.Equal(55, sum);
}
[Fact]
public void ForEachItemSequentiallyTest2()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
cont(sampleException);
cont(sampleException);
});
Assert.True(finalContinuationInvoked);
Assert.Same(sampleException, lastException);
Assert.Equal(1, sum);
}
[Fact]
public void ForEachItemSequentiallyTest3()
{
bool finalContinuationInvoked = false;
Exception lastException = null;
Exception sampleException = new InvalidOperationException("Some message");
AsyncContinuation finalContinuation = ex =>
{
finalContinuationInvoked = true;
lastException = ex;
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemSequentially(input, finalContinuation,
(i, cont) =>
{
sum += i;
throw sampleException;
});
Assert.True(finalContinuationInvoked);
Assert.Same(sampleException, lastException);
Assert.Equal(1, sum);
}
[Fact]
public void ForEachItemInParallelEmptyTest()
{
int[] items = new int[0];
Exception lastException = null;
bool finalContinuationInvoked = false;
AsyncContinuation continuation = ex =>
{
lastException = ex;
finalContinuationInvoked = true;
};
AsyncHelpers.ForEachItemInParallel(items, continuation, (i, cont) => { Assert.True(false, "Will not be reached"); });
Assert.True(finalContinuationInvoked);
Assert.Null(lastException);
}
[Fact]
public void ForEachItemInParallelTest()
{
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
lock (input)
{
sum += i;
}
cont(null);
cont(null);
});
finalContinuationInvoked.WaitOne();
Assert.Null(lastException);
Assert.Equal(55, sum);
}
[Fact]
public void ForEachItemInParallelSingleFailureTest()
{
using (new InternalLoggerScope())
{
InternalLogger.LogLevel = LogLevel.Trace;
InternalLogger.LogToConsole = true;
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
Console.WriteLine("Callback on {0}", Thread.CurrentThread.ManagedThreadId);
lock (input)
{
sum += i;
}
if (i == 7)
{
throw new InvalidOperationException("Some failure.");
}
cont(null);
});
finalContinuationInvoked.WaitOne();
Assert.Equal(55, sum);
Assert.NotNull(lastException);
Assert.IsType(typeof(InvalidOperationException), lastException);
Assert.Equal("Some failure.", lastException.Message);
}
}
[Fact]
public void ForEachItemInParallelMultipleFailuresTest()
{
var finalContinuationInvoked = new ManualResetEvent(false);
Exception lastException = null;
AsyncContinuation finalContinuation = ex =>
{
lastException = ex;
finalContinuationInvoked.Set();
};
int sum = 0;
var input = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, };
AsyncHelpers.ForEachItemInParallel(input, finalContinuation,
(i, cont) =>
{
lock (input)
{
sum += i;
}
throw new InvalidOperationException("Some failure.");
});
finalContinuationInvoked.WaitOne();
Assert.Equal(55, sum);
Assert.NotNull(lastException);
Assert.IsType(typeof(NLogRuntimeException), lastException);
Assert.True(lastException.Message.StartsWith("Got multiple exceptions:\r\n"));
}
[Fact]
public void PrecededByTest1()
{
int invokedCount1 = 0;
int invokedCount2 = 0;
int sequence = 7;
int invokedCount1Sequence = 0;
int invokedCount2Sequence = 0;
AsyncContinuation originalContinuation = ex =>
{
invokedCount1++;
invokedCount1Sequence = sequence++;
};
AsynchronousAction doSomethingElse = c =>
{
invokedCount2++;
invokedCount2Sequence = sequence++;
c(null);
c(null);
};
AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse);
cont(null);
// make sure doSomethingElse was invoked first
// then original continuation
Assert.Equal(7, invokedCount2Sequence);
Assert.Equal(8, invokedCount1Sequence);
Assert.Equal(1, invokedCount1);
Assert.Equal(1, invokedCount2);
}
[Fact]
public void PrecededByTest2()
{
int invokedCount1 = 0;
int invokedCount2 = 0;
int sequence = 7;
int invokedCount1Sequence = 0;
int invokedCount2Sequence = 0;
AsyncContinuation originalContinuation = ex =>
{
invokedCount1++;
invokedCount1Sequence = sequence++;
};
AsynchronousAction doSomethingElse = c =>
{
invokedCount2++;
invokedCount2Sequence = sequence++;
c(null);
c(null);
};
AsyncContinuation cont = AsyncHelpers.PrecededBy(originalContinuation, doSomethingElse);
var sampleException = new InvalidOperationException("Some message.");
cont(sampleException);
// make sure doSomethingElse was not invoked
Assert.Equal(0, invokedCount2Sequence);
Assert.Equal(7, invokedCount1Sequence);
Assert.Equal(1, invokedCount1);
Assert.Equal(0, invokedCount2);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Abp;
using Abp.Configuration.Startup;
using Abp.Domain.Uow;
using Abp.Runtime.Session;
using Abp.TestBase;
using Abp.NServiceBus.EntityFramework;
using Abp.NServiceBus.Migrations.SeedData;
using Abp.NServiceBus.MultiTenancy;
using Abp.NServiceBus.Users;
using Castle.MicroKernel.Registration;
using Effort;
using EntityFramework.DynamicFilters;
namespace Abp.NServiceBus.Tests
{
public abstract class NServiceBusTestBase : AbpIntegratedTestBase<NServiceBusTestModule>
{
private DbConnection _hostDb;
private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture
protected NServiceBusTestBase()
{
//Seed initial data for host
AbpSession.TenantId = null;
UsingDbContext(context =>
{
new InitialHostDbBuilder(context).Create();
new DefaultTenantCreator(context).Create();
});
//Seed initial data for default tenant
AbpSession.TenantId = 1;
UsingDbContext(context =>
{
new TenantRoleAndUserBuilder(context, 1).Create();
});
LoginAsDefaultTenantAdmin();
}
protected override void PreInitialize()
{
base.PreInitialize();
/* You can switch database architecture here: */
UseSingleDatabase();
//UseDatabasePerTenant();
}
/* Uses single database for host and all tenants.
*/
private void UseSingleDatabase()
{
_hostDb = DbConnectionFactory.CreateTransient();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod(() => _hostDb)
.LifestyleSingleton()
);
}
/* Uses single database for host and Default tenant,
* but dedicated databases for all other tenants.
*/
private void UseDatabasePerTenant()
{
_hostDb = DbConnectionFactory.CreateTransient();
_tenantDbs = new Dictionary<int, DbConnection>();
LocalIocManager.IocContainer.Register(
Component.For<DbConnection>()
.UsingFactoryMethod((kernel) =>
{
lock (_tenantDbs)
{
var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current;
var abpSession = kernel.Resolve<IAbpSession>();
var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId;
if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db
{
return _hostDb;
}
if (!_tenantDbs.ContainsKey(tenantId.Value))
{
_tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient();
}
return _tenantDbs[tenantId.Value];
}
}, true)
.LifestyleTransient()
);
}
#region UsingDbContext
protected IDisposable UsingTenantId(int? tenantId)
{
var previousTenantId = AbpSession.TenantId;
AbpSession.TenantId = tenantId;
return new DisposeAction(() => AbpSession.TenantId = previousTenantId);
}
protected void UsingDbContext(Action<NServiceBusDbContext> action)
{
UsingDbContext(AbpSession.TenantId, action);
}
protected Task UsingDbContextAsync(Func<NServiceBusDbContext, Task> action)
{
return UsingDbContextAsync(AbpSession.TenantId, action);
}
protected T UsingDbContext<T>(Func<NServiceBusDbContext, T> func)
{
return UsingDbContext(AbpSession.TenantId, func);
}
protected Task<T> UsingDbContextAsync<T>(Func<NServiceBusDbContext, Task<T>> func)
{
return UsingDbContextAsync(AbpSession.TenantId, func);
}
protected void UsingDbContext(int? tenantId, Action<NServiceBusDbContext> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<NServiceBusDbContext>())
{
context.DisableAllFilters();
action(context);
context.SaveChanges();
}
}
}
protected async Task UsingDbContextAsync(int? tenantId, Func<NServiceBusDbContext, Task> action)
{
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<NServiceBusDbContext>())
{
context.DisableAllFilters();
await action(context);
await context.SaveChangesAsync();
}
}
}
protected T UsingDbContext<T>(int? tenantId, Func<NServiceBusDbContext, T> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<NServiceBusDbContext>())
{
context.DisableAllFilters();
result = func(context);
context.SaveChanges();
}
}
return result;
}
protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<NServiceBusDbContext, Task<T>> func)
{
T result;
using (UsingTenantId(tenantId))
{
using (var context = LocalIocManager.Resolve<NServiceBusDbContext>())
{
context.DisableAllFilters();
result = await func(context);
await context.SaveChangesAsync();
}
}
return result;
}
#endregion
#region Login
protected void LoginAsHostAdmin()
{
LoginAsHost(User.AdminUserName);
}
protected void LoginAsDefaultTenantAdmin()
{
LoginAsTenant(Tenant.DefaultTenantName, User.AdminUserName);
}
protected void LoginAsHost(string userName)
{
Resolve<IMultiTenancyConfig>().IsEnabled = true;
AbpSession.TenantId = null;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for host.");
}
AbpSession.UserId = user.Id;
}
protected void LoginAsTenant(string tenancyName, string userName)
{
var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
if (tenant == null)
{
throw new Exception("There is no tenant: " + tenancyName);
}
AbpSession.TenantId = tenant.Id;
var user =
UsingDbContext(
context =>
context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
if (user == null)
{
throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
}
AbpSession.UserId = user.Id;
}
#endregion
/// <summary>
/// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
/// Throws exception if it's null.
/// </summary>
protected async Task<User> GetCurrentUserAsync()
{
var userId = AbpSession.GetUserId();
return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId));
}
/// <summary>
/// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
/// Throws exception if there is no current tenant.
/// </summary>
protected async Task<Tenant> GetCurrentTenantAsync()
{
var tenantId = AbpSession.GetTenantId();
return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId));
}
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.ApiManagement;
using Microsoft.Azure.Management.ApiManagement.SmapiModels;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.ApiManagement
{
/// <summary>
/// Operation to return the status of the most recent synchronization
/// between configuration database and the Git repository.
/// </summary>
internal partial class TenantConfigurationSyncStateOperation : IServiceOperations<ApiManagementClient>, ITenantConfigurationSyncStateOperation
{
/// <summary>
/// Initializes a new instance of the
/// TenantConfigurationSyncStateOperation class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal TenantConfigurationSyncStateOperation(ApiManagementClient client)
{
this._client = client;
}
private ApiManagementClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.ApiManagement.ApiManagementClient.
/// </summary>
public ApiManagementClient Client
{
get { return this._client; }
}
/// <summary>
/// Gets Tenant Configuration Synchronization State operation result.
/// </summary>
/// <param name='resourceGroupName'>
/// Required. The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// Required. The name of the Api Management service.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Get Tenant Configuration Synchronization State response details.
/// </returns>
public async Task<TenantConfigurationSyncStateResponse> GetAsync(string resourceGroupName, string serviceName, CancellationToken cancellationToken)
{
// Validate
if (resourceGroupName == null)
{
throw new ArgumentNullException("resourceGroupName");
}
if (serviceName == null)
{
throw new ArgumentNullException("serviceName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("serviceName", serviceName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/resourceGroups/";
url = url + Uri.EscapeDataString(resourceGroupName);
url = url + "/providers/";
url = url + "Microsoft.ApiManagement";
url = url + "/service/";
url = url + Uri.EscapeDataString(serviceName);
url = url + "/tenant/configuration/syncState";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2014-02-14");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
TenantConfigurationSyncStateResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new TenantConfigurationSyncStateResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
TenantConfigurationSyncStateContract valueInstance = new TenantConfigurationSyncStateContract();
result.Value = valueInstance;
JToken branchValue = responseDoc["branch"];
if (branchValue != null && branchValue.Type != JTokenType.Null)
{
string branchInstance = ((string)branchValue);
valueInstance.Branch = branchInstance;
}
JToken commitIdValue = responseDoc["commitId"];
if (commitIdValue != null && commitIdValue.Type != JTokenType.Null)
{
string commitIdInstance = ((string)commitIdValue);
valueInstance.CommitId = commitIdInstance;
}
JToken isExportValue = responseDoc["isExport"];
if (isExportValue != null && isExportValue.Type != JTokenType.Null)
{
bool isExportInstance = ((bool)isExportValue);
valueInstance.IsExport = isExportInstance;
}
JToken isSyncedValue = responseDoc["isSynced"];
if (isSyncedValue != null && isSyncedValue.Type != JTokenType.Null)
{
bool isSyncedInstance = ((bool)isSyncedValue);
valueInstance.IsSynced = isSyncedInstance;
}
JToken isGitEnabledValue = responseDoc["isGitEnabled"];
if (isGitEnabledValue != null && isGitEnabledValue.Type != JTokenType.Null)
{
bool isGitEnabledInstance = ((bool)isGitEnabledValue);
valueInstance.IsGitEnabled = isGitEnabledInstance;
}
JToken syncDateValue = responseDoc["syncDate"];
if (syncDateValue != null && syncDateValue.Type != JTokenType.Null)
{
DateTime syncDateInstance = ((DateTime)syncDateValue);
valueInstance.SyncDate = syncDateInstance;
}
JToken configurationChangeDateValue = responseDoc["configurationChangeDate"];
if (configurationChangeDateValue != null && configurationChangeDateValue.Type != JTokenType.Null)
{
DateTime configurationChangeDateInstance = ((DateTime)configurationChangeDateValue);
valueInstance.ConfigurationChangeDate = configurationChangeDateInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
/*
* [The "BSD license"]
* Copyright (c) 2013 Terence Parr
* Copyright (c) 2013 Sam Harwell
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.Text;
using System.Collections;
using System.Collections.Generic;
using Antlr4.Runtime;
using Antlr4.Runtime.Atn;
using Antlr4.Runtime.Dfa;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Sharpen;
using Antlr4.Runtime.Tree;
using Antlr4.Runtime.Tree.Pattern;
namespace Antlr4.Runtime
{
/// <summary>This is all the parsing support code essentially; most of it is error recovery stuff.</summary>
/// <remarks>This is all the parsing support code essentially; most of it is error recovery stuff.</remarks>
public abstract class Parser : Recognizer<IToken, ParserATNSimulator>
{
#if !PORTABLE
public class TraceListener : IParseTreeListener
{
public virtual void EnterEveryRule(ParserRuleContext ctx)
{
System.Console.Out.WriteLine("enter " + this._enclosing.RuleNames[ctx.RuleIndex] + ", LT(1)=" + this._enclosing._input.Lt(1).Text);
}
public virtual void ExitEveryRule(ParserRuleContext ctx)
{
System.Console.Out.WriteLine("exit " + this._enclosing.RuleNames[ctx.RuleIndex] + ", LT(1)=" + this._enclosing._input.Lt(1).Text);
}
public virtual void VisitErrorNode(IErrorNode node)
{
}
public virtual void VisitTerminal(ITerminalNode node)
{
ParserRuleContext parent = (ParserRuleContext)((IRuleNode)node.Parent).RuleContext;
IToken token = node.Symbol;
System.Console.Out.WriteLine("consume " + token + " rule " + this._enclosing.RuleNames[parent.RuleIndex]);
}
internal TraceListener(Parser _enclosing)
{
this._enclosing = _enclosing;
}
private readonly Parser _enclosing;
}
#endif
public class TrimToSizeListener : IParseTreeListener
{
public static readonly Parser.TrimToSizeListener Instance = new Parser.TrimToSizeListener();
public virtual void VisitTerminal(ITerminalNode node)
{
}
public virtual void VisitErrorNode(IErrorNode node)
{
}
public virtual void EnterEveryRule(ParserRuleContext ctx)
{
}
public virtual void ExitEveryRule(ParserRuleContext ctx)
{
if (ctx.children is List<IParseTree>)
{
((List<IParseTree>)ctx.children).TrimExcess();
}
}
}
/// <summary>
/// This field maps from the serialized ATN string to the deserialized
/// <see cref="Antlr4.Runtime.Atn.ATN"/>
/// with
/// bypass alternatives.
/// </summary>
/// <seealso cref="Antlr4.Runtime.Atn.ATNDeserializationOptions.GenerateRuleBypassTransitions()"/>
private static readonly IDictionary<string, ATN> bypassAltsAtnCache = new Dictionary<string, ATN>();
/// <summary>The error handling strategy for the parser.</summary>
/// <remarks>
/// The error handling strategy for the parser. The default value is a new
/// instance of
/// <see cref="DefaultErrorStrategy"/>
/// .
/// </remarks>
/// <seealso cref="ErrorHandler"/>
[NotNull]
private IAntlrErrorStrategy _errHandler = new DefaultErrorStrategy();
/// <summary>The input stream.</summary>
/// <remarks>The input stream.</remarks>
/// <seealso cref="InputStream()"/>
private ITokenStream _input;
private readonly List<int> _precedenceStack = new List<int> { 0 };
/// <summary>
/// The
/// <see cref="ParserRuleContext"/>
/// object for the currently executing rule.
/// This is always non-null during the parsing process.
/// </summary>
private ParserRuleContext _ctx;
/// <summary>
/// Specifies whether or not the parser should construct a parse tree during
/// the parsing process.
/// </summary>
/// <remarks>
/// Specifies whether or not the parser should construct a parse tree during
/// the parsing process. The default value is
/// <see langword="true"/>
/// .
/// </remarks>
/// <seealso cref="BuildParseTree"/>
private bool _buildParseTrees = true;
#if !PORTABLE
/// <summary>
/// When
/// <see cref="Trace"/>
/// <c>(true)</c>
/// is called, a reference to the
/// <see cref="TraceListener"/>
/// is stored here so it can be easily removed in a
/// later call to
/// <see cref="Trace"/>
/// <c>(false)</c>
/// . The listener itself is
/// implemented as a parser listener so this field is not directly used by
/// other parser methods.
/// </summary>
private Parser.TraceListener _tracer;
#endif
/// <summary>
/// The list of
/// <see cref="Antlr4.Runtime.Tree.IParseTreeListener"/>
/// listeners registered to receive
/// events during the parse.
/// </summary>
/// <seealso cref="AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)"/>
[Nullable]
private IList<IParseTreeListener> _parseListeners;
/// <summary>The number of syntax errors reported during parsing.</summary>
/// <remarks>
/// The number of syntax errors reported during parsing. This value is
/// incremented each time
/// <see cref="NotifyErrorListeners(string)"/>
/// is called.
/// </remarks>
private int _syntaxErrors;
public Parser(ITokenStream input)
{
TokenStream = input;
}
/// <summary>reset the parser's state</summary>
public virtual void Reset()
{
if (((ITokenStream)InputStream) != null)
{
((ITokenStream)InputStream).Seek(0);
}
_errHandler.Reset(this);
_ctx = null;
_syntaxErrors = 0;
#if !PORTABLE
Trace = false;
#endif
_precedenceStack.Clear();
_precedenceStack.Add(0);
ATNSimulator interpreter = Interpreter;
if (interpreter != null)
{
interpreter.Reset();
}
}
/// <summary>
/// Match current input symbol against
/// <paramref name="ttype"/>
/// . If the symbol type
/// matches,
/// <see cref="IAntlrErrorStrategy.ReportMatch(Parser)"/>
/// and
/// <see cref="Consume()"/>
/// are
/// called to complete the match process.
/// <p>If the symbol type does not match,
/// <see cref="IAntlrErrorStrategy.RecoverInline(Parser)"/>
/// is called on the current error
/// strategy to attempt recovery. If
/// <see cref="BuildParseTree()"/>
/// is
/// <see langword="true"/>
/// and the token index of the symbol returned by
/// <see cref="IAntlrErrorStrategy.RecoverInline(Parser)"/>
/// is -1, the symbol is added to
/// the parse tree by calling
/// <see cref="ParserRuleContext.AddErrorNode(IToken)"/>
/// .</p>
/// </summary>
/// <param name="ttype">the token type to match</param>
/// <returns>the matched symbol</returns>
/// <exception cref="RecognitionException">
/// if the current input symbol did not match
/// <paramref name="ttype"/>
/// and the error strategy could not recover from the
/// mismatched symbol
/// </exception>
/// <exception cref="Antlr4.Runtime.RecognitionException"/>
[return: NotNull]
public virtual IToken Match(int ttype)
{
IToken t = CurrentToken;
if (t.Type == ttype)
{
_errHandler.ReportMatch(this);
Consume();
}
else
{
t = _errHandler.RecoverInline(this);
if (_buildParseTrees && t.TokenIndex == -1)
{
// we must have conjured up a new token during single token insertion
// if it's not the current symbol
_ctx.AddErrorNode(t);
}
}
return t;
}
/// <summary>Match current input symbol as a wildcard.</summary>
/// <remarks>
/// Match current input symbol as a wildcard. If the symbol type matches
/// (i.e. has a value greater than 0),
/// <see cref="IAntlrErrorStrategy.ReportMatch(Parser)"/>
/// and
/// <see cref="Consume()"/>
/// are called to complete the match process.
/// <p>If the symbol type does not match,
/// <see cref="IAntlrErrorStrategy.RecoverInline(Parser)"/>
/// is called on the current error
/// strategy to attempt recovery. If
/// <see cref="BuildParseTree()"/>
/// is
/// <see langword="true"/>
/// and the token index of the symbol returned by
/// <see cref="IAntlrErrorStrategy.RecoverInline(Parser)"/>
/// is -1, the symbol is added to
/// the parse tree by calling
/// <see cref="ParserRuleContext.AddErrorNode(IToken)"/>
/// .</p>
/// </remarks>
/// <returns>the matched symbol</returns>
/// <exception cref="RecognitionException">
/// if the current input symbol did not match
/// a wildcard and the error strategy could not recover from the mismatched
/// symbol
/// </exception>
/// <exception cref="Antlr4.Runtime.RecognitionException"/>
[return: NotNull]
public virtual IToken MatchWildcard()
{
IToken t = CurrentToken;
if (t.Type > 0)
{
_errHandler.ReportMatch(this);
Consume();
}
else
{
t = _errHandler.RecoverInline(this);
if (_buildParseTrees && t.TokenIndex == -1)
{
// we must have conjured up a new token during single token insertion
// if it's not the current symbol
_ctx.AddErrorNode(t);
}
}
return t;
}
/// <summary>
/// Track the
/// <see cref="ParserRuleContext"/>
/// objects during the parse and hook
/// them up using the
/// <see cref="ParserRuleContext.children"/>
/// list so that it
/// forms a parse tree. The
/// <see cref="ParserRuleContext"/>
/// returned from the start
/// rule represents the root of the parse tree.
/// <p>Note that if we are not building parse trees, rule contexts only point
/// upwards. When a rule exits, it returns the context but that gets garbage
/// collected if nobody holds a reference. It points upwards but nobody
/// points at it.</p>
/// <p>When we build parse trees, we are adding all of these contexts to
/// <see cref="ParserRuleContext.children"/>
/// list. Contexts are then not candidates
/// for garbage collection.</p>
/// </summary>
/// <summary>
/// Gets whether or not a complete parse tree will be constructed while
/// parsing.
/// </summary>
/// <remarks>
/// Gets whether or not a complete parse tree will be constructed while
/// parsing. This property is
/// <see langword="true"/>
/// for a newly constructed parser.
/// </remarks>
/// <returns>
///
/// <see langword="true"/>
/// if a complete parse tree will be constructed while
/// parsing, otherwise
/// <see langword="false"/>
/// </returns>
public virtual bool BuildParseTree
{
get
{
return _buildParseTrees;
}
set
{
this._buildParseTrees = value;
}
}
/// <summary>Trim the internal lists of the parse tree during parsing to conserve memory.</summary>
/// <remarks>
/// Trim the internal lists of the parse tree during parsing to conserve memory.
/// This property is set to
/// <see langword="false"/>
/// by default for a newly constructed parser.
/// </remarks>
/// <value>
///
/// <see langword="true"/>
/// to trim the capacity of the
/// <see cref="ParserRuleContext.children"/>
/// list to its size after a rule is parsed.
/// </value>
/// <returns>
///
/// <see langword="true"/>
/// if the
/// <see cref="ParserRuleContext.children"/>
/// list is trimmed
/// using the default
/// <see cref="TrimToSizeListener"/>
/// during the parse process.
/// </returns>
public virtual bool TrimParseTree
{
get
{
return ParseListeners.Contains(Parser.TrimToSizeListener.Instance);
}
set
{
bool trimParseTrees = value;
if (trimParseTrees)
{
if (TrimParseTree)
{
return;
}
AddParseListener(Parser.TrimToSizeListener.Instance);
}
else
{
RemoveParseListener(Parser.TrimToSizeListener.Instance);
}
}
}
public virtual IList<IParseTreeListener> ParseListeners
{
get
{
IList<IParseTreeListener> listeners = _parseListeners;
if (listeners == null)
{
return Sharpen.Collections.EmptyList<IParseTreeListener>();
}
return listeners;
}
}
/// <summary>
/// Registers
/// <paramref name="listener"/>
/// to receive events during the parsing process.
/// <p>To support output-preserving grammar transformations (including but not
/// limited to left-recursion removal, automated left-factoring, and
/// optimized code generation), calls to listener methods during the parse
/// may differ substantially from calls made by
/// <see cref="Antlr4.Runtime.Tree.ParseTreeWalker.Default"/>
/// used after the parse is complete. In
/// particular, rule entry and exit events may occur in a different order
/// during the parse than after the parser. In addition, calls to certain
/// rule entry methods may be omitted.</p>
/// <p>With the following specific exceptions, calls to listener events are
/// <em>deterministic</em>, i.e. for identical input the calls to listener
/// methods will be the same.</p>
/// <ul>
/// <li>Alterations to the grammar used to generate code may change the
/// behavior of the listener calls.</li>
/// <li>Alterations to the command line options passed to ANTLR 4 when
/// generating the parser may change the behavior of the listener calls.</li>
/// <li>Changing the version of the ANTLR Tool used to generate the parser
/// may change the behavior of the listener calls.</li>
/// </ul>
/// </summary>
/// <param name="listener">the listener to add</param>
/// <exception cref="System.ArgumentNullException">
/// if
/// <c/>
/// listener is
/// <see langword="null"/>
/// </exception>
public virtual void AddParseListener(IParseTreeListener listener)
{
if (listener == null)
{
throw new ArgumentNullException("listener");
}
if (_parseListeners == null)
{
_parseListeners = new List<IParseTreeListener>();
}
this._parseListeners.Add(listener);
}
/// <summary>
/// Remove
/// <paramref name="listener"/>
/// from the list of parse listeners.
/// <p>If
/// <paramref name="listener"/>
/// is
/// <see langword="null"/>
/// or has not been added as a parse
/// listener, this method does nothing.</p>
/// </summary>
/// <seealso cref="AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)"/>
/// <param name="listener">the listener to remove</param>
public virtual void RemoveParseListener(IParseTreeListener listener)
{
if (_parseListeners != null)
{
if (_parseListeners.Remove(listener))
{
if (_parseListeners.Count == 0)
{
_parseListeners = null;
}
}
}
}
/// <summary>Remove all parse listeners.</summary>
/// <remarks>Remove all parse listeners.</remarks>
/// <seealso cref="AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)"/>
public virtual void RemoveParseListeners()
{
_parseListeners = null;
}
/// <summary>Notify any parse listeners of an enter rule event.</summary>
/// <remarks>Notify any parse listeners of an enter rule event.</remarks>
/// <seealso cref="AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)"/>
protected internal virtual void TriggerEnterRuleEvent()
{
foreach (IParseTreeListener listener in _parseListeners)
{
listener.EnterEveryRule(_ctx);
_ctx.EnterRule(listener);
}
}
/// <summary>Notify any parse listeners of an exit rule event.</summary>
/// <remarks>Notify any parse listeners of an exit rule event.</remarks>
/// <seealso cref="AddParseListener(Antlr4.Runtime.Tree.IParseTreeListener)"/>
protected internal virtual void TriggerExitRuleEvent()
{
// reverse order walk of listeners
if (_parseListeners != null) {
for (int i = _parseListeners.Count - 1; i >= 0; i--) {
IParseTreeListener listener = _parseListeners [i];
_ctx.ExitRule (listener);
listener.ExitEveryRule (_ctx);
}
}
}
/// <summary>Gets the number of syntax errors reported during parsing.</summary>
/// <remarks>
/// Gets the number of syntax errors reported during parsing. This value is
/// incremented each time
/// <see cref="NotifyErrorListeners(string)"/>
/// is called.
/// </remarks>
/// <seealso cref="NotifyErrorListeners(string)"/>
public virtual int NumberOfSyntaxErrors
{
get
{
return _syntaxErrors;
}
}
public virtual ITokenFactory TokenFactory
{
get
{
return _input.TokenSource.TokenFactory;
}
}
/// <summary>
/// The ATN with bypass alternatives is expensive to create so we create it
/// lazily.
/// </summary>
/// <remarks>
/// The ATN with bypass alternatives is expensive to create so we create it
/// lazily.
/// </remarks>
/// <exception cref="System.NotSupportedException">
/// if the current parser does not
/// implement the
/// <see cref="Recognizer{Symbol, ATNInterpreter}.SerializedAtn()"/>
/// method.
/// </exception>
[return: NotNull]
public virtual ATN GetATNWithBypassAlts()
{
string serializedAtn = SerializedAtn;
if (serializedAtn == null)
{
throw new NotSupportedException("The current parser does not support an ATN with bypass alternatives.");
}
lock (bypassAltsAtnCache)
{
ATN result = bypassAltsAtnCache.Get(serializedAtn);
if (result == null)
{
ATNDeserializationOptions deserializationOptions = new ATNDeserializationOptions();
deserializationOptions.GenerateRuleBypassTransitions = true;
result = new ATNDeserializer(deserializationOptions).Deserialize(serializedAtn.ToCharArray());
bypassAltsAtnCache.Put(serializedAtn, result);
}
return result;
}
}
/// <summary>The preferred method of getting a tree pattern.</summary>
/// <remarks>
/// The preferred method of getting a tree pattern. For example, here's a
/// sample use:
/// <pre>
/// ParseTree t = parser.expr();
/// ParseTreePattern p = parser.compileParseTreePattern("<ID>+0", MyParser.RULE_expr);
/// ParseTreeMatch m = p.match(t);
/// String id = m.get("ID");
/// </pre>
/// </remarks>
public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex)
{
if (((ITokenStream)InputStream) != null)
{
ITokenSource tokenSource = ((ITokenStream)InputStream).TokenSource;
if (tokenSource is Lexer)
{
Lexer lexer = (Lexer)tokenSource;
return CompileParseTreePattern(pattern, patternRuleIndex, lexer);
}
}
throw new NotSupportedException("Parser can't discover a lexer to use");
}
/// <summary>
/// The same as
/// <see cref="CompileParseTreePattern(string, int)"/>
/// but specify a
/// <see cref="Lexer"/>
/// rather than trying to deduce it from this parser.
/// </summary>
public virtual ParseTreePattern CompileParseTreePattern(string pattern, int patternRuleIndex, Lexer lexer)
{
ParseTreePatternMatcher m = new ParseTreePatternMatcher(lexer, this);
return m.Compile(pattern, patternRuleIndex);
}
public virtual IAntlrErrorStrategy ErrorHandler
{
get
{
return _errHandler;
}
set
{
IAntlrErrorStrategy handler = value;
this._errHandler = handler;
}
}
public override IIntStream InputStream
{
get
{
return _input;
}
}
public ITokenStream TokenStream
{
get
{
return _input;
}
set
{
this._input = null;
Reset ();
this._input = value;
}
}
/// <summary>
/// Match needs to return the current input symbol, which gets put
/// into the label for the associated token ref; e.g., x=ID.
/// </summary>
/// <remarks>
/// Match needs to return the current input symbol, which gets put
/// into the label for the associated token ref; e.g., x=ID.
/// </remarks>
public virtual IToken CurrentToken
{
get
{
return _input.Lt(1);
}
}
public void NotifyErrorListeners(string msg)
{
NotifyErrorListeners(CurrentToken, msg, null);
}
public virtual void NotifyErrorListeners(IToken offendingToken, string msg, RecognitionException e)
{
_syntaxErrors++;
int line = -1;
int charPositionInLine = -1;
if (offendingToken != null)
{
line = offendingToken.Line;
charPositionInLine = offendingToken.Column;
}
IAntlrErrorListener<IToken> listener = ((IParserErrorListener)ErrorListenerDispatch);
listener.SyntaxError(this, offendingToken, line, charPositionInLine, msg, e);
}
/// <summary>
/// Consume and return the
/// <linkplain>
/// #getCurrentToken
/// current symbol
/// </linkplain>
/// .
/// <p>E.g., given the following input with
/// <c>A</c>
/// being the current
/// lookahead symbol, this function moves the cursor to
/// <c>B</c>
/// and returns
/// <c>A</c>
/// .</p>
/// <pre>
/// A B
/// ^
/// </pre>
/// If the parser is not in error recovery mode, the consumed symbol is added
/// to the parse tree using
/// <see cref="ParserRuleContext.AddChild(IToken)"/>
/// , and
/// <see cref="Antlr4.Runtime.Tree.IParseTreeListener.VisitTerminal(Antlr4.Runtime.Tree.ITerminalNode)"/>
/// is called on any parse listeners.
/// If the parser <em>is</em> in error recovery mode, the consumed symbol is
/// added to the parse tree using
/// <see cref="ParserRuleContext.AddErrorNode(IToken)"/>
/// , and
/// <see cref="Antlr4.Runtime.Tree.IParseTreeListener.VisitErrorNode(Antlr4.Runtime.Tree.IErrorNode)"/>
/// is called on any parse
/// listeners.
/// </summary>
public virtual IToken Consume()
{
IToken o = CurrentToken;
if (o.Type != Eof)
{
((ITokenStream)InputStream).Consume();
}
bool hasListener = _parseListeners != null && _parseListeners.Count != 0;
if (_buildParseTrees || hasListener)
{
if (_errHandler.InErrorRecoveryMode(this))
{
IErrorNode node = _ctx.AddErrorNode(o);
if (_parseListeners != null)
{
foreach (IParseTreeListener listener in _parseListeners)
{
listener.VisitErrorNode(node);
}
}
}
else
{
ITerminalNode node = _ctx.AddChild(o);
if (_parseListeners != null)
{
foreach (IParseTreeListener listener in _parseListeners)
{
listener.VisitTerminal(node);
}
}
}
}
return o;
}
protected internal virtual void AddContextToParseTree()
{
ParserRuleContext parent = (ParserRuleContext)_ctx.Parent;
// add current context to parent if we have a parent
if (parent != null)
{
parent.AddChild(_ctx);
}
}
/// <summary>Always called by generated parsers upon entry to a rule.</summary>
/// <remarks>
/// Always called by generated parsers upon entry to a rule. Access field
/// <see cref="_ctx"/>
/// get the current context.
/// </remarks>
public virtual void EnterRule(ParserRuleContext localctx, int state, int ruleIndex)
{
State = state;
_ctx = localctx;
_ctx.Start = _input.Lt(1);
if (_buildParseTrees)
{
AddContextToParseTree();
}
if (_parseListeners != null)
{
TriggerEnterRuleEvent();
}
}
public virtual void EnterLeftFactoredRule(ParserRuleContext localctx, int state, int ruleIndex)
{
State = state;
if (_buildParseTrees)
{
ParserRuleContext factoredContext = (ParserRuleContext)_ctx.GetChild(_ctx.ChildCount - 1);
_ctx.RemoveLastChild();
factoredContext.Parent = localctx;
localctx.AddChild(factoredContext);
}
_ctx = localctx;
_ctx.Start = _input.Lt(1);
if (_buildParseTrees)
{
AddContextToParseTree();
}
if (_parseListeners != null)
{
TriggerEnterRuleEvent();
}
}
public virtual void ExitRule()
{
_ctx.Stop = _input.Lt(-1);
// trigger event on _ctx, before it reverts to parent
if (_parseListeners != null)
{
TriggerExitRuleEvent();
}
State = _ctx.invokingState;
_ctx = (ParserRuleContext)_ctx.Parent;
}
public virtual void EnterOuterAlt(ParserRuleContext localctx, int altNum)
{
// if we have new localctx, make sure we replace existing ctx
// that is previous child of parse tree
if (_buildParseTrees && _ctx != localctx)
{
ParserRuleContext parent = (ParserRuleContext)_ctx.Parent;
if (parent != null)
{
parent.RemoveLastChild();
parent.AddChild(localctx);
}
}
_ctx = localctx;
}
/// <summary>Get the precedence level for the top-most precedence rule.</summary>
/// <remarks>Get the precedence level for the top-most precedence rule.</remarks>
/// <returns>
/// The precedence level for the top-most precedence rule, or -1 if
/// the parser context is not nested within a precedence rule.
/// </returns>
public int Precedence
{
get
{
if (_precedenceStack.Count == 0)
{
return -1;
}
return _precedenceStack[_precedenceStack.Count - 1];
}
}
[Obsolete(@"UseEnterRecursionRule(ParserRuleContext, int, int, int) instead.")]
public virtual void EnterRecursionRule(ParserRuleContext localctx, int ruleIndex)
{
EnterRecursionRule(localctx, Atn.ruleToStartState[ruleIndex].stateNumber, ruleIndex, 0);
}
public virtual void EnterRecursionRule(ParserRuleContext localctx, int state, int ruleIndex, int precedence)
{
State = state;
_precedenceStack.Add(precedence);
_ctx = localctx;
_ctx.Start = _input.Lt(1);
if (_parseListeners != null)
{
TriggerEnterRuleEvent();
}
}
// simulates rule entry for left-recursive rules
/// <summary>
/// Like
/// <see cref="EnterRule(ParserRuleContext, int, int)"/>
/// but for recursive rules.
/// </summary>
public virtual void PushNewRecursionContext(ParserRuleContext localctx, int state, int ruleIndex)
{
ParserRuleContext previous = _ctx;
previous.Parent = localctx;
previous.invokingState = state;
previous.Stop = _input.Lt(-1);
_ctx = localctx;
_ctx.Start = previous.Start;
if (_buildParseTrees)
{
_ctx.AddChild(previous);
}
if (_parseListeners != null)
{
TriggerEnterRuleEvent();
}
}
// simulates rule entry for left-recursive rules
public virtual void UnrollRecursionContexts(ParserRuleContext _parentctx)
{
_precedenceStack.RemoveAt(_precedenceStack.Count - 1);
_ctx.Stop = _input.Lt(-1);
ParserRuleContext retctx = _ctx;
// save current ctx (return value)
// unroll so _ctx is as it was before call to recursive method
if (_parseListeners != null)
{
while (_ctx != _parentctx)
{
TriggerExitRuleEvent();
_ctx = (ParserRuleContext)_ctx.Parent;
}
}
else
{
_ctx = _parentctx;
}
// hook into tree
retctx.Parent = _parentctx;
if (_buildParseTrees && _parentctx != null)
{
// add return ctx into invoking rule's tree
_parentctx.AddChild(retctx);
}
}
public virtual ParserRuleContext GetInvokingContext(int ruleIndex)
{
ParserRuleContext p = _ctx;
while (p != null)
{
if (p.RuleIndex == ruleIndex)
{
return p;
}
p = (ParserRuleContext)p.Parent;
}
return null;
}
public virtual ParserRuleContext Context
{
get
{
return _ctx;
}
set
{
ParserRuleContext ctx = value;
_ctx = ctx;
}
}
public override bool Precpred(RuleContext localctx, int precedence)
{
return precedence >= _precedenceStack[_precedenceStack.Count - 1];
}
public override IAntlrErrorListener<IToken> ErrorListenerDispatch
{
get
{
return new ProxyParserErrorListener(ErrorListeners);
}
}
public virtual bool InContext(string context)
{
// TODO: useful in parser?
return false;
}
/// <summary>
/// Checks whether or not
/// <paramref name="symbol"/>
/// can follow the current state in the
/// ATN. The behavior of this method is equivalent to the following, but is
/// implemented such that the complete context-sensitive follow set does not
/// need to be explicitly constructed.
/// <pre>
/// return getExpectedTokens().contains(symbol);
/// </pre>
/// </summary>
/// <param name="symbol">the symbol type to check</param>
/// <returns>
///
/// <see langword="true"/>
/// if
/// <paramref name="symbol"/>
/// can follow the current state in
/// the ATN, otherwise
/// <see langword="false"/>
/// .
/// </returns>
public virtual bool IsExpectedToken(int symbol)
{
// return getInterpreter().atn.nextTokens(_ctx);
ATN atn = Interpreter.atn;
ParserRuleContext ctx = _ctx;
ATNState s = atn.states[State];
IntervalSet following = atn.NextTokens(s);
if (following.Contains(symbol))
{
return true;
}
// System.out.println("following "+s+"="+following);
if (!following.Contains(TokenConstants.Epsilon))
{
return false;
}
while (ctx != null && ctx.invokingState >= 0 && following.Contains(TokenConstants.Epsilon))
{
ATNState invokingState = atn.states[ctx.invokingState];
RuleTransition rt = (RuleTransition)invokingState.Transition(0);
following = atn.NextTokens(rt.followState);
if (following.Contains(symbol))
{
return true;
}
ctx = (ParserRuleContext)ctx.Parent;
}
if (following.Contains(TokenConstants.Epsilon) && symbol == TokenConstants.Eof)
{
return true;
}
return false;
}
/// <summary>
/// Computes the set of input symbols which could follow the current parser
/// state and context, as given by
/// <see cref="Recognizer{Symbol, ATNInterpreter}.State()"/>
/// and
/// <see cref="Context()"/>
/// ,
/// respectively.
/// </summary>
/// <seealso cref="Antlr4.Runtime.Atn.ATN.GetExpectedTokens(int, RuleContext)"/>
[return: NotNull]
public virtual IntervalSet GetExpectedTokens()
{
return Atn.GetExpectedTokens(State, Context);
}
[return: NotNull]
public virtual IntervalSet GetExpectedTokensWithinCurrentRule()
{
ATN atn = Interpreter.atn;
ATNState s = atn.states[State];
return atn.NextTokens(s);
}
/// <summary>
/// Get a rule's index (i.e.,
/// <c>RULE_ruleName</c>
/// field) or -1 if not found.
/// </summary>
public virtual int GetRuleIndex(string ruleName)
{
int ruleIndex;
if (RuleIndexMap.TryGetValue(ruleName, out ruleIndex))
{
return ruleIndex;
}
return -1;
}
public virtual ParserRuleContext RuleContext
{
get
{
return _ctx;
}
}
/// <summary>
/// Return List<String> of the rule names in your parser instance
/// leading up to a call to the current rule.
/// </summary>
/// <remarks>
/// Return List<String> of the rule names in your parser instance
/// leading up to a call to the current rule. You could override if
/// you want more details such as the file/line info of where
/// in the ATN a rule is invoked.
/// This is very useful for error messages.
/// </remarks>
public virtual IList<string> GetRuleInvocationStack()
{
return GetRuleInvocationStack(_ctx);
}
public virtual string GetRuleInvocationStackAsString()
{
StringBuilder sb = new StringBuilder ("[");
foreach (string s in GetRuleInvocationStack()) {
sb.Append (s);
sb.Append (", ");
}
sb.Length = sb.Length - 2;
sb.Append ("]");
return sb.ToString ();
}
public virtual IList<string> GetRuleInvocationStack(RuleContext p)
{
string[] ruleNames = RuleNames;
IList<string> stack = new List<string>();
while (p != null)
{
// compute what follows who invoked us
int ruleIndex = p.RuleIndex;
if (ruleIndex < 0)
{
stack.Add("n/a");
}
else
{
stack.Add(ruleNames[ruleIndex]);
}
p = p.Parent;
}
return stack;
}
/// <summary>For debugging and other purposes.</summary>
/// <remarks>For debugging and other purposes.</remarks>
public virtual IList<string> GetDFAStrings()
{
IList<string> s = new List<string>();
for (int d = 0; d < Interpreter.atn.decisionToDFA.Length; d++)
{
DFA dfa = Interpreter.atn.decisionToDFA[d];
s.Add(dfa.ToString(Vocabulary, RuleNames));
}
return s;
}
#if !PORTABLE
/// <summary>For debugging and other purposes.</summary>
/// <remarks>For debugging and other purposes.</remarks>
public virtual void DumpDFA()
{
bool seenOne = false;
for (int d = 0; d < Interpreter.atn.decisionToDFA.Length; d++)
{
DFA dfa = Interpreter.atn.decisionToDFA[d];
if (!dfa.IsEmpty)
{
if (seenOne)
{
System.Console.Out.WriteLine();
}
System.Console.Out.WriteLine("Decision " + dfa.decision + ":");
System.Console.Out.Write(dfa.ToString(Vocabulary, RuleNames));
seenOne = true;
}
}
}
#endif
public virtual string SourceName
{
get
{
return _input.SourceName;
}
}
public override ParseInfo ParseInfo
{
get
{
ParserATNSimulator interp = Interpreter;
if (interp is ProfilingATNSimulator)
{
return new ParseInfo((ProfilingATNSimulator)interp);
}
return null;
}
}
/// <since>4.3</since>
public virtual bool Profile
{
set
{
bool profile = value;
ParserATNSimulator interp = Interpreter;
if (profile)
{
if (!(interp is ProfilingATNSimulator))
{
Interpreter = new ProfilingATNSimulator(this);
}
}
else
{
if (interp is ProfilingATNSimulator)
{
Interpreter = new ParserATNSimulator(this, Atn);
}
}
}
}
#if !PORTABLE
/// <summary>
/// During a parse is sometimes useful to listen in on the rule entry and exit
/// events as well as token matches.
/// </summary>
/// <remarks>
/// During a parse is sometimes useful to listen in on the rule entry and exit
/// events as well as token matches. This is for quick and dirty debugging.
/// </remarks>
public virtual bool Trace
{
get
{
foreach (object o in ParseListeners)
{
if (o is Parser.TraceListener)
{
return true;
}
}
return false;
}
set
{
bool trace = value;
if (!trace)
{
RemoveParseListener(_tracer);
_tracer = null;
}
else
{
if (_tracer != null)
{
RemoveParseListener(_tracer);
}
else
{
_tracer = new Parser.TraceListener(this);
}
AddParseListener(_tracer);
}
}
}
#endif
}
}
| |
//
// Encog(tm) Core v3.2 - .Net Version
// http://www.heatonresearch.com/encog/
//
// Copyright 2008-2014 Heaton Research, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// For more information on Heaton Research copyrights, licenses
// and trademarks visit:
// http://www.heatonresearch.com/copyright
//
using System;
namespace Encog.Engine.Network.Activation
{
/// <summary>
/// A ramp activation function. This function has a high and low threshold. If
/// the high threshold is exceeded a fixed value is returned. Likewise, if the
/// low value is exceeded another fixed value is returned.
/// </summary>
[Serializable]
public class ActivationRamp : IActivationFunction
{
/// <summary>
/// The ramp high threshold parameter.
/// </summary>
///
public const int ParamRampHighThreshold = 0;
/// <summary>
/// The ramp low threshold parameter.
/// </summary>
///
public const int ParamRampLowThreshold = 1;
/// <summary>
/// The ramp high parameter.
/// </summary>
///
public const int ParamRampHigh = 2;
/// <summary>
/// The ramp low parameter.
/// </summary>
///
public const int ParamRampLow = 3;
/// <summary>
/// The parameters.
/// </summary>
///
private readonly double[] _paras;
/// <summary>
/// Construct a ramp activation function.
/// </summary>
///
/// <param name="thresholdHigh">The high threshold value.</param>
/// <param name="thresholdLow">The low threshold value.</param>
/// <param name="high">The high value, replaced if the high threshold is exceeded.</param>
/// <param name="low">The low value, replaced if the low threshold is exceeded.</param>
public ActivationRamp(double thresholdHigh,
double thresholdLow, double high, double low)
{
_paras = new double[4];
_paras[ParamRampHighThreshold] = thresholdHigh;
_paras[ParamRampLowThreshold] = thresholdLow;
_paras[ParamRampHigh] = high;
_paras[ParamRampLow] = low;
}
/// <summary>
/// Default constructor.
/// </summary>
///
public ActivationRamp()
: this(1, 0, 1, 0)
{
}
/// <summary>
/// Clone the object.
/// </summary>
/// <returns>The cloned object.</returns>
public object Clone()
{
return new ActivationRamp(
_paras[ParamRampHighThreshold],
_paras[ParamRampLowThreshold],
_paras[ParamRampHigh],
_paras[ParamRampLow]);
}
/// <summary>
/// The high value.
/// </summary>
public double High
{
get { return _paras[ParamRampHigh]; }
set { _paras[ParamRampHigh] = value; }
}
/// <summary>
/// The low value.
/// </summary>
public double Low
{
get { return _paras[ParamRampLow]; }
set { _paras[ParamRampLow] = value; }
}
/// <summary>
/// Set the threshold high.
/// </summary>
public double ThresholdHigh
{
get { return _paras[ParamRampHighThreshold]; }
set { _paras[ParamRampHighThreshold] = value; }
}
/// <summary>
/// The threshold low.
/// </summary>
public double ThresholdLow
{
get { return _paras[ParamRampLowThreshold]; }
set { _paras[ParamRampLowThreshold] = value; }
}
/// <summary>
/// True, as this function does have a derivative.
/// </summary>
/// <returns>True, as this function does have a derivative.</returns>
public virtual bool HasDerivative
{
get
{
return true;
}
}
/// <inheritdoc />
public virtual void ActivationFunction(double[] x, int start,
int size)
{
double slope = (_paras[ParamRampHighThreshold] - _paras[ParamRampLowThreshold])
/(_paras[ParamRampHigh] - _paras[ParamRampLow]);
for (int i = start; i < start + size; i++)
{
if (x[i] < _paras[ParamRampLowThreshold])
{
x[i] = _paras[ParamRampLow];
}
else if (x[i] > _paras[ParamRampHighThreshold])
{
x[i] = _paras[ParamRampHigh];
}
else
{
x[i] = (slope*x[i]);
}
}
}
/// <inheritdoc />
public virtual double DerivativeFunction(double b, double a)
{
return 1.0d;
}
/// <inheritdoc />
public virtual String[] ParamNames
{
get
{
String[] result = {
"thresholdHigh", "thresholdLow", "high",
"low"
};
return result;
}
}
/// <inheritdoc />
public virtual double[] Params
{
get { return _paras; }
}
}
}
| |
// CodeContracts
//
// Copyright (c) Microsoft Corporation
//
// All rights reserved.
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// File System.Windows.IInputElement.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows
{
public partial interface IInputElement
{
#region Methods and constructors
void AddHandler(RoutedEvent routedEvent, Delegate handler);
bool CaptureMouse();
bool CaptureStylus();
bool Focus();
void RaiseEvent(RoutedEventArgs e);
void ReleaseMouseCapture();
void ReleaseStylusCapture();
void RemoveHandler(RoutedEvent routedEvent, Delegate handler);
#endregion
#region Properties and indexers
bool Focusable
{
get;
set;
}
bool IsEnabled
{
get;
}
bool IsKeyboardFocused
{
get;
}
bool IsKeyboardFocusWithin
{
get;
}
bool IsMouseCaptured
{
get;
}
bool IsMouseDirectlyOver
{
get;
}
bool IsMouseOver
{
get;
}
bool IsStylusCaptured
{
get;
}
bool IsStylusDirectlyOver
{
get;
}
bool IsStylusOver
{
get;
}
#endregion
#region Events
event System.Windows.Input.KeyboardFocusChangedEventHandler GotKeyboardFocus
;
event System.Windows.Input.MouseEventHandler GotMouseCapture
;
event System.Windows.Input.StylusEventHandler GotStylusCapture
;
event System.Windows.Input.KeyEventHandler KeyDown
;
event System.Windows.Input.KeyEventHandler KeyUp
;
event System.Windows.Input.KeyboardFocusChangedEventHandler LostKeyboardFocus
;
event System.Windows.Input.MouseEventHandler LostMouseCapture
;
event System.Windows.Input.StylusEventHandler LostStylusCapture
;
event System.Windows.Input.MouseEventHandler MouseEnter
;
event System.Windows.Input.MouseEventHandler MouseLeave
;
event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonDown
;
event System.Windows.Input.MouseButtonEventHandler MouseLeftButtonUp
;
event System.Windows.Input.MouseEventHandler MouseMove
;
event System.Windows.Input.MouseButtonEventHandler MouseRightButtonDown
;
event System.Windows.Input.MouseButtonEventHandler MouseRightButtonUp
;
event System.Windows.Input.MouseWheelEventHandler MouseWheel
;
event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewGotKeyboardFocus
;
event System.Windows.Input.KeyEventHandler PreviewKeyDown
;
event System.Windows.Input.KeyEventHandler PreviewKeyUp
;
event System.Windows.Input.KeyboardFocusChangedEventHandler PreviewLostKeyboardFocus
;
event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonDown
;
event System.Windows.Input.MouseButtonEventHandler PreviewMouseLeftButtonUp
;
event System.Windows.Input.MouseEventHandler PreviewMouseMove
;
event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonDown
;
event System.Windows.Input.MouseButtonEventHandler PreviewMouseRightButtonUp
;
event System.Windows.Input.MouseWheelEventHandler PreviewMouseWheel
;
event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonDown
;
event System.Windows.Input.StylusButtonEventHandler PreviewStylusButtonUp
;
event System.Windows.Input.StylusDownEventHandler PreviewStylusDown
;
event System.Windows.Input.StylusEventHandler PreviewStylusInAirMove
;
event System.Windows.Input.StylusEventHandler PreviewStylusInRange
;
event System.Windows.Input.StylusEventHandler PreviewStylusMove
;
event System.Windows.Input.StylusEventHandler PreviewStylusOutOfRange
;
event System.Windows.Input.StylusSystemGestureEventHandler PreviewStylusSystemGesture
;
event System.Windows.Input.StylusEventHandler PreviewStylusUp
;
event System.Windows.Input.TextCompositionEventHandler PreviewTextInput
;
event System.Windows.Input.StylusButtonEventHandler StylusButtonDown
;
event System.Windows.Input.StylusButtonEventHandler StylusButtonUp
;
event System.Windows.Input.StylusDownEventHandler StylusDown
;
event System.Windows.Input.StylusEventHandler StylusEnter
;
event System.Windows.Input.StylusEventHandler StylusInAirMove
;
event System.Windows.Input.StylusEventHandler StylusInRange
;
event System.Windows.Input.StylusEventHandler StylusLeave
;
event System.Windows.Input.StylusEventHandler StylusMove
;
event System.Windows.Input.StylusEventHandler StylusOutOfRange
;
event System.Windows.Input.StylusSystemGestureEventHandler StylusSystemGesture
;
event System.Windows.Input.StylusEventHandler StylusUp
;
event System.Windows.Input.TextCompositionEventHandler TextInput
;
#endregion
}
}
| |
using System;
namespace jaytwo.NetMF.UnitsLib
{
public class WeightMeasurement : OverloadedMeasurementBase
{
// as defined in the NSIT Handbook 44
// http://www.nist.gov/pml/wmd/pubs/upload/2012-hb44-final.pdf
internal const double KILOGRAMS_PER_POUND = 0.45359237;
// http://www.elivermore.com/conversions.htm
internal const double NEWTONS_PER_POUND = 4.4482216152605;
internal const double NEWTONS_PER_KILOGRAM = 9.80665;
public static WeightMeasurement FromPressure(PressureMeasurement pressure, AreaMeasurement area)
{
var resultNewtons = pressure.Pa * area.SquareMeters;
return WeightMeasurement.FromNewtons(resultNewtons);
}
public static WeightMeasurement FromTorque(MechanicalEnergyMeasurement torque, LengthMeasurement radius)
{
var resultNewtons = torque.NewtonMeters / radius.Meters;
return WeightMeasurement.FromNewtons(resultNewtons);
}
public static WeightMeasurement FromPounds(double pounds)
{
var kilograms = (pounds * KILOGRAMS_PER_POUND);
return WeightMeasurement.FromKilograms(kilograms);
}
public static WeightMeasurement FromTons(double tons)
{
var pounds = (tons * 2000d);
return WeightMeasurement.FromPounds(pounds);
}
public static WeightMeasurement FromKilograms(double kilograms)
{
return new WeightMeasurement(kilograms);
}
public static WeightMeasurement FromNewtons(double newtons)
{
var kilograms = (newtons / NEWTONS_PER_KILOGRAM);
return WeightMeasurement.FromKilograms(kilograms);
}
public static WeightMeasurement FromBasicUnits(double basicUnits)
{
return new WeightMeasurement(basicUnits);
}
private WeightMeasurement(double kilograms)
: base(kilograms)
{
}
#if MF_FRAMEWORK_VERSION_V3_0 || MF_FRAMEWORK_VERSION_V4_0 || MF_FRAMEWORK_VERSION_V4_1
private WeightMeasurement()
: base()
{
}
#endif
public double Kilograms { get { return BasicUnits; } }
public double Grams { get { return (DoubleMetricPrefixUtility.FromKilo(Kilograms)); } }
public double Newtons { get { return (Kilograms * NEWTONS_PER_KILOGRAM);} }
public double MetricTons { get { return (Kilograms / 1000); } }
public double Ounces { get { return (Pounds * 16); } }
public double Pounds { get { return (Kilograms / KILOGRAMS_PER_POUND); } }
public double Tons { get { return (Pounds / 2000); } }
public double Grains { get { return (Pounds * 7000); } }
#if !MF_FRAMEWORK_VERSION_V3_0 && !MF_FRAMEWORK_VERSION_V4_0 && !MF_FRAMEWORK_VERSION_V4_1
public static WeightMeasurement None = new WeightMeasurement(double.NaN);
#else
public static WeightMeasurement None = new WeightMeasurement();
#endif
public static WeightMeasurement Zero = new WeightMeasurement(0);
public static WeightMeasurement Min = new WeightMeasurement(double.NegativeInfinity);
public static WeightMeasurement Max = new WeightMeasurement(double.PositiveInfinity);
public override string ToString()
{
return BasicUnits.ToString();
}
public WeightMeasurement MultiplyBy(double value)
{
var result = (BasicUnits * value);
return new WeightMeasurement(result);
}
public WeightMeasurement DivideBy(double value)
{
var result = (BasicUnits / value);
return new WeightMeasurement(result);
}
public WeightMeasurement Add(WeightMeasurement value)
{
var result = (BasicUnits + value.BasicUnits);
return new WeightMeasurement(result);
}
public WeightMeasurement Subtract(WeightMeasurement value)
{
var result = (BasicUnits - value.BasicUnits);
return new WeightMeasurement(result);
}
#if !MF_FRAMEWORK_VERSION_V3_0 && !MF_FRAMEWORK_VERSION_V4_0 && !MF_FRAMEWORK_VERSION_V4_1
public static WeightMeasurement Parse(string value)
{
return TryParse(value) ?? WeightMeasurement.None;
}
public static WeightMeasurement TryParse(string value)
{
double units;
if (double.TryParse(value, out units))
{
return new WeightMeasurement(units);
}
else
{
return null;
}
}
#endif
public override bool Equals(object obj)
{
if (obj == null)
{
return false;
}
WeightMeasurement other = obj as WeightMeasurement;
if ((object)other == null)
{
return false;
}
return MeasurementHelpers.AreDoublesEqual(BasicUnits, other.BasicUnits);
}
public bool Equals(WeightMeasurement other)
{
return ElectricalPowerMeasurement.IsEqualTo(this, other);
}
public static bool operator ==(WeightMeasurement a, WeightMeasurement b)
{
return OverloadedMeasurementBase.IsEqualTo(a, b);
}
public static bool operator !=(WeightMeasurement a, WeightMeasurement b)
{
return !OverloadedMeasurementBase.IsEqualTo(a, b);
}
public static bool operator >(WeightMeasurement a, WeightMeasurement b)
{
return OverloadedMeasurementBase.IsGreaterThan(a, b);
}
public static bool operator >=(WeightMeasurement a, WeightMeasurement b)
{
return OverloadedMeasurementBase.IsGreaterThanOrEqual(a, b);
}
public static bool operator <(WeightMeasurement a, WeightMeasurement b)
{
return OverloadedMeasurementBase.IsLessThan(a, b);
}
public static bool operator <=(WeightMeasurement a, WeightMeasurement b)
{
return OverloadedMeasurementBase.IsLessThanOrEqual(a, b);
}
public static implicit operator WeightMeasurement(double value)
{
return new WeightMeasurement(value);
}
public static implicit operator double(WeightMeasurement value)
{
return value.BasicUnits;
}
public override int GetHashCode()
{
return OverloadedMeasurementBase.GetHashCode(this);
}
}
}
| |
namespace Ioke.Lang {
using Ioke.Lang.Util;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
public class Base {
public static object CellNames(IokeObject context, IokeObject message, object on, bool includeMimics, object cutoff) {
if(includeMimics) {
var visited = IdentityHashTable.Create();
var names = new SaneArrayList();
var visitedNames = new SaneHashSet<object>();
var undefined = new SaneHashSet<string>();
Runtime runtime = context.runtime;
var toVisit = new SaneArrayList();
toVisit.Add(on);
while(toVisit.Count > 0) {
IokeObject current = IokeObject.As(toVisit[0], context);
toVisit.RemoveAt(0);
if(!visited.Contains(current)) {
visited[current] = null;
if(cutoff != current) {
foreach(IokeObject o in current.GetMimics()) toVisit.Add(o);
}
var mso = current.Cells;
foreach(string s in mso.Keys) {
if(!undefined.Contains(s)) {
if(mso[s] == runtime.nul) {
undefined.Add(s);
} else {
object x = runtime.GetSymbol(s);
if(!visitedNames.Contains(x)) {
visitedNames.Add(x);
names.Add(x);
}
}
}
}
}
}
return runtime.NewList(names);
} else {
var mso = IokeObject.As(on, context).Cells;
var names = new SaneArrayList();
Runtime runtime = context.runtime;
foreach(string s in mso.Keys) {
if(mso[s] != runtime.nul) {
names.Add(runtime.GetSymbol(s));
}
}
return runtime.NewList(names);
}
}
public static object Cells(IokeObject context, IokeObject message, object on, bool includeMimics) {
var cells = new SaneOrderedDictionary();
Runtime runtime = context.runtime;
if(includeMimics) {
var visited = IdentityHashTable.Create();
var undefined = new SaneHashSet<string>();
var toVisit = new SaneArrayList();
toVisit.Add(on);
while(toVisit.Count > 0) {
IokeObject current = IokeObject.As(toVisit[0], context);
toVisit.RemoveAt(0);
if(!visited.Contains(current)) {
visited[current] = null;
foreach(IokeObject o in current.GetMimics()) toVisit.Add(o);
var mso = current.Cells;
foreach(string s in mso.Keys) {
if(!undefined.Contains(s)) {
object val = mso[s];
if(val == runtime.nul) {
undefined.Add(s);
} else {
object x = runtime.GetSymbol(s);
if(!cells.Contains(x)) {
cells[x] = val;
}
}
}
}
}
}
} else {
var mso = IokeObject.As(on, context).Cells;
foreach(string s in mso.Keys) {
object val = mso[s];
if(val != runtime.nul) {
cells[runtime.GetSymbol(s)] = val;
}
}
}
return runtime.NewDict(cells);
}
public static object AssignCell(IokeObject context, IokeObject message, object on, object first, object val) {
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, first));
if(val is IokeObject) {
if((IokeObject.dataOf(val) is Named) && ((Named)IokeObject.dataOf(val)).Name == null) {
((Named)IokeObject.dataOf(val)).Name = name;
} else if(name.Length > 0 && char.IsUpper(name[0]) && !IokeObject.As(val, context).HasKind) {
if(on == context.runtime.Ground) {
IokeObject.As(val, context).Kind = name;
} else {
IokeObject.As(val, context).Kind = IokeObject.As(on, context).GetKind(message, context) + " " + name;
}
}
}
return IokeObject.SetCell(on, message, context, name, val);
}
public static object Documentation(IokeObject context, IokeObject message, object on) {
string docs = IokeObject.As(on, context).Documentation;
if(null == docs) {
return context.runtime.nil;
}
return context.runtime.NewText(docs);
}
public static object SetDocumentation(IokeObject context, IokeObject message, object on, object arg) {
if(arg == context.runtime.nil) {
IokeObject.As(on, context).SetDocumentation(null, message, context);
} else {
string s = Text.GetText(arg);
IokeObject.As(on, context).SetDocumentation(s, message, context);
}
return arg;
}
private static object RecursiveDestructuring(IList places, int numPlaces, IokeObject message, IokeObject context, object on, object toTuple) {
object tupledValue = ((Message)IokeObject.dataOf(context.runtime.asTuple)).SendTo(context.runtime.asTuple, context, toTuple);
object[] values = Tuple.GetElements(tupledValue);
int numValues = values.Length;
int min = System.Math.Min(numValues, numPlaces);
bool hadEndingUnderscore = false;
for(int i=0; i<min; i++) {
IokeObject m1 = IokeObject.As(places[i], context);
string name = m1.Name;
if(name.Equals("_")) {
if(i == numPlaces - 1) {
hadEndingUnderscore = true;
}
} else {
if(m1.Arguments.Count == 0) {
object value = values[i];
IokeObject.Assign(on, name, value, context, message);
if(value is IokeObject) {
if((IokeObject.dataOf(value) is Named) && ((Named)IokeObject.dataOf(value)).Name == null) {
((Named)IokeObject.dataOf(value)).Name = name;
} else if(name.Length > 0 && char.IsUpper(name[0]) && !(IokeObject.As(value, context).HasKind)) {
if(on == context.runtime.Ground || on == context.runtime.IokeGround) {
IokeObject.As(value, context).Kind = name;
} else {
IokeObject.As(value, context).Kind = IokeObject.As(on, context).GetKind(message, context) + " " + name;
}
}
}
} else if(name.Equals("")) {
var newArgs = m1.Arguments;
RecursiveDestructuring(newArgs, newArgs.Count, message, context, on, values[i]);
} else {
string newName = name + "=";
IList arguments = new SaneArrayList(m1.Arguments);
arguments.Add(context.runtime.CreateMessage(Message.Wrap(IokeObject.As(values[i], context))));
IokeObject msg = context.runtime.NewMessageFrom(message, newName, arguments);
((Message)IokeObject.dataOf(msg)).SendTo(msg, context, on);
}
}
}
if(numPlaces > min || (numValues > min && !hadEndingUnderscore)) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"DestructuringMismatch"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
context.runtime.ErrorCondition(condition);
}
return tupledValue;
}
public static void Init(IokeObject obj) {
obj.Kind = "Base";
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects two or more arguments, the first arguments unevaluated, the last evaluated. assigns the result of evaluating the last argument in the context of the caller, and assigns this result to the name/s provided by the first arguments. the first arguments remains unevaluated. the result of the assignment is the value assigned to the name. if the last argument is a method-like object and it's name is not set, that name will be set to the name of the cell.",
new NativeMethod("=", DefaultArgumentsDefinition.builder()
.WithRequiredPositionalUnevaluated("place")
.WithRestUnevaluated("morePlacesForDestructuring")
.WithRequiredPositional("value")
.Arguments,
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
var args = message.Arguments;
if(args.Count == 2) {
IokeObject m1 = IokeObject.As(Message.GetArguments(message)[0], context);
string name = m1.Name;
if(m1.Arguments.Count == 0) {
object value = ((Message)IokeObject.dataOf(message)).GetEvaluatedArgument(message, 1, context);
IokeObject.Assign(on, name, value, context, message);
if(value is IokeObject) {
if((IokeObject.dataOf(value) is Named) && ((Named)IokeObject.dataOf(value)).Name == null) {
((Named)IokeObject.dataOf(value)).Name = name;
} else if(name.Length > 0 && char.IsUpper(name[0]) && !(IokeObject.As(value, context).HasKind)) {
if(on == context.runtime.Ground || on == context.runtime.IokeGround) {
IokeObject.As(value, context).Kind = name;
} else {
IokeObject.As(value, context).Kind = IokeObject.As(on, context).GetKind(message, context) + " " + name;
}
}
}
return value;
} else {
string newName = name + "=";
IList arguments = new SaneArrayList(m1.Arguments);
arguments.Add(Message.GetArguments(message)[1]);
IokeObject msg = context.runtime.NewMessageFrom(message, newName, arguments);
return ((Message)IokeObject.dataOf(msg)).SendTo(msg, context, on);
}
} else {
int lastIndex = args.Count - 1;
int numPlaces = lastIndex;
return RecursiveDestructuring(args, numPlaces, message, context, on, Message.GetEvaluatedArgument(args[lastIndex], context));
}
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("will return a new derivation of the receiving object. Might throw exceptions if the object is an oddball object.",
new NativeMethod.WithNoArguments("mimic", (method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
return IokeObject.As(on, context).Mimic(message, context);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument that names the cell to set, sets this cell to the result of evaluating the second argument, and returns the value set.",
new NativeMethod("cell=",
DefaultArgumentsDefinition
.builder()
.WithRequiredPositional("cellName")
.WithRequiredPositional("value")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
return AssignCell(context, message, on, args[0], args[1]);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and returns the cell that matches that name, without activating even if it's activatable.",
new NativeMethod("cell", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
return IokeObject.GetCell(on, message, context, name);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a hash for the object",
new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
return context.runtime.NewNumber(System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(IokeObject.As(on, context).Cells));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns true if the left hand side is equal to the right hand side. exactly what this means depend on the object. the default behavior of Ioke objects is to only be equal if they are the same instance.",
new NativeMethod("==", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("other")
.Arguments,
(method, context, message, on, outer) => {
IList args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
return (IokeObject.As(on, context).Cells == IokeObject.As(args[0], context).Cells) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and returns a boolean indicating whether such a cell is reachable from this point.",
new NativeMethod("cell?", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
IList args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
return IokeObject.FindCell(on, message, context, name) != context.runtime.nul ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns the documentation text of the object called on. anything can have a documentation text - this text will initially be nil.",
new NativeMethod.WithNoArguments("documentation",
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>());
return Documentation(context, message, on);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns this object",
new NativeMethod.WithNoArguments("identity",
(method, context, message, on, outer) => {
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, new SaneArrayList(), new SaneDictionary<string, object>());
return on;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("sets the documentation string for a specific object.",
new TypeCheckingNativeMethod("documentation=", TypeCheckingArgumentsDefinition.builder()
.WithRequiredPositional("text").WhichMustMimic(obj.runtime.Text).OrBeNil()
.Arguments,
(method, on, args, keywords, context, message) => {
return SetDocumentation(context, message, on, args[0]);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and returns a boolean indicating whether this cell is owned by the receiver or not. the assumption is that the cell should exist. if it doesn't exist, a NoSuchCell condition will be signalled.",
new NativeMethod("cellOwner?", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
return (IokeObject.FindPlace(on, message, context, name) == on) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and returns the closest object that defines such a cell. if it doesn't exist, a NoSuchCell condition will be signalled.",
new NativeMethod("cellOwner", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
object result = IokeObject.FindPlace(on, message, context, name);
if(result == context.runtime.nul) {
return context.runtime.nil;
}
return result;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and removes that cell from the current receiver. if the current receiver has no such object, signals a condition. note that if another cell with that name is available in the mimic chain, it will still be accessible after calling this method. the method returns the receiver.",
new NativeMethod("removeCell!", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
IokeObject.RemoveCell(on, message, context, name);
return on;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("expects one evaluated text or symbol argument and makes that cell undefined in the current receiver. what that means is that from now on it will look like this cell doesn't exist in the receiver or any of its mimics. the cell will not show up if you call cellNames on the receiver or any of the receivers mimics. the undefined status can be removed by doing removeCell! on the correct cell name. a cell name that doesn't exist can still be undefined. the method returns the receiver.",
new NativeMethod("undefineCell!", DefaultArgumentsDefinition.builder()
.WithRequiredPositional("cellName")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
string name = Text.GetText(((Message)IokeObject.dataOf(context.runtime.asText)).SendTo(context.runtime.asText, context, args[0]));
IokeObject.UndefineCell(on, message, context, name);
return on;
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("takes one optional evaluated boolean argument, which defaults to false. if false, this method returns a list of the cell names of the receiver. if true, it returns the cell names of this object and all it's mimics recursively.",
new NativeMethod("cellNames", DefaultArgumentsDefinition.builder()
.WithOptionalPositional("includeMimics", "false")
.WithOptionalPositional("cutoff", "nil")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
return CellNames(context, message, on, args.Count > 0 && IokeObject.IsObjectTrue(args[0]), (args.Count > 1) ? args[1] : null);
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("takes one optional evaluated boolean argument, which defaults to false. if false, this method returns a dict of the cell names and values of the receiver. if true, it returns the cell names and values of this object and all it's mimics recursively.",
new NativeMethod("cells", DefaultArgumentsDefinition.builder()
.WithOptionalPositional("includeMimics", "false")
.Arguments,
(method, context, message, on, outer) => {
var args = new SaneArrayList();
outer.ArgumentsDefinition.GetEvaluatedArguments(context, message, on, args, new SaneDictionary<string, object>());
return Cells(context, message, on, args.Count > 0 && IokeObject.IsObjectTrue(args[0]));
})));
}
}
}
| |
namespace PackageEditor
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.fsFolderTree = new System.Windows.Forms.TreeView();
this.imageList = new System.Windows.Forms.ImageList(this.components);
this.fsFilesList = new System.Windows.Forms.ListView();
this.columnFileName = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnFileSize = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnFileType = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.fileContextMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
this.fileContextMenuDelete = new System.Windows.Forms.ToolStripMenuItem();
this.fileContextMenuProperties = new System.Windows.Forms.ToolStripMenuItem();
this.panel2 = new System.Windows.Forms.Panel();
this.panel3 = new System.Windows.Forms.Panel();
this.fsFolderInfoIsolationCombo = new System.Windows.Forms.ComboBox();
this.fsFolderInfoIsolationLbl = new System.Windows.Forms.Label();
this.fsFolderInfoFullName = new System.Windows.Forms.Label();
this.regSplitContainer = new System.Windows.Forms.SplitContainer();
this.regFolderTree = new System.Windows.Forms.TreeView();
this.ContextMenuStripRegistryFolder = new System.Windows.Forms.ContextMenuStrip(this.components);
this.toolStripMenuItemExport = new System.Windows.Forms.ToolStripMenuItem();
this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.tbType = new System.Windows.Forms.TextBox();
this.tbValue = new System.Windows.Forms.TextBox();
this.tbSize = new System.Windows.Forms.TextBox();
this.tbFile = new System.Windows.Forms.TextBox();
this.regFilesList = new PackageEditor.ListViewEx();
this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.panel4 = new System.Windows.Forms.Panel();
this.panel6 = new System.Windows.Forms.Panel();
this.regFolderInfoIsolationCombo = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.regFolderInfoFullName = new System.Windows.Forms.Label();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.newToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.saveasToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.exportXmlToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.langToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.englishMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.frenchMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.spanishMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.chineseMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.regProgressTimer = new System.Windows.Forms.Timer(this.components);
this.itemHoverTimer = new System.Windows.Forms.Timer(this.components);
this.tabControl = new System.Windows.Forms.TabControl();
this.tabGeneral = new System.Windows.Forms.TabPage();
this.dropboxLabel = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.label10 = new System.Windows.Forms.Label();
this.propertyFileVersion = new System.Windows.Forms.TextBox();
this.lnkChangeIcon = new System.Windows.Forms.LinkLabel();
this.label2 = new System.Windows.Forms.Label();
this.propertyFriendlyName = new System.Windows.Forms.TextBox();
this.propertyIcon = new System.Windows.Forms.PictureBox();
this.propertyAppID = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox11 = new System.Windows.Forms.GroupBox();
this.lnkAutoLaunch = new System.Windows.Forms.LinkLabel();
this.lnkChangeDataStorage = new System.Windows.Forms.LinkLabel();
this.propertyAutoLaunch = new System.Windows.Forms.Label();
this.propertyDataStorage = new System.Windows.Forms.Label();
this.groupBox9 = new System.Windows.Forms.GroupBox();
this.helpVirtMode = new System.Windows.Forms.Label();
this.picRAM = new System.Windows.Forms.PictureBox();
this.picDisk = new System.Windows.Forms.PictureBox();
this.propertyVirtModeRam = new System.Windows.Forms.RadioButton();
this.propertyVirtModeDisk = new System.Windows.Forms.RadioButton();
this.label9 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.lblAutoLaunch = new System.Windows.Forms.Label();
this.groupBox10 = new System.Windows.Forms.GroupBox();
this.picFullAccess = new System.Windows.Forms.PictureBox();
this.picIsolatedMode = new System.Windows.Forms.PictureBox();
this.helpIsolationMode = new System.Windows.Forms.Label();
this.picDataMode = new System.Windows.Forms.PictureBox();
this.propertyIsolationDataMode = new System.Windows.Forms.RadioButton();
this.propertyIsolationIsolated = new System.Windows.Forms.RadioButton();
this.propertyIsolationMerge = new System.Windows.Forms.RadioButton();
this.dropboxButton = new System.Windows.Forms.Button();
this.tabFileSystem = new System.Windows.Forms.TabPage();
this.panel5 = new System.Windows.Forms.Panel();
this.fileToolStrip = new System.Windows.Forms.ToolStrip();
this.fsAddBtn = new System.Windows.Forms.ToolStripButton();
this.fsAddEmptyDirBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.fsRemoveBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.fsAddDirBtn = new System.Windows.Forms.ToolStripButton();
this.fsSaveFileAsBtn = new System.Windows.Forms.ToolStripButton();
this.tabRegistry = new System.Windows.Forms.TabPage();
this.panel8 = new System.Windows.Forms.Panel();
this.panel1 = new System.Windows.Forms.Panel();
this.panel7 = new System.Windows.Forms.Panel();
this.regProgressBar = new System.Windows.Forms.ProgressBar();
this.regToolStrip = new System.Windows.Forms.ToolStrip();
this.regRemoveBtn = new System.Windows.Forms.ToolStripButton();
this.regEditBtn = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.regImportBtn = new System.Windows.Forms.ToolStripButton();
this.regExportBtn = new System.Windows.Forms.ToolStripButton();
this.tabAdvanced = new System.Windows.Forms.TabPage();
this.groupBox5 = new System.Windows.Forms.GroupBox();
this.cbVolatileRegistry = new System.Windows.Forms.CheckBox();
this.propertyScmDirect = new System.Windows.Forms.CheckBox();
this.propertyDisplayLogo = new System.Windows.Forms.CheckBox();
this.cbDatFile = new System.Windows.Forms.CheckBox();
this.lnkAutoUpdate = new System.Windows.Forms.LinkLabel();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.lnkCustomEvents = new System.Windows.Forms.LinkLabel();
this.propertyStopInheritance = new System.Windows.Forms.TextBox();
this.groupBox7 = new System.Windows.Forms.GroupBox();
this.chkCleanDoneDialog = new System.Windows.Forms.CheckBox();
this.rdbCleanNone = new System.Windows.Forms.RadioButton();
this.chkCleanAsk = new System.Windows.Forms.CheckBox();
this.rdbCleanAll = new System.Windows.Forms.RadioButton();
this.rdbCleanRegOnly = new System.Windows.Forms.RadioButton();
this.groupBox4 = new System.Windows.Forms.GroupBox();
this.rdbIntegrateVirtual = new System.Windows.Forms.RadioButton();
this.rdbIntegrateStandard = new System.Windows.Forms.RadioButton();
this.rdbIntegrateNone = new System.Windows.Forms.RadioButton();
this.tabSecurity = new System.Windows.Forms.TabPage();
this.panel10 = new System.Windows.Forms.Panel();
this.groupDataEncrypt = new System.Windows.Forms.GroupBox();
this.panel16 = new System.Windows.Forms.Panel();
this.lnkExportPwdKey = new System.Windows.Forms.LinkLabel();
this.lnkImportPwdKey = new System.Windows.Forms.LinkLabel();
this.propertyEncryptUserCreatedPassword = new System.Windows.Forms.RadioButton();
this.lnkEncryptionLearnMore = new System.Windows.Forms.LinkLabel();
this.label12 = new System.Windows.Forms.Label();
this.tbEncryptionPwdConfirm = new System.Windows.Forms.TextBox();
this.tbEncryptionPwd = new System.Windows.Forms.TextBox();
this.lnkGenerateEncKey = new System.Windows.Forms.LinkLabel();
this.tbEncryptionKey = new System.Windows.Forms.TextBox();
this.propertyEncryptUsingPassword = new System.Windows.Forms.RadioButton();
this.propertyEncryptUsingKey = new System.Windows.Forms.RadioButton();
this.propertyEncryption = new System.Windows.Forms.CheckBox();
this.groupUsageRights = new System.Windows.Forms.GroupBox();
this.lnkActiveDirectory = new System.Windows.Forms.LinkLabel();
this.groupExpiration = new System.Windows.Forms.GroupBox();
this.propertyExpirationDatePicker = new System.Windows.Forms.DateTimePicker();
this.propertyExpiration = new System.Windows.Forms.CheckBox();
this.propertyTtlDays = new System.Windows.Forms.CheckBox();
this.propertyTtlResistRemove = new System.Windows.Forms.CheckBox();
this.propertyTtlDaysValue = new System.Windows.Forms.NumericUpDown();
this.groupEditProtect = new System.Windows.Forms.GroupBox();
this.label6 = new System.Windows.Forms.Label();
this.tbPasswordConfirm = new System.Windows.Forms.TextBox();
this.propertyProtPassword = new System.Windows.Forms.TextBox();
this.propertyProt = new System.Windows.Forms.CheckBox();
this.tabWelcome = new System.Windows.Forms.TabPage();
this.panelWelcome = new System.Windows.Forms.Panel();
this.panel15 = new System.Windows.Forms.Panel();
this.panel14 = new System.Windows.Forms.Panel();
this.pictureBox2 = new System.Windows.Forms.PictureBox();
this.panel13 = new System.Windows.Forms.Panel();
this.listViewMRU = new System.Windows.Forms.ListView();
this.columnFileN = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader()));
this.imageListMRU = new System.Windows.Forms.ImageList(this.components);
this.lnkPackageEdit = new System.Windows.Forms.LinkLabel();
this.panel9 = new System.Windows.Forms.Panel();
this.label11 = new System.Windows.Forms.Label();
this.line = new System.Windows.Forms.GroupBox();
this.bottomPanel = new System.Windows.Forms.Panel();
this.panel12 = new System.Windows.Forms.PictureBox();
this.panel11 = new System.Windows.Forms.PictureBox();
this.bkPanel = new System.Windows.Forms.Panel();
this.panelLicense = new System.Windows.Forms.Panel();
this.lnkUpgrade = new System.Windows.Forms.LinkLabel();
this.lblNotCommercial = new System.Windows.Forms.Label();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.fileContextMenu.SuspendLayout();
this.panel2.SuspendLayout();
this.panel3.SuspendLayout();
this.regSplitContainer.Panel1.SuspendLayout();
this.regSplitContainer.Panel2.SuspendLayout();
this.regSplitContainer.SuspendLayout();
this.ContextMenuStripRegistryFolder.SuspendLayout();
this.panel4.SuspendLayout();
this.panel6.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.tabControl.SuspendLayout();
this.tabGeneral.SuspendLayout();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyIcon)).BeginInit();
this.groupBox1.SuspendLayout();
this.groupBox11.SuspendLayout();
this.groupBox9.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picRAM)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picDisk)).BeginInit();
this.groupBox10.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.picFullAccess)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picIsolatedMode)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.picDataMode)).BeginInit();
this.tabFileSystem.SuspendLayout();
this.panel5.SuspendLayout();
this.fileToolStrip.SuspendLayout();
this.tabRegistry.SuspendLayout();
this.panel8.SuspendLayout();
this.panel1.SuspendLayout();
this.panel7.SuspendLayout();
this.regToolStrip.SuspendLayout();
this.tabAdvanced.SuspendLayout();
this.groupBox5.SuspendLayout();
this.groupBox7.SuspendLayout();
this.groupBox4.SuspendLayout();
this.tabSecurity.SuspendLayout();
this.groupDataEncrypt.SuspendLayout();
this.panel16.SuspendLayout();
this.groupUsageRights.SuspendLayout();
this.groupExpiration.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyTtlDaysValue)).BeginInit();
this.groupEditProtect.SuspendLayout();
this.tabWelcome.SuspendLayout();
this.panelWelcome.SuspendLayout();
this.panel15.SuspendLayout();
this.panel14.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit();
this.panel13.SuspendLayout();
this.panel9.SuspendLayout();
this.bottomPanel.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.panel12)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.panel11)).BeginInit();
this.bkPanel.SuspendLayout();
this.panelLicense.SuspendLayout();
this.SuspendLayout();
//
// splitContainer1
//
resources.ApplyResources(this.splitContainer1, "splitContainer1");
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.fsFolderTree);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.fsFilesList);
this.splitContainer1.Panel2.Controls.Add(this.panel2);
//
// fsFolderTree
//
this.fsFolderTree.AllowDrop = true;
resources.ApplyResources(this.fsFolderTree, "fsFolderTree");
this.fsFolderTree.ImageList = this.imageList;
this.fsFolderTree.Name = "fsFolderTree";
this.fsFolderTree.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.fsFolderTree_ItemDrag);
this.fsFolderTree.BeforeSelect += new System.Windows.Forms.TreeViewCancelEventHandler(this.fsFolderTree_BeforeSelect);
this.fsFolderTree.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.fsFolderTree_AfterSelect);
this.fsFolderTree.DragDrop += new System.Windows.Forms.DragEventHandler(this.Vfs_DragDrop);
this.fsFolderTree.DragEnter += new System.Windows.Forms.DragEventHandler(this.Vfs_DragEnter);
this.fsFolderTree.DragOver += new System.Windows.Forms.DragEventHandler(this.fsFolderTree_DragOver);
//
// imageList
//
this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream")));
this.imageList.TransparentColor = System.Drawing.Color.Red;
this.imageList.Images.SetKeyName(0, "folder_fullaccess.png");
this.imageList.Images.SetKeyName(1, "folder");
this.imageList.Images.SetKeyName(2, "folder_strictlyisolated.png");
this.imageList.Images.SetKeyName(3, "remove");
this.imageList.Images.SetKeyName(4, "058.png");
this.imageList.Images.SetKeyName(5, "folder_opened");
this.imageList.Images.SetKeyName(6, "new_document");
this.imageList.Images.SetKeyName(7, "078b.png");
this.imageList.Images.SetKeyName(8, "add");
//
// fsFilesList
//
this.fsFilesList.AllowDrop = true;
this.fsFilesList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnFileName,
this.columnFileSize,
this.columnFileType});
this.fsFilesList.ContextMenuStrip = this.fileContextMenu;
resources.ApplyResources(this.fsFilesList, "fsFilesList");
this.fsFilesList.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
((System.Windows.Forms.ListViewItem)(resources.GetObject("fsFilesList.Items"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("fsFilesList.Items1")))});
this.fsFilesList.Name = "fsFilesList";
this.fsFilesList.SmallImageList = this.imageList;
this.fsFilesList.UseCompatibleStateImageBehavior = false;
this.fsFilesList.View = System.Windows.Forms.View.Details;
this.fsFilesList.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.fsFilesList_ColumnClick);
this.fsFilesList.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.fsFilesList_ItemDrag);
this.fsFilesList.DragDrop += new System.Windows.Forms.DragEventHandler(this.Vfs_DragDrop);
this.fsFilesList.DragEnter += new System.Windows.Forms.DragEventHandler(this.Vfs_DragEnter);
this.fsFilesList.DoubleClick += new System.EventHandler(this.fileContextMenuProperties_Click);
//
// columnFileName
//
resources.ApplyResources(this.columnFileName, "columnFileName");
//
// columnFileSize
//
resources.ApplyResources(this.columnFileSize, "columnFileSize");
//
// columnFileType
//
resources.ApplyResources(this.columnFileType, "columnFileType");
//
// fileContextMenu
//
this.fileContextMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileContextMenuDelete,
this.fileContextMenuProperties});
this.fileContextMenu.Name = "fileContextMenu";
resources.ApplyResources(this.fileContextMenu, "fileContextMenu");
//
// fileContextMenuDelete
//
this.fileContextMenuDelete.Name = "fileContextMenuDelete";
resources.ApplyResources(this.fileContextMenuDelete, "fileContextMenuDelete");
this.fileContextMenuDelete.Click += new System.EventHandler(this.fileContextMenuDelete_Click);
//
// fileContextMenuProperties
//
this.fileContextMenuProperties.Name = "fileContextMenuProperties";
resources.ApplyResources(this.fileContextMenuProperties, "fileContextMenuProperties");
this.fileContextMenuProperties.Click += new System.EventHandler(this.fileContextMenuProperties_Click);
//
// panel2
//
this.panel2.Controls.Add(this.panel3);
this.panel2.Controls.Add(this.fsFolderInfoFullName);
resources.ApplyResources(this.panel2, "panel2");
this.panel2.Name = "panel2";
//
// panel3
//
this.panel3.Controls.Add(this.fsFolderInfoIsolationCombo);
this.panel3.Controls.Add(this.fsFolderInfoIsolationLbl);
resources.ApplyResources(this.panel3, "panel3");
this.panel3.Name = "panel3";
//
// fsFolderInfoIsolationCombo
//
this.fsFolderInfoIsolationCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.fsFolderInfoIsolationCombo.FormattingEnabled = true;
resources.ApplyResources(this.fsFolderInfoIsolationCombo, "fsFolderInfoIsolationCombo");
this.fsFolderInfoIsolationCombo.Name = "fsFolderInfoIsolationCombo";
//
// fsFolderInfoIsolationLbl
//
resources.ApplyResources(this.fsFolderInfoIsolationLbl, "fsFolderInfoIsolationLbl");
this.fsFolderInfoIsolationLbl.Name = "fsFolderInfoIsolationLbl";
//
// fsFolderInfoFullName
//
resources.ApplyResources(this.fsFolderInfoFullName, "fsFolderInfoFullName");
this.fsFolderInfoFullName.Name = "fsFolderInfoFullName";
//
// regSplitContainer
//
resources.ApplyResources(this.regSplitContainer, "regSplitContainer");
this.regSplitContainer.Name = "regSplitContainer";
//
// regSplitContainer.Panel1
//
this.regSplitContainer.Panel1.Controls.Add(this.regFolderTree);
//
// regSplitContainer.Panel2
//
this.regSplitContainer.Panel2.Controls.Add(this.tbType);
this.regSplitContainer.Panel2.Controls.Add(this.tbValue);
this.regSplitContainer.Panel2.Controls.Add(this.tbSize);
this.regSplitContainer.Panel2.Controls.Add(this.tbFile);
this.regSplitContainer.Panel2.Controls.Add(this.regFilesList);
this.regSplitContainer.Panel2.Controls.Add(this.panel4);
//
// regFolderTree
//
this.regFolderTree.ContextMenuStrip = this.ContextMenuStripRegistryFolder;
resources.ApplyResources(this.regFolderTree, "regFolderTree");
this.regFolderTree.ImageList = this.imageList;
this.regFolderTree.Name = "regFolderTree";
//
// ContextMenuStripRegistryFolder
//
this.ContextMenuStripRegistryFolder.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItemExport,
this.deleteToolStripMenuItem});
this.ContextMenuStripRegistryFolder.Name = "Export";
resources.ApplyResources(this.ContextMenuStripRegistryFolder, "ContextMenuStripRegistryFolder");
//
// toolStripMenuItemExport
//
this.toolStripMenuItemExport.Name = "toolStripMenuItemExport";
resources.ApplyResources(this.toolStripMenuItemExport, "toolStripMenuItemExport");
this.toolStripMenuItemExport.Click += new System.EventHandler(this.toolStripMenuItemExport_Click);
//
// deleteToolStripMenuItem
//
this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem";
resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem");
this.deleteToolStripMenuItem.Click += new System.EventHandler(this.deleteToolStripMenuItem_Click);
//
// tbType
//
this.tbType.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbType, "tbType");
this.tbType.Name = "tbType";
this.tbType.ReadOnly = true;
//
// tbValue
//
resources.ApplyResources(this.tbValue, "tbValue");
this.tbValue.Name = "tbValue";
//
// tbSize
//
this.tbSize.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbSize, "tbSize");
this.tbSize.Name = "tbSize";
this.tbSize.ReadOnly = true;
//
// tbFile
//
this.tbFile.BackColor = System.Drawing.SystemColors.Window;
resources.ApplyResources(this.tbFile, "tbFile");
this.tbFile.Name = "tbFile";
this.tbFile.ReadOnly = true;
//
// regFilesList
//
this.regFilesList.AllowColumnReorder = true;
this.regFilesList.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnHeader3,
this.columnHeader4,
this.columnHeader5});
resources.ApplyResources(this.regFilesList, "regFilesList");
this.regFilesList.DoubleClickActivation = false;
this.regFilesList.FullRowSelect = true;
this.regFilesList.Items.AddRange(new System.Windows.Forms.ListViewItem[] {
((System.Windows.Forms.ListViewItem)(resources.GetObject("regFilesList.Items"))),
((System.Windows.Forms.ListViewItem)(resources.GetObject("regFilesList.Items1")))});
this.regFilesList.Name = "regFilesList";
this.regFilesList.UseCompatibleStateImageBehavior = false;
this.regFilesList.View = System.Windows.Forms.View.Details;
this.regFilesList.SubItemClicked += new PackageEditor.SubItemEventHandler(this.regFilesList_SubItemClicked);
this.regFilesList.SubItemEndEditing += new PackageEditor.SubItemEndEditingEventHandler(this.regFilesList_SubItemEndEditing);
this.regFilesList.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.regFilesList_ColumnClick);
//
// columnHeader3
//
resources.ApplyResources(this.columnHeader3, "columnHeader3");
//
// columnHeader4
//
resources.ApplyResources(this.columnHeader4, "columnHeader4");
//
// columnHeader5
//
resources.ApplyResources(this.columnHeader5, "columnHeader5");
//
// panel4
//
this.panel4.Controls.Add(this.panel6);
this.panel4.Controls.Add(this.regFolderInfoFullName);
resources.ApplyResources(this.panel4, "panel4");
this.panel4.Name = "panel4";
//
// panel6
//
this.panel6.Controls.Add(this.regFolderInfoIsolationCombo);
this.panel6.Controls.Add(this.label3);
resources.ApplyResources(this.panel6, "panel6");
this.panel6.Name = "panel6";
//
// regFolderInfoIsolationCombo
//
this.regFolderInfoIsolationCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.regFolderInfoIsolationCombo.FormattingEnabled = true;
resources.ApplyResources(this.regFolderInfoIsolationCombo, "regFolderInfoIsolationCombo");
this.regFolderInfoIsolationCombo.Name = "regFolderInfoIsolationCombo";
//
// label3
//
resources.ApplyResources(this.label3, "label3");
this.label3.Name = "label3";
//
// regFolderInfoFullName
//
resources.ApplyResources(this.regFolderInfoFullName, "regFolderInfoFullName");
this.regFolderInfoFullName.Name = "regFolderInfoFullName";
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem});
resources.ApplyResources(this.menuStrip1, "menuStrip1");
this.menuStrip1.Name = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.openToolStripMenuItem,
this.newToolStripMenuItem,
this.saveToolStripMenuItem,
this.saveasToolStripMenuItem,
this.closeToolStripMenuItem,
this.exportXmlToolStripMenuItem,
this.langToolStripMenuItem,
this.toolStripMenuItem1,
this.exitToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem");
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
resources.ApplyResources(this.openToolStripMenuItem, "openToolStripMenuItem");
this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click);
//
// newToolStripMenuItem
//
this.newToolStripMenuItem.Name = "newToolStripMenuItem";
resources.ApplyResources(this.newToolStripMenuItem, "newToolStripMenuItem");
this.newToolStripMenuItem.Click += new System.EventHandler(this.newToolStripMenuItem_Click);
//
// saveToolStripMenuItem
//
this.saveToolStripMenuItem.Name = "saveToolStripMenuItem";
resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem");
this.saveToolStripMenuItem.Click += new System.EventHandler(this.saveToolStripMenuItem_Click);
//
// saveasToolStripMenuItem
//
this.saveasToolStripMenuItem.Name = "saveasToolStripMenuItem";
resources.ApplyResources(this.saveasToolStripMenuItem, "saveasToolStripMenuItem");
this.saveasToolStripMenuItem.Click += new System.EventHandler(this.saveasToolStripMenuItem_Click);
//
// closeToolStripMenuItem
//
this.closeToolStripMenuItem.Name = "closeToolStripMenuItem";
resources.ApplyResources(this.closeToolStripMenuItem, "closeToolStripMenuItem");
this.closeToolStripMenuItem.Click += new System.EventHandler(this.closeToolStripMenuItem_Click);
//
// exportXmlToolStripMenuItem
//
this.exportXmlToolStripMenuItem.Name = "exportXmlToolStripMenuItem";
resources.ApplyResources(this.exportXmlToolStripMenuItem, "exportXmlToolStripMenuItem");
this.exportXmlToolStripMenuItem.Click += new System.EventHandler(this.exportXmlToolStripMenuItem_Click);
//
// langToolStripMenuItem
//
this.langToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.englishMenuItem,
this.frenchMenuItem,
this.spanishMenuItem,
this.chineseMenuItem});
this.langToolStripMenuItem.Name = "langToolStripMenuItem";
resources.ApplyResources(this.langToolStripMenuItem, "langToolStripMenuItem");
//
// englishMenuItem
//
this.englishMenuItem.Name = "englishMenuItem";
resources.ApplyResources(this.englishMenuItem, "englishMenuItem");
this.englishMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// frenchMenuItem
//
this.frenchMenuItem.Name = "frenchMenuItem";
resources.ApplyResources(this.frenchMenuItem, "frenchMenuItem");
this.frenchMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// spanishMenuItem
//
this.spanishMenuItem.Name = "spanishMenuItem";
resources.ApplyResources(this.spanishMenuItem, "spanishMenuItem");
this.spanishMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// chineseMenuItem
//
this.chineseMenuItem.Name = "chineseMenuItem";
resources.ApplyResources(this.chineseMenuItem, "chineseMenuItem");
this.chineseMenuItem.Click += new System.EventHandler(this.langMenuItem_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
resources.ApplyResources(this.toolStripMenuItem1, "toolStripMenuItem1");
//
// exitToolStripMenuItem
//
this.exitToolStripMenuItem.Name = "exitToolStripMenuItem";
resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem");
this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click);
//
// regProgressTimer
//
this.regProgressTimer.Tick += new System.EventHandler(this.regProgressTimer_Tick);
//
// itemHoverTimer
//
this.itemHoverTimer.Tick += new System.EventHandler(this.OnItemHover);
//
// tabControl
//
resources.ApplyResources(this.tabControl, "tabControl");
this.tabControl.Controls.Add(this.tabGeneral);
this.tabControl.Controls.Add(this.tabFileSystem);
this.tabControl.Controls.Add(this.tabRegistry);
this.tabControl.Controls.Add(this.tabAdvanced);
this.tabControl.Controls.Add(this.tabSecurity);
this.tabControl.Controls.Add(this.tabWelcome);
this.tabControl.Name = "tabControl";
this.tabControl.SelectedIndex = 0;
this.tabControl.SelectedIndexChanged += new System.EventHandler(this.tabControl_SelectedIndexChanged);
//
// tabGeneral
//
this.tabGeneral.BackColor = System.Drawing.Color.White;
this.tabGeneral.Controls.Add(this.dropboxLabel);
this.tabGeneral.Controls.Add(this.groupBox3);
this.tabGeneral.Controls.Add(this.groupBox1);
this.tabGeneral.Controls.Add(this.dropboxButton);
resources.ApplyResources(this.tabGeneral, "tabGeneral");
this.tabGeneral.Name = "tabGeneral";
//
// dropboxLabel
//
resources.ApplyResources(this.dropboxLabel, "dropboxLabel");
this.dropboxLabel.Name = "dropboxLabel";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.label10);
this.groupBox3.Controls.Add(this.propertyFileVersion);
this.groupBox3.Controls.Add(this.lnkChangeIcon);
this.groupBox3.Controls.Add(this.label2);
this.groupBox3.Controls.Add(this.propertyFriendlyName);
this.groupBox3.Controls.Add(this.propertyIcon);
this.groupBox3.Controls.Add(this.propertyAppID);
this.groupBox3.Controls.Add(this.label1);
resources.ApplyResources(this.groupBox3, "groupBox3");
this.groupBox3.Name = "groupBox3";
this.groupBox3.TabStop = false;
//
// label10
//
resources.ApplyResources(this.label10, "label10");
this.label10.Name = "label10";
//
// propertyFileVersion
//
resources.ApplyResources(this.propertyFileVersion, "propertyFileVersion");
this.propertyFileVersion.Name = "propertyFileVersion";
this.propertyFileVersion.TextChanged += new System.EventHandler(this.PropertyChange);
//
// lnkChangeIcon
//
resources.ApplyResources(this.lnkChangeIcon, "lnkChangeIcon");
this.lnkChangeIcon.Name = "lnkChangeIcon";
this.lnkChangeIcon.TabStop = true;
this.lnkChangeIcon.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkChangeIcon_LinkClicked);
//
// label2
//
resources.ApplyResources(this.label2, "label2");
this.label2.Name = "label2";
//
// propertyFriendlyName
//
resources.ApplyResources(this.propertyFriendlyName, "propertyFriendlyName");
this.propertyFriendlyName.Name = "propertyFriendlyName";
this.propertyFriendlyName.TextChanged += new System.EventHandler(this.PropertyChange);
//
// propertyIcon
//
resources.ApplyResources(this.propertyIcon, "propertyIcon");
this.propertyIcon.Name = "propertyIcon";
this.propertyIcon.TabStop = false;
//
// propertyAppID
//
resources.ApplyResources(this.propertyAppID, "propertyAppID");
this.propertyAppID.Name = "propertyAppID";
this.propertyAppID.TextChanged += new System.EventHandler(this.PropertyChange);
//
// label1
//
resources.ApplyResources(this.label1, "label1");
this.label1.Name = "label1";
//
// groupBox1
//
resources.ApplyResources(this.groupBox1, "groupBox1");
this.groupBox1.Controls.Add(this.groupBox11);
this.groupBox1.Controls.Add(this.groupBox9);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.lblAutoLaunch);
this.groupBox1.Controls.Add(this.groupBox10);
this.groupBox1.Name = "groupBox1";
this.groupBox1.TabStop = false;
//
// groupBox11
//
resources.ApplyResources(this.groupBox11, "groupBox11");
this.groupBox11.Controls.Add(this.lnkAutoLaunch);
this.groupBox11.Controls.Add(this.lnkChangeDataStorage);
this.groupBox11.Controls.Add(this.propertyAutoLaunch);
this.groupBox11.Controls.Add(this.propertyDataStorage);
this.groupBox11.Name = "groupBox11";
this.groupBox11.TabStop = false;
//
// lnkAutoLaunch
//
resources.ApplyResources(this.lnkAutoLaunch, "lnkAutoLaunch");
this.lnkAutoLaunch.Name = "lnkAutoLaunch";
this.lnkAutoLaunch.TabStop = true;
this.lnkAutoLaunch.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkAutoLaunch_LinkClicked);
//
// lnkChangeDataStorage
//
resources.ApplyResources(this.lnkChangeDataStorage, "lnkChangeDataStorage");
this.lnkChangeDataStorage.Name = "lnkChangeDataStorage";
this.lnkChangeDataStorage.TabStop = true;
this.lnkChangeDataStorage.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkChangeDataStorage_LinkClicked);
//
// propertyAutoLaunch
//
resources.ApplyResources(this.propertyAutoLaunch, "propertyAutoLaunch");
this.propertyAutoLaunch.Name = "propertyAutoLaunch";
//
// propertyDataStorage
//
resources.ApplyResources(this.propertyDataStorage, "propertyDataStorage");
this.propertyDataStorage.Name = "propertyDataStorage";
//
// groupBox9
//
resources.ApplyResources(this.groupBox9, "groupBox9");
this.groupBox9.Controls.Add(this.helpVirtMode);
this.groupBox9.Controls.Add(this.picRAM);
this.groupBox9.Controls.Add(this.picDisk);
this.groupBox9.Controls.Add(this.propertyVirtModeRam);
this.groupBox9.Controls.Add(this.propertyVirtModeDisk);
this.groupBox9.Name = "groupBox9";
this.groupBox9.TabStop = false;
//
// helpVirtMode
//
resources.ApplyResources(this.helpVirtMode, "helpVirtMode");
this.helpVirtMode.Name = "helpVirtMode";
//
// picRAM
//
resources.ApplyResources(this.picRAM, "picRAM");
this.picRAM.Name = "picRAM";
this.picRAM.TabStop = false;
//
// picDisk
//
resources.ApplyResources(this.picDisk, "picDisk");
this.picDisk.Name = "picDisk";
this.picDisk.TabStop = false;
//
// propertyVirtModeRam
//
resources.ApplyResources(this.propertyVirtModeRam, "propertyVirtModeRam");
this.propertyVirtModeRam.Name = "propertyVirtModeRam";
this.propertyVirtModeRam.TabStop = true;
this.propertyVirtModeRam.UseVisualStyleBackColor = true;
this.propertyVirtModeRam.CheckedChanged += new System.EventHandler(this.propertyVirtMode_CheckedChanged);
this.propertyVirtModeRam.Click += new System.EventHandler(this.PropertyChange);
//
// propertyVirtModeDisk
//
resources.ApplyResources(this.propertyVirtModeDisk, "propertyVirtModeDisk");
this.propertyVirtModeDisk.Name = "propertyVirtModeDisk";
this.propertyVirtModeDisk.TabStop = true;
this.propertyVirtModeDisk.UseVisualStyleBackColor = true;
this.propertyVirtModeDisk.CheckedChanged += new System.EventHandler(this.propertyVirtMode_CheckedChanged);
this.propertyVirtModeDisk.Click += new System.EventHandler(this.PropertyChange);
//
// label9
//
resources.ApplyResources(this.label9, "label9");
this.label9.Name = "label9";
//
// label5
//
resources.ApplyResources(this.label5, "label5");
this.label5.Name = "label5";
//
// label4
//
resources.ApplyResources(this.label4, "label4");
this.label4.Name = "label4";
//
// lblAutoLaunch
//
resources.ApplyResources(this.lblAutoLaunch, "lblAutoLaunch");
this.lblAutoLaunch.Name = "lblAutoLaunch";
//
// groupBox10
//
resources.ApplyResources(this.groupBox10, "groupBox10");
this.groupBox10.Controls.Add(this.picFullAccess);
this.groupBox10.Controls.Add(this.picIsolatedMode);
this.groupBox10.Controls.Add(this.helpIsolationMode);
this.groupBox10.Controls.Add(this.picDataMode);
this.groupBox10.Controls.Add(this.propertyIsolationDataMode);
this.groupBox10.Controls.Add(this.propertyIsolationIsolated);
this.groupBox10.Controls.Add(this.propertyIsolationMerge);
this.groupBox10.Name = "groupBox10";
this.groupBox10.TabStop = false;
//
// picFullAccess
//
resources.ApplyResources(this.picFullAccess, "picFullAccess");
this.picFullAccess.Name = "picFullAccess";
this.picFullAccess.TabStop = false;
//
// picIsolatedMode
//
resources.ApplyResources(this.picIsolatedMode, "picIsolatedMode");
this.picIsolatedMode.Name = "picIsolatedMode";
this.picIsolatedMode.TabStop = false;
//
// helpIsolationMode
//
resources.ApplyResources(this.helpIsolationMode, "helpIsolationMode");
this.helpIsolationMode.Name = "helpIsolationMode";
//
// picDataMode
//
resources.ApplyResources(this.picDataMode, "picDataMode");
this.picDataMode.Name = "picDataMode";
this.picDataMode.TabStop = false;
//
// propertyIsolationDataMode
//
resources.ApplyResources(this.propertyIsolationDataMode, "propertyIsolationDataMode");
this.propertyIsolationDataMode.Name = "propertyIsolationDataMode";
this.propertyIsolationDataMode.TabStop = true;
this.propertyIsolationDataMode.UseVisualStyleBackColor = true;
this.propertyIsolationDataMode.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationDataMode.Click += new System.EventHandler(this.IsolationChanged);
//
// propertyIsolationIsolated
//
resources.ApplyResources(this.propertyIsolationIsolated, "propertyIsolationIsolated");
this.propertyIsolationIsolated.Name = "propertyIsolationIsolated";
this.propertyIsolationIsolated.TabStop = true;
this.propertyIsolationIsolated.UseVisualStyleBackColor = true;
this.propertyIsolationIsolated.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationIsolated.Click += new System.EventHandler(this.IsolationChanged);
//
// propertyIsolationMerge
//
resources.ApplyResources(this.propertyIsolationMerge, "propertyIsolationMerge");
this.propertyIsolationMerge.Name = "propertyIsolationMerge";
this.propertyIsolationMerge.TabStop = true;
this.propertyIsolationMerge.UseVisualStyleBackColor = true;
this.propertyIsolationMerge.CheckedChanged += new System.EventHandler(this.propertyIsolationMode_CheckedChanged);
this.propertyIsolationMerge.Click += new System.EventHandler(this.IsolationChanged);
//
// dropboxButton
//
resources.ApplyResources(this.dropboxButton, "dropboxButton");
this.dropboxButton.Name = "dropboxButton";
this.dropboxButton.UseVisualStyleBackColor = true;
this.dropboxButton.Click += new System.EventHandler(this.dropboxButton_Click);
//
// tabFileSystem
//
this.tabFileSystem.BackColor = System.Drawing.Color.White;
this.tabFileSystem.Controls.Add(this.panel5);
this.tabFileSystem.Controls.Add(this.fileToolStrip);
resources.ApplyResources(this.tabFileSystem, "tabFileSystem");
this.tabFileSystem.Name = "tabFileSystem";
//
// panel5
//
this.panel5.Controls.Add(this.splitContainer1);
resources.ApplyResources(this.panel5, "panel5");
this.panel5.Name = "panel5";
//
// fileToolStrip
//
this.fileToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fsAddBtn,
this.fsAddEmptyDirBtn,
this.toolStripSeparator3,
this.fsRemoveBtn,
this.toolStripSeparator4,
this.fsAddDirBtn,
this.fsSaveFileAsBtn});
resources.ApplyResources(this.fileToolStrip, "fileToolStrip");
this.fileToolStrip.Name = "fileToolStrip";
//
// fsAddBtn
//
this.fsAddBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddBtn.Image = global::PackageEditor.Properties.Resources._078;
resources.ApplyResources(this.fsAddBtn, "fsAddBtn");
this.fsAddBtn.Name = "fsAddBtn";
//
// fsAddEmptyDirBtn
//
this.fsAddEmptyDirBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddEmptyDirBtn.Image = global::PackageEditor.Properties.Resources._115;
resources.ApplyResources(this.fsAddEmptyDirBtn, "fsAddEmptyDirBtn");
this.fsAddEmptyDirBtn.Name = "fsAddEmptyDirBtn";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
//
// fsRemoveBtn
//
this.fsRemoveBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsRemoveBtn.Image = global::PackageEditor.Properties.Resources._058;
resources.ApplyResources(this.fsRemoveBtn, "fsRemoveBtn");
this.fsRemoveBtn.Name = "fsRemoveBtn";
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
//
// fsAddDirBtn
//
this.fsAddDirBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.fsAddDirBtn.Image = global::PackageEditor.Properties.Resources._019;
resources.ApplyResources(this.fsAddDirBtn, "fsAddDirBtn");
this.fsAddDirBtn.Name = "fsAddDirBtn";
//
// fsSaveFileAsBtn
//
this.fsSaveFileAsBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.fsSaveFileAsBtn, "fsSaveFileAsBtn");
this.fsSaveFileAsBtn.Name = "fsSaveFileAsBtn";
//
// tabRegistry
//
this.tabRegistry.AllowDrop = true;
this.tabRegistry.Controls.Add(this.panel8);
resources.ApplyResources(this.tabRegistry, "tabRegistry");
this.tabRegistry.Name = "tabRegistry";
this.tabRegistry.UseVisualStyleBackColor = true;
this.tabRegistry.DragDrop += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragDrop);
this.tabRegistry.DragEnter += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragEnter);
this.tabRegistry.DragOver += new System.Windows.Forms.DragEventHandler(this.tabRegistry_DragOver);
//
// panel8
//
this.panel8.BackColor = System.Drawing.Color.White;
this.panel8.Controls.Add(this.panel1);
this.panel8.Controls.Add(this.panel7);
resources.ApplyResources(this.panel8, "panel8");
this.panel8.Name = "panel8";
//
// panel1
//
this.panel1.Controls.Add(this.regSplitContainer);
resources.ApplyResources(this.panel1, "panel1");
this.panel1.Name = "panel1";
//
// panel7
//
resources.ApplyResources(this.panel7, "panel7");
this.panel7.Controls.Add(this.regProgressBar);
this.panel7.Controls.Add(this.regToolStrip);
this.panel7.Name = "panel7";
//
// regProgressBar
//
resources.ApplyResources(this.regProgressBar, "regProgressBar");
this.regProgressBar.Name = "regProgressBar";
//
// regToolStrip
//
this.regToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.regRemoveBtn,
this.regEditBtn,
this.toolStripSeparator2,
this.regImportBtn,
this.regExportBtn});
resources.ApplyResources(this.regToolStrip, "regToolStrip");
this.regToolStrip.Name = "regToolStrip";
//
// regRemoveBtn
//
this.regRemoveBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regRemoveBtn, "regRemoveBtn");
this.regRemoveBtn.Name = "regRemoveBtn";
//
// regEditBtn
//
this.regEditBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regEditBtn, "regEditBtn");
this.regEditBtn.Name = "regEditBtn";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
//
// regImportBtn
//
this.regImportBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regImportBtn, "regImportBtn");
this.regImportBtn.Name = "regImportBtn";
this.regImportBtn.Click += new System.EventHandler(this.regImportBtn_Click);
//
// regExportBtn
//
this.regExportBtn.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
resources.ApplyResources(this.regExportBtn, "regExportBtn");
this.regExportBtn.Name = "regExportBtn";
this.regExportBtn.Click += new System.EventHandler(this.regExportBtn_Click);
//
// tabAdvanced
//
this.tabAdvanced.BackColor = System.Drawing.Color.White;
this.tabAdvanced.Controls.Add(this.groupBox5);
this.tabAdvanced.Controls.Add(this.groupBox7);
this.tabAdvanced.Controls.Add(this.groupBox4);
resources.ApplyResources(this.tabAdvanced, "tabAdvanced");
this.tabAdvanced.Name = "tabAdvanced";
//
// groupBox5
//
this.groupBox5.Controls.Add(this.cbVolatileRegistry);
this.groupBox5.Controls.Add(this.propertyScmDirect);
this.groupBox5.Controls.Add(this.propertyDisplayLogo);
this.groupBox5.Controls.Add(this.cbDatFile);
this.groupBox5.Controls.Add(this.lnkAutoUpdate);
this.groupBox5.Controls.Add(this.label8);
this.groupBox5.Controls.Add(this.label7);
this.groupBox5.Controls.Add(this.lnkCustomEvents);
this.groupBox5.Controls.Add(this.propertyStopInheritance);
resources.ApplyResources(this.groupBox5, "groupBox5");
this.groupBox5.Name = "groupBox5";
this.groupBox5.TabStop = false;
//
// cbVolatileRegistry
//
resources.ApplyResources(this.cbVolatileRegistry, "cbVolatileRegistry");
this.cbVolatileRegistry.Name = "cbVolatileRegistry";
this.cbVolatileRegistry.UseVisualStyleBackColor = true;
this.cbVolatileRegistry.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyScmDirect
//
resources.ApplyResources(this.propertyScmDirect, "propertyScmDirect");
this.propertyScmDirect.Name = "propertyScmDirect";
this.propertyScmDirect.UseVisualStyleBackColor = true;
this.propertyScmDirect.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyDisplayLogo
//
resources.ApplyResources(this.propertyDisplayLogo, "propertyDisplayLogo");
this.propertyDisplayLogo.Name = "propertyDisplayLogo";
this.propertyDisplayLogo.UseVisualStyleBackColor = true;
this.propertyDisplayLogo.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// cbDatFile
//
resources.ApplyResources(this.cbDatFile, "cbDatFile");
this.cbDatFile.Name = "cbDatFile";
this.cbDatFile.UseVisualStyleBackColor = true;
this.cbDatFile.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// lnkAutoUpdate
//
resources.ApplyResources(this.lnkAutoUpdate, "lnkAutoUpdate");
this.lnkAutoUpdate.Cursor = System.Windows.Forms.Cursors.Hand;
this.lnkAutoUpdate.Name = "lnkAutoUpdate";
this.lnkAutoUpdate.TabStop = true;
this.lnkAutoUpdate.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkAutoUpdate_LinkClicked);
//
// label8
//
resources.ApplyResources(this.label8, "label8");
this.label8.Name = "label8";
//
// label7
//
resources.ApplyResources(this.label7, "label7");
this.label7.Name = "label7";
//
// lnkCustomEvents
//
resources.ApplyResources(this.lnkCustomEvents, "lnkCustomEvents");
this.lnkCustomEvents.Cursor = System.Windows.Forms.Cursors.Hand;
this.lnkCustomEvents.Name = "lnkCustomEvents";
this.lnkCustomEvents.TabStop = true;
this.lnkCustomEvents.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkCustomEvents_LinkClicked);
//
// propertyStopInheritance
//
resources.ApplyResources(this.propertyStopInheritance, "propertyStopInheritance");
this.propertyStopInheritance.Name = "propertyStopInheritance";
//
// groupBox7
//
this.groupBox7.Controls.Add(this.chkCleanDoneDialog);
this.groupBox7.Controls.Add(this.rdbCleanNone);
this.groupBox7.Controls.Add(this.chkCleanAsk);
this.groupBox7.Controls.Add(this.rdbCleanAll);
this.groupBox7.Controls.Add(this.rdbCleanRegOnly);
resources.ApplyResources(this.groupBox7, "groupBox7");
this.groupBox7.Name = "groupBox7";
this.groupBox7.TabStop = false;
//
// chkCleanDoneDialog
//
resources.ApplyResources(this.chkCleanDoneDialog, "chkCleanDoneDialog");
this.chkCleanDoneDialog.Name = "chkCleanDoneDialog";
this.chkCleanDoneDialog.UseVisualStyleBackColor = true;
this.chkCleanDoneDialog.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbCleanNone
//
resources.ApplyResources(this.rdbCleanNone, "rdbCleanNone");
this.rdbCleanNone.Name = "rdbCleanNone";
this.rdbCleanNone.TabStop = true;
this.rdbCleanNone.UseVisualStyleBackColor = true;
this.rdbCleanNone.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// chkCleanAsk
//
resources.ApplyResources(this.chkCleanAsk, "chkCleanAsk");
this.chkCleanAsk.Name = "chkCleanAsk";
this.chkCleanAsk.UseVisualStyleBackColor = true;
this.chkCleanAsk.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbCleanAll
//
resources.ApplyResources(this.rdbCleanAll, "rdbCleanAll");
this.rdbCleanAll.Name = "rdbCleanAll";
this.rdbCleanAll.TabStop = true;
this.rdbCleanAll.UseVisualStyleBackColor = true;
this.rdbCleanAll.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// rdbCleanRegOnly
//
resources.ApplyResources(this.rdbCleanRegOnly, "rdbCleanRegOnly");
this.rdbCleanRegOnly.Name = "rdbCleanRegOnly";
this.rdbCleanRegOnly.TabStop = true;
this.rdbCleanRegOnly.UseVisualStyleBackColor = true;
this.rdbCleanRegOnly.CheckedChanged += new System.EventHandler(this.rdb_CheckedChanged);
//
// groupBox4
//
this.groupBox4.Controls.Add(this.rdbIntegrateVirtual);
this.groupBox4.Controls.Add(this.rdbIntegrateStandard);
this.groupBox4.Controls.Add(this.rdbIntegrateNone);
resources.ApplyResources(this.groupBox4, "groupBox4");
this.groupBox4.Name = "groupBox4";
this.groupBox4.TabStop = false;
//
// rdbIntegrateVirtual
//
resources.ApplyResources(this.rdbIntegrateVirtual, "rdbIntegrateVirtual");
this.rdbIntegrateVirtual.Name = "rdbIntegrateVirtual";
this.rdbIntegrateVirtual.TabStop = true;
this.rdbIntegrateVirtual.UseVisualStyleBackColor = true;
this.rdbIntegrateVirtual.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbIntegrateStandard
//
resources.ApplyResources(this.rdbIntegrateStandard, "rdbIntegrateStandard");
this.rdbIntegrateStandard.Name = "rdbIntegrateStandard";
this.rdbIntegrateStandard.TabStop = true;
this.rdbIntegrateStandard.UseVisualStyleBackColor = true;
this.rdbIntegrateStandard.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// rdbIntegrateNone
//
resources.ApplyResources(this.rdbIntegrateNone, "rdbIntegrateNone");
this.rdbIntegrateNone.Name = "rdbIntegrateNone";
this.rdbIntegrateNone.TabStop = true;
this.rdbIntegrateNone.UseVisualStyleBackColor = true;
this.rdbIntegrateNone.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// tabSecurity
//
this.tabSecurity.Controls.Add(this.panel10);
this.tabSecurity.Controls.Add(this.groupDataEncrypt);
this.tabSecurity.Controls.Add(this.groupUsageRights);
this.tabSecurity.Controls.Add(this.groupExpiration);
this.tabSecurity.Controls.Add(this.groupEditProtect);
resources.ApplyResources(this.tabSecurity, "tabSecurity");
this.tabSecurity.Name = "tabSecurity";
this.tabSecurity.UseVisualStyleBackColor = true;
//
// panel10
//
resources.ApplyResources(this.panel10, "panel10");
this.panel10.Name = "panel10";
//
// groupDataEncrypt
//
this.groupDataEncrypt.Controls.Add(this.panel16);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUserCreatedPassword);
this.groupDataEncrypt.Controls.Add(this.lnkEncryptionLearnMore);
this.groupDataEncrypt.Controls.Add(this.label12);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionPwdConfirm);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionPwd);
this.groupDataEncrypt.Controls.Add(this.lnkGenerateEncKey);
this.groupDataEncrypt.Controls.Add(this.tbEncryptionKey);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUsingPassword);
this.groupDataEncrypt.Controls.Add(this.propertyEncryptUsingKey);
this.groupDataEncrypt.Controls.Add(this.propertyEncryption);
resources.ApplyResources(this.groupDataEncrypt, "groupDataEncrypt");
this.groupDataEncrypt.Name = "groupDataEncrypt";
this.groupDataEncrypt.TabStop = false;
//
// panel16
//
this.panel16.Controls.Add(this.lnkExportPwdKey);
this.panel16.Controls.Add(this.lnkImportPwdKey);
resources.ApplyResources(this.panel16, "panel16");
this.panel16.Name = "panel16";
//
// lnkExportPwdKey
//
resources.ApplyResources(this.lnkExportPwdKey, "lnkExportPwdKey");
this.lnkExportPwdKey.Name = "lnkExportPwdKey";
this.lnkExportPwdKey.TabStop = true;
this.lnkExportPwdKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkExportPwdKey_LinkClicked);
//
// lnkImportPwdKey
//
resources.ApplyResources(this.lnkImportPwdKey, "lnkImportPwdKey");
this.lnkImportPwdKey.Name = "lnkImportPwdKey";
this.lnkImportPwdKey.TabStop = true;
this.lnkImportPwdKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkImportPwdKey_LinkClicked);
//
// propertyEncryptUserCreatedPassword
//
resources.ApplyResources(this.propertyEncryptUserCreatedPassword, "propertyEncryptUserCreatedPassword");
this.propertyEncryptUserCreatedPassword.Name = "propertyEncryptUserCreatedPassword";
this.propertyEncryptUserCreatedPassword.TabStop = true;
this.propertyEncryptUserCreatedPassword.UseVisualStyleBackColor = true;
//
// lnkEncryptionLearnMore
//
resources.ApplyResources(this.lnkEncryptionLearnMore, "lnkEncryptionLearnMore");
this.lnkEncryptionLearnMore.Name = "lnkEncryptionLearnMore";
this.lnkEncryptionLearnMore.TabStop = true;
this.lnkEncryptionLearnMore.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkEncryptionLearnMore_LinkClicked);
//
// label12
//
resources.ApplyResources(this.label12, "label12");
this.label12.Name = "label12";
//
// tbEncryptionPwdConfirm
//
resources.ApplyResources(this.tbEncryptionPwdConfirm, "tbEncryptionPwdConfirm");
this.tbEncryptionPwdConfirm.Name = "tbEncryptionPwdConfirm";
//
// tbEncryptionPwd
//
resources.ApplyResources(this.tbEncryptionPwd, "tbEncryptionPwd");
this.tbEncryptionPwd.Name = "tbEncryptionPwd";
this.tbEncryptionPwd.Enter += new System.EventHandler(this.tbEncryptionPwd_Enter);
//
// lnkGenerateEncKey
//
resources.ApplyResources(this.lnkGenerateEncKey, "lnkGenerateEncKey");
this.lnkGenerateEncKey.Name = "lnkGenerateEncKey";
this.lnkGenerateEncKey.TabStop = true;
this.lnkGenerateEncKey.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkGenerateEncKey_LinkClicked);
//
// tbEncryptionKey
//
resources.ApplyResources(this.tbEncryptionKey, "tbEncryptionKey");
this.tbEncryptionKey.Name = "tbEncryptionKey";
//
// propertyEncryptUsingPassword
//
resources.ApplyResources(this.propertyEncryptUsingPassword, "propertyEncryptUsingPassword");
this.propertyEncryptUsingPassword.Name = "propertyEncryptUsingPassword";
this.propertyEncryptUsingPassword.TabStop = true;
this.propertyEncryptUsingPassword.UseVisualStyleBackColor = true;
this.propertyEncryptUsingPassword.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// propertyEncryptUsingKey
//
resources.ApplyResources(this.propertyEncryptUsingKey, "propertyEncryptUsingKey");
this.propertyEncryptUsingKey.Name = "propertyEncryptUsingKey";
this.propertyEncryptUsingKey.TabStop = true;
this.propertyEncryptUsingKey.UseVisualStyleBackColor = true;
this.propertyEncryptUsingKey.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// propertyEncryption
//
resources.ApplyResources(this.propertyEncryption, "propertyEncryption");
this.propertyEncryption.Name = "propertyEncryption";
this.propertyEncryption.UseVisualStyleBackColor = true;
this.propertyEncryption.CheckedChanged += new System.EventHandler(this.propertyEncryption_CheckedChanged);
//
// groupUsageRights
//
this.groupUsageRights.Controls.Add(this.lnkActiveDirectory);
resources.ApplyResources(this.groupUsageRights, "groupUsageRights");
this.groupUsageRights.Name = "groupUsageRights";
this.groupUsageRights.TabStop = false;
//
// lnkActiveDirectory
//
resources.ApplyResources(this.lnkActiveDirectory, "lnkActiveDirectory");
this.lnkActiveDirectory.Name = "lnkActiveDirectory";
this.lnkActiveDirectory.TabStop = true;
this.lnkActiveDirectory.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkActiveDirectory_LinkClicked);
//
// groupExpiration
//
this.groupExpiration.Controls.Add(this.propertyExpirationDatePicker);
this.groupExpiration.Controls.Add(this.propertyExpiration);
this.groupExpiration.Controls.Add(this.propertyTtlDays);
this.groupExpiration.Controls.Add(this.propertyTtlResistRemove);
this.groupExpiration.Controls.Add(this.propertyTtlDaysValue);
resources.ApplyResources(this.groupExpiration, "groupExpiration");
this.groupExpiration.Name = "groupExpiration";
this.groupExpiration.TabStop = false;
//
// propertyExpirationDatePicker
//
resources.ApplyResources(this.propertyExpirationDatePicker, "propertyExpirationDatePicker");
this.propertyExpirationDatePicker.Name = "propertyExpirationDatePicker";
//
// propertyExpiration
//
resources.ApplyResources(this.propertyExpiration, "propertyExpiration");
this.propertyExpiration.Name = "propertyExpiration";
this.propertyExpiration.UseVisualStyleBackColor = true;
this.propertyExpiration.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlDays
//
resources.ApplyResources(this.propertyTtlDays, "propertyTtlDays");
this.propertyTtlDays.Name = "propertyTtlDays";
this.propertyTtlDays.UseVisualStyleBackColor = true;
this.propertyTtlDays.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlResistRemove
//
resources.ApplyResources(this.propertyTtlResistRemove, "propertyTtlResistRemove");
this.propertyTtlResistRemove.Name = "propertyTtlResistRemove";
this.propertyTtlResistRemove.UseVisualStyleBackColor = true;
this.propertyTtlResistRemove.CheckedChanged += new System.EventHandler(this.PropertyChange);
//
// propertyTtlDaysValue
//
resources.ApplyResources(this.propertyTtlDaysValue, "propertyTtlDaysValue");
this.propertyTtlDaysValue.Name = "propertyTtlDaysValue";
//
// groupEditProtect
//
this.groupEditProtect.Controls.Add(this.label6);
this.groupEditProtect.Controls.Add(this.tbPasswordConfirm);
this.groupEditProtect.Controls.Add(this.propertyProtPassword);
this.groupEditProtect.Controls.Add(this.propertyProt);
resources.ApplyResources(this.groupEditProtect, "groupEditProtect");
this.groupEditProtect.Name = "groupEditProtect";
this.groupEditProtect.TabStop = false;
//
// label6
//
resources.ApplyResources(this.label6, "label6");
this.label6.Name = "label6";
//
// tbPasswordConfirm
//
resources.ApplyResources(this.tbPasswordConfirm, "tbPasswordConfirm");
this.tbPasswordConfirm.Name = "tbPasswordConfirm";
//
// propertyProtPassword
//
resources.ApplyResources(this.propertyProtPassword, "propertyProtPassword");
this.propertyProtPassword.Name = "propertyProtPassword";
this.propertyProtPassword.Enter += new System.EventHandler(this.propertyProtPassword_Enter);
//
// propertyProt
//
resources.ApplyResources(this.propertyProt, "propertyProt");
this.propertyProt.Name = "propertyProt";
this.propertyProt.UseVisualStyleBackColor = true;
this.propertyProt.CheckedChanged += new System.EventHandler(this.propertyProt_CheckedChanged);
//
// tabWelcome
//
this.tabWelcome.Controls.Add(this.panelWelcome);
resources.ApplyResources(this.tabWelcome, "tabWelcome");
this.tabWelcome.Name = "tabWelcome";
this.tabWelcome.UseVisualStyleBackColor = true;
//
// panelWelcome
//
resources.ApplyResources(this.panelWelcome, "panelWelcome");
this.panelWelcome.BackColor = System.Drawing.Color.White;
this.panelWelcome.Controls.Add(this.panel15);
this.panelWelcome.Controls.Add(this.panel13);
this.panelWelcome.Name = "panelWelcome";
//
// panel15
//
resources.ApplyResources(this.panel15, "panel15");
this.panel15.BackColor = System.Drawing.Color.Transparent;
this.panel15.Controls.Add(this.panel14);
this.panel15.Name = "panel15";
//
// panel14
//
resources.ApplyResources(this.panel14, "panel14");
this.panel14.BackColor = System.Drawing.Color.Transparent;
this.panel14.Controls.Add(this.pictureBox2);
this.panel14.Name = "panel14";
//
// pictureBox2
//
resources.ApplyResources(this.pictureBox2, "pictureBox2");
this.pictureBox2.Name = "pictureBox2";
this.pictureBox2.TabStop = false;
//
// panel13
//
resources.ApplyResources(this.panel13, "panel13");
this.panel13.BackColor = System.Drawing.Color.White;
this.panel13.Controls.Add(this.listViewMRU);
this.panel13.Controls.Add(this.lnkPackageEdit);
this.panel13.Controls.Add(this.panel9);
this.panel13.Name = "panel13";
//
// listViewMRU
//
this.listViewMRU.Activation = System.Windows.Forms.ItemActivation.OneClick;
resources.ApplyResources(this.listViewMRU, "listViewMRU");
this.listViewMRU.BackColor = System.Drawing.Color.White;
this.listViewMRU.BorderStyle = System.Windows.Forms.BorderStyle.None;
this.listViewMRU.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] {
this.columnFileN});
this.listViewMRU.ForeColor = System.Drawing.Color.Blue;
this.listViewMRU.FullRowSelect = true;
this.listViewMRU.Groups.AddRange(new System.Windows.Forms.ListViewGroup[] {
((System.Windows.Forms.ListViewGroup)(resources.GetObject("listViewMRU.Groups"))),
((System.Windows.Forms.ListViewGroup)(resources.GetObject("listViewMRU.Groups1")))});
this.listViewMRU.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None;
this.listViewMRU.LargeImageList = this.imageListMRU;
this.listViewMRU.MultiSelect = false;
this.listViewMRU.Name = "listViewMRU";
this.listViewMRU.SmallImageList = this.imageListMRU;
this.listViewMRU.UseCompatibleStateImageBehavior = false;
this.listViewMRU.View = System.Windows.Forms.View.List;
this.listViewMRU.Click += new System.EventHandler(this.listViewMRU_Click);
//
// columnFileN
//
resources.ApplyResources(this.columnFileN, "columnFileN");
//
// imageListMRU
//
this.imageListMRU.ColorDepth = System.Windows.Forms.ColorDepth.Depth32Bit;
resources.ApplyResources(this.imageListMRU, "imageListMRU");
this.imageListMRU.TransparentColor = System.Drawing.Color.Transparent;
//
// lnkPackageEdit
//
resources.ApplyResources(this.lnkPackageEdit, "lnkPackageEdit");
this.lnkPackageEdit.Name = "lnkPackageEdit";
this.lnkPackageEdit.TabStop = true;
this.lnkPackageEdit.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkPackageEdit_LinkClicked);
this.lnkPackageEdit.Click += new System.EventHandler(this.btnEditPackage_Click);
//
// panel9
//
resources.ApplyResources(this.panel9, "panel9");
this.panel9.Controls.Add(this.label11);
this.panel9.Controls.Add(this.line);
this.panel9.Name = "panel9";
//
// label11
//
resources.ApplyResources(this.label11, "label11");
this.label11.Name = "label11";
//
// line
//
resources.ApplyResources(this.line, "line");
this.line.Name = "line";
this.line.TabStop = false;
//
// bottomPanel
//
this.bottomPanel.Controls.Add(this.panel12);
this.bottomPanel.Controls.Add(this.panel11);
resources.ApplyResources(this.bottomPanel, "bottomPanel");
this.bottomPanel.Name = "bottomPanel";
//
// panel12
//
resources.ApplyResources(this.panel12, "panel12");
this.panel12.Name = "panel12";
this.panel12.TabStop = false;
//
// panel11
//
resources.ApplyResources(this.panel11, "panel11");
this.panel11.Name = "panel11";
this.panel11.TabStop = false;
//
// bkPanel
//
resources.ApplyResources(this.bkPanel, "bkPanel");
this.bkPanel.Controls.Add(this.panelLicense);
this.bkPanel.Name = "bkPanel";
//
// panelLicense
//
resources.ApplyResources(this.panelLicense, "panelLicense");
this.panelLicense.BackColor = System.Drawing.SystemColors.Control;
this.panelLicense.Controls.Add(this.lnkUpgrade);
this.panelLicense.Controls.Add(this.lblNotCommercial);
this.panelLicense.Name = "panelLicense";
//
// lnkUpgrade
//
this.lnkUpgrade.BackColor = System.Drawing.Color.Transparent;
resources.ApplyResources(this.lnkUpgrade, "lnkUpgrade");
this.lnkUpgrade.Name = "lnkUpgrade";
this.lnkUpgrade.TabStop = true;
this.lnkUpgrade.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.lnkUpgrade_LinkClicked);
//
// lblNotCommercial
//
resources.ApplyResources(this.lblNotCommercial, "lblNotCommercial");
this.lblNotCommercial.Name = "lblNotCommercial";
//
// MainForm
//
this.AllowDrop = true;
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.bottomPanel);
this.Controls.Add(this.tabControl);
this.Controls.Add(this.menuStrip1);
this.Controls.Add(this.bkPanel);
this.DoubleBuffered = true;
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainForm_FormClosing);
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainForm_FormClosed);
this.Load += new System.EventHandler(this.MainForm_Load);
this.Shown += new System.EventHandler(this.MainForm_Shown);
this.DragDrop += new System.Windows.Forms.DragEventHandler(this.MainForm_DragDrop);
this.DragEnter += new System.Windows.Forms.DragEventHandler(this.MainForm_DragEnter);
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.fileContextMenu.ResumeLayout(false);
this.panel2.ResumeLayout(false);
this.panel2.PerformLayout();
this.panel3.ResumeLayout(false);
this.regSplitContainer.Panel1.ResumeLayout(false);
this.regSplitContainer.Panel2.ResumeLayout(false);
this.regSplitContainer.Panel2.PerformLayout();
this.regSplitContainer.ResumeLayout(false);
this.ContextMenuStripRegistryFolder.ResumeLayout(false);
this.panel4.ResumeLayout(false);
this.panel4.PerformLayout();
this.panel6.ResumeLayout(false);
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.tabControl.ResumeLayout(false);
this.tabGeneral.ResumeLayout(false);
this.tabGeneral.PerformLayout();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyIcon)).EndInit();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox11.ResumeLayout(false);
this.groupBox11.PerformLayout();
this.groupBox9.ResumeLayout(false);
this.groupBox9.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picRAM)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picDisk)).EndInit();
this.groupBox10.ResumeLayout(false);
this.groupBox10.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.picFullAccess)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picIsolatedMode)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.picDataMode)).EndInit();
this.tabFileSystem.ResumeLayout(false);
this.tabFileSystem.PerformLayout();
this.panel5.ResumeLayout(false);
this.fileToolStrip.ResumeLayout(false);
this.fileToolStrip.PerformLayout();
this.tabRegistry.ResumeLayout(false);
this.panel8.ResumeLayout(false);
this.panel8.PerformLayout();
this.panel1.ResumeLayout(false);
this.panel7.ResumeLayout(false);
this.panel7.PerformLayout();
this.regToolStrip.ResumeLayout(false);
this.regToolStrip.PerformLayout();
this.tabAdvanced.ResumeLayout(false);
this.groupBox5.ResumeLayout(false);
this.groupBox5.PerformLayout();
this.groupBox7.ResumeLayout(false);
this.groupBox7.PerformLayout();
this.groupBox4.ResumeLayout(false);
this.groupBox4.PerformLayout();
this.tabSecurity.ResumeLayout(false);
this.groupDataEncrypt.ResumeLayout(false);
this.groupDataEncrypt.PerformLayout();
this.panel16.ResumeLayout(false);
this.panel16.PerformLayout();
this.groupUsageRights.ResumeLayout(false);
this.groupUsageRights.PerformLayout();
this.groupExpiration.ResumeLayout(false);
this.groupExpiration.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.propertyTtlDaysValue)).EndInit();
this.groupEditProtect.ResumeLayout(false);
this.groupEditProtect.PerformLayout();
this.tabWelcome.ResumeLayout(false);
this.panelWelcome.ResumeLayout(false);
this.panel15.ResumeLayout(false);
this.panel14.ResumeLayout(false);
this.panel14.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit();
this.panel13.ResumeLayout(false);
this.panel13.PerformLayout();
this.panel9.ResumeLayout(false);
this.panel9.PerformLayout();
this.bottomPanel.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.panel12)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.panel11)).EndInit();
this.bkPanel.ResumeLayout(false);
this.panelLicense.ResumeLayout(false);
this.panelLicense.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ImageList imageList;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem saveasToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem closeToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem;
private System.Windows.Forms.Timer regProgressTimer;
private System.Windows.Forms.Timer itemHoverTimer;
private System.Windows.Forms.TabControl tabControl;
private System.Windows.Forms.TabPage tabGeneral;
private System.Windows.Forms.Label dropboxLabel;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox propertyFriendlyName;
private System.Windows.Forms.TextBox propertyAppID;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.LinkLabel lnkAutoLaunch;
private System.Windows.Forms.Label propertyAutoLaunch;
private System.Windows.Forms.LinkLabel lnkChangeIcon;
private System.Windows.Forms.LinkLabel lnkChangeDataStorage;
private System.Windows.Forms.Label propertyDataStorage;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.RadioButton propertyIsolationDataMode;
private System.Windows.Forms.RadioButton propertyIsolationIsolated;
private System.Windows.Forms.RadioButton propertyIsolationMerge;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.PictureBox propertyIcon;
private System.Windows.Forms.Label lblAutoLaunch;
private System.Windows.Forms.Button dropboxButton;
private System.Windows.Forms.TabPage tabFileSystem;
private System.Windows.Forms.Panel panel5;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView fsFolderTree;
private System.Windows.Forms.ListView fsFilesList;
private System.Windows.Forms.ColumnHeader columnFileName;
private System.Windows.Forms.ColumnHeader columnFileSize;
private System.Windows.Forms.Panel panel2;
private System.Windows.Forms.Panel panel3;
private System.Windows.Forms.ComboBox fsFolderInfoIsolationCombo;
private System.Windows.Forms.Label fsFolderInfoIsolationLbl;
private System.Windows.Forms.Label fsFolderInfoFullName;
private System.Windows.Forms.ToolStrip fileToolStrip;
private System.Windows.Forms.ToolStripButton fsAddBtn;
private System.Windows.Forms.ToolStripButton fsAddDirBtn;
private System.Windows.Forms.ToolStripButton fsRemoveBtn;
private System.Windows.Forms.ToolStripButton fsAddEmptyDirBtn;
private System.Windows.Forms.ToolStripButton fsSaveFileAsBtn;
private System.Windows.Forms.TabPage tabRegistry;
private System.Windows.Forms.Panel panel8;
private System.Windows.Forms.Panel panel1;
private System.Windows.Forms.SplitContainer regSplitContainer;
private System.Windows.Forms.TreeView regFolderTree;
private System.Windows.Forms.Panel panel4;
private System.Windows.Forms.Panel panel6;
private System.Windows.Forms.ComboBox regFolderInfoIsolationCombo;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label regFolderInfoFullName;
private System.Windows.Forms.Panel panel7;
private System.Windows.Forms.ProgressBar regProgressBar;
private System.Windows.Forms.ToolStrip regToolStrip;
private System.Windows.Forms.ToolStripButton regRemoveBtn;
private System.Windows.Forms.ToolStripButton regEditBtn;
private System.Windows.Forms.TabPage tabAdvanced;
private System.Windows.Forms.GroupBox groupBox5;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.LinkLabel lnkCustomEvents;
private System.Windows.Forms.TextBox propertyStopInheritance;
private System.Windows.Forms.Panel bkPanel;
private ListViewEx regFilesList;
private System.Windows.Forms.TextBox tbValue;
private System.Windows.Forms.TextBox tbSize;
private System.Windows.Forms.TextBox tbFile;
private System.Windows.Forms.ColumnHeader columnHeader3;
private System.Windows.Forms.ColumnHeader columnHeader4;
private System.Windows.Forms.ColumnHeader columnHeader5;
private System.Windows.Forms.TextBox tbType;
private System.Windows.Forms.PictureBox panel11;
private System.Windows.Forms.PictureBox panel12;
private System.Windows.Forms.Panel bottomPanel;
private System.Windows.Forms.GroupBox groupBox7;
private System.Windows.Forms.CheckBox chkCleanAsk;
private System.Windows.Forms.RadioButton rdbCleanAll;
private System.Windows.Forms.RadioButton rdbCleanRegOnly;
private System.Windows.Forms.RadioButton rdbCleanNone;
private System.Windows.Forms.CheckBox chkCleanDoneDialog;
private System.Windows.Forms.ToolStripMenuItem newToolStripMenuItem;
private System.Windows.Forms.ContextMenuStrip ContextMenuStripRegistryFolder;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItemExport;
private System.Windows.Forms.ToolStripMenuItem deleteToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem exportXmlToolStripMenuItem;
private System.Windows.Forms.Panel panelWelcome;
private System.Windows.Forms.ImageList imageListMRU;
private System.Windows.Forms.TabPage tabWelcome;
private System.Windows.Forms.ToolStripButton regImportBtn;
private System.Windows.Forms.ToolStripButton regExportBtn;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ContextMenuStrip fileContextMenu;
private System.Windows.Forms.ToolStripMenuItem fileContextMenuDelete;
private System.Windows.Forms.ToolStripMenuItem fileContextMenuProperties;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.TextBox propertyFileVersion;
private System.Windows.Forms.ColumnHeader columnFileType;
private System.Windows.Forms.LinkLabel lnkPackageEdit;
private System.Windows.Forms.Panel panel9;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.ListView listViewMRU;
private System.Windows.Forms.ColumnHeader columnFileN;
private System.Windows.Forms.Panel panel13;
private System.Windows.Forms.Panel panel15;
private System.Windows.Forms.Panel panel14;
private System.Windows.Forms.PictureBox pictureBox2;
private System.Windows.Forms.ToolStripMenuItem langToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem englishMenuItem;
private System.Windows.Forms.ToolStripMenuItem frenchMenuItem;
private System.Windows.Forms.ToolStripMenuItem spanishMenuItem;
private System.Windows.Forms.GroupBox groupBox4;
private System.Windows.Forms.RadioButton rdbIntegrateVirtual;
private System.Windows.Forms.RadioButton rdbIntegrateStandard;
private System.Windows.Forms.RadioButton rdbIntegrateNone;
private System.Windows.Forms.ToolStripMenuItem chineseMenuItem;
private System.Windows.Forms.RadioButton propertyVirtModeDisk;
private System.Windows.Forms.RadioButton propertyVirtModeRam;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.LinkLabel lnkAutoUpdate;
private System.Windows.Forms.GroupBox groupBox9;
private System.Windows.Forms.PictureBox picDisk;
private System.Windows.Forms.PictureBox picRAM;
private System.Windows.Forms.Label helpVirtMode;
private System.Windows.Forms.GroupBox groupBox10;
private System.Windows.Forms.Label helpIsolationMode;
private System.Windows.Forms.PictureBox picDataMode;
private System.Windows.Forms.PictureBox picIsolatedMode;
private System.Windows.Forms.PictureBox picFullAccess;
private System.Windows.Forms.GroupBox groupBox11;
private System.Windows.Forms.CheckBox cbDatFile;
private System.Windows.Forms.GroupBox line;
private System.Windows.Forms.CheckBox propertyDisplayLogo;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.Panel panelLicense;
private System.Windows.Forms.Label lblNotCommercial;
private System.Windows.Forms.LinkLabel lnkUpgrade;
private System.Windows.Forms.CheckBox propertyScmDirect;
private System.Windows.Forms.CheckBox cbVolatileRegistry;
private System.Windows.Forms.TabPage tabSecurity;
private System.Windows.Forms.GroupBox groupUsageRights;
private System.Windows.Forms.LinkLabel lnkActiveDirectory;
private System.Windows.Forms.GroupBox groupExpiration;
private System.Windows.Forms.DateTimePicker propertyExpirationDatePicker;
private System.Windows.Forms.CheckBox propertyExpiration;
private System.Windows.Forms.CheckBox propertyTtlDays;
private System.Windows.Forms.CheckBox propertyTtlResistRemove;
private System.Windows.Forms.NumericUpDown propertyTtlDaysValue;
private System.Windows.Forms.GroupBox groupEditProtect;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.TextBox tbPasswordConfirm;
private System.Windows.Forms.TextBox propertyProtPassword;
private System.Windows.Forms.CheckBox propertyProt;
private System.Windows.Forms.GroupBox groupDataEncrypt;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox tbEncryptionPwdConfirm;
private System.Windows.Forms.TextBox tbEncryptionPwd;
private System.Windows.Forms.LinkLabel lnkGenerateEncKey;
private System.Windows.Forms.TextBox tbEncryptionKey;
private System.Windows.Forms.RadioButton propertyEncryptUsingPassword;
private System.Windows.Forms.RadioButton propertyEncryptUsingKey;
private System.Windows.Forms.CheckBox propertyEncryption;
private System.Windows.Forms.Panel panel10;
private System.Windows.Forms.LinkLabel lnkEncryptionLearnMore;
private System.Windows.Forms.RadioButton propertyEncryptUserCreatedPassword;
private System.Windows.Forms.LinkLabel lnkExportPwdKey;
private System.Windows.Forms.Panel panel16;
private System.Windows.Forms.LinkLabel lnkImportPwdKey;
}
}
| |
using System;
using System.Net;
using System.IO;
using System.Threading;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.ComponentModel;
using SteamBot.SteamGroups;
using SteamKit2;
using SteamAPI;
using SteamKit2.Internal;
using SteamAuth;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using SteamAPI.TradeOffers;
using SteamAPI.TradeOffers.Enums;
namespace SteamBot
{
public class Bot : IDisposable
{
#region Bot delegates
public delegate UserHandler UserHandlerCreator(Bot bot, SteamID id);
#endregion
#region Private readonly variables
private readonly SteamUser.LogOnDetails logOnDetails;
private readonly string logFile;
private readonly Dictionary<SteamID, UserHandler> userHandlers;
private readonly Log.LogLevel consoleLogLevel;
private readonly Log.LogLevel fileLogLevel;
private readonly UserHandlerCreator createHandler;
private readonly bool isProccess;
private readonly BackgroundWorker botThread;
#endregion
#region Private variables
private string myUserNonce;
private string myUniqueId;
private bool cookiesAreInvalid = true;
private List<SteamID> friends;
private bool disposed = false;
private string consoleInput;
private DateTime lastConfirmationFetchTime = DateTime.Now;
private bool isFetchingConfirmations = false;
#endregion
#region Public readonly variables
/// <summary>
/// Userhandler class bot is running.
/// </summary>
public readonly string BotControlClass;
/// <summary>
/// The display name of bot to steam.
/// </summary>
public readonly string DisplayName;
/// <summary>
/// The chat response from the config file.
/// </summary>
public readonly string ChatResponse;
/// <summary>
/// An array of admins for bot.
/// </summary>
public readonly IEnumerable<SteamID> Admins;
public readonly SteamClient SteamClient;
public readonly SteamUser SteamUser;
public readonly SteamFriends SteamFriends;
public readonly SteamTrading SteamTrade;
public readonly SteamGameCoordinator SteamGameCoordinator;
/// <summary>
/// The amount of time the bot will trade for.
/// </summary>
public readonly int MaximumTradeTime;
/// <summary>
/// The amount of time the bot will wait between user interactions with trade.
/// </summary>
public readonly int MaximumActionGap;
/// <summary>
/// The api key of bot.
/// </summary>
public readonly string ApiKey;
public readonly SteamAPI.SteamWeb SteamWeb;
/// <summary>
/// The prefix shown before bot's display name.
/// </summary>
public readonly string DisplayNamePrefix;
/// <summary>
/// The time in milliseconds between checking for new trade offers.
/// </value>
public readonly int TradeOfferRefreshRate;
#endregion
#region Public variables
public string AuthCode;
public bool IsRunning;
/// <summary>
/// Is bot fully Logged in.
/// Set only when bot did successfully Log in.
/// </summary>
public bool IsLoggedIn { get; private set; }
/// <summary>
/// The current game bot is in.
/// Default: 0 = No game.
/// </summary>
public int CurrentGame { get; private set; }
/// <summary>
/// The instance of the Logger for the bot.
/// </summary>
public Log Log;
public TradeOffers TradeOffers;
public SteamGuardAccount SteamGuardAccount;
#endregion
public IEnumerable<SteamID> FriendsList
{
get
{
CreateFriendsListIfNecessary();
return friends;
}
}
/// <summary>
/// Compatibility sanity.
/// </summary>
[Obsolete("Refactored to be Log instead of log")]
public Log log { get { return Log; } }
public Bot(Configuration.BotInfo config, string apiKey, UserHandlerCreator handlerCreator, bool debug = false, bool process = false)
{
userHandlers = new Dictionary<SteamID, UserHandler>();
logOnDetails = new SteamUser.LogOnDetails
{
Username = config.Username,
Password = config.Password
};
if (config.UsesTwoFactorAuth)
{
logOnDetails.TwoFactorCode = GetMobileAuthCode();
}
DisplayName = config.DisplayName;
ChatResponse = config.ChatResponse;
TradeOfferRefreshRate = config.TradeOfferRefreshRate;
DisplayNamePrefix = config.DisplayNamePrefix;
Admins = config.Admins;
ApiKey = !String.IsNullOrEmpty(config.ApiKey) ? config.ApiKey : apiKey;
isProccess = process;
try
{
if( config.LogLevel != null )
{
consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.LogLevel, true);
Console.WriteLine(@"(Console) LogLevel configuration parameter used in bot {0} is depreciated and may be removed in future versions. Please use ConsoleLogLevel instead.", DisplayName);
}
else consoleLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.ConsoleLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) ConsoleLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
consoleLogLevel = Log.LogLevel.Info;
}
try
{
fileLogLevel = (Log.LogLevel)Enum.Parse(typeof(Log.LogLevel), config.FileLogLevel, true);
}
catch (ArgumentException)
{
Console.WriteLine(@"(Console) FileLogLevel invalid or unspecified for bot {0}. Defaulting to ""Info""", DisplayName);
fileLogLevel = Log.LogLevel.Info;
}
logFile = config.LogFile;
CreateLog();
createHandler = handlerCreator;
BotControlClass = config.BotControlClass;
SteamWeb = new SteamAPI.SteamWeb();
// Hacking around https
ServicePointManager.ServerCertificateValidationCallback += SteamWeb.ValidateRemoteCertificate;
Log.Debug ("Initializing Steam Bot...");
SteamClient = new SteamClient();
SteamClient.AddHandler(new SteamNotifications());
SteamTrade = SteamClient.GetHandler<SteamTrading>();
SteamUser = SteamClient.GetHandler<SteamUser>();
SteamFriends = SteamClient.GetHandler<SteamFriends>();
SteamGameCoordinator = SteamClient.GetHandler<SteamGameCoordinator>();
botThread = new BackgroundWorker { WorkerSupportsCancellation = true };
botThread.DoWork += BackgroundWorkerOnDoWork;
botThread.RunWorkerCompleted += BackgroundWorkerOnRunWorkerCompleted;
botThread.RunWorkerAsync();
}
~Bot()
{
DisposeBot();
}
private void CreateLog()
{
if(Log == null)
Log = new Log (logFile, DisplayName, consoleLogLevel, fileLogLevel);
}
private void DisposeLog()
{
if(Log != null)
{
Log.Dispose();
Log = null;
}
}
private void CreateFriendsListIfNecessary()
{
if (friends != null)
return;
friends = new List<SteamID>();
for (int i = 0; i < SteamFriends.GetFriendCount(); i++)
friends.Add(SteamFriends.GetFriendByIndex(i));
}
/// <summary>
/// Occurs when the bot needs the SteamGuard authentication code.
/// </summary>
/// <remarks>
/// Return the code in <see cref="SteamGuardRequiredEventArgs.SteamGuard"/>
/// </remarks>
public event EventHandler<SteamGuardRequiredEventArgs> OnSteamGuardRequired;
/// <summary>
/// Starts the callback thread and connects to Steam via SteamKit2.
/// </summary>
/// <remarks>
/// THIS NEVER RETURNS.
/// </remarks>
/// <returns><c>true</c>. See remarks</returns>
public bool StartBot()
{
CreateLog();
IsRunning = true;
Log.Info("Connecting...");
if (!botThread.IsBusy)
botThread.RunWorkerAsync();
SteamClient.Connect();
Log.Success("Done Loading Bot!");
return true; // never get here
}
/// <summary>
/// Disconnect from the Steam network and stop the callback
/// thread.
/// </summary>
public void StopBot()
{
IsRunning = false;
Log.Debug("Trying to shut down bot thread.");
SteamClient.Disconnect();
botThread.CancelAsync();
userHandlers.Clear();
DisposeLog();
}
public void HandleBotCommand(string command)
{
try
{
if (command == "linkauth")
{
LinkMobileAuth();
}
else if (command == "getauth")
{
try
{
Log.Info("Generated Steam Guard code: " + SteamGuardAccount.GenerateSteamGuardCode());
}
catch (NullReferenceException)
{
Log.Error("Unable to generate Steam Guard code.");
}
}
else if (command == "unlinkauth")
{
if (SteamGuardAccount == null)
{
Log.Error("Mobile authenticator is not active on this bot.");
}
else if (SteamGuardAccount.DeactivateAuthenticator())
{
Log.Success("Deactivated authenticator on this account.");
}
else
{
Log.Error("Failed to deactivate authenticator on this account.");
}
}
else
{
GetUserHandler(SteamClient.SteamID).OnBotCommand(command);
}
}
catch (ObjectDisposedException e)
{
// Writing to console because odds are the error was caused by a disposed Log.
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
if (!this.IsRunning)
{
Console.WriteLine("The Bot is no longer running and could not write to the Log. Try Starting this bot first.");
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Exception caught in BotCommand Thread: {0}", e));
}
}
public void HandleInput(string input)
{
consoleInput = input;
}
public string WaitForInput()
{
consoleInput = null;
while (true)
{
if (consoleInput != null)
{
return consoleInput;
}
Thread.Sleep(5);
}
}
public void SetGamePlaying(int id)
{
var gamePlaying = new SteamKit2.ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
if (id != 0)
gamePlaying.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed
{
game_id = new GameID(id),
});
SteamClient.Send(gamePlaying);
CurrentGame = id;
}
void HandleSteamMessage(ICallbackMsg msg)
{
Log.Debug(msg.ToString());
#region Login
msg.Handle<SteamClient.ConnectedCallback> (callback =>
{
Log.Debug ("Connection Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
UserLogOn();
}
else
{
Log.Error ("Failed to connect to Steam Community, trying again...");
SteamClient.Connect ();
}
});
msg.Handle<SteamUser.LoggedOnCallback> (callback =>
{
Log.Debug("Logged On Callback: {0}", callback.Result);
if (callback.Result == EResult.OK)
{
myUserNonce = callback.WebAPIUserNonce;
}
else
{
Log.Error("Login Error: {0}", callback.Result);
}
if (callback.Result == EResult.AccountLogonDeniedNeedTwoFactorCode)
{
var mobileAuthCode = GetMobileAuthCode();
if (string.IsNullOrEmpty(mobileAuthCode))
{
Log.Error("Failed to generate 2FA code. Make sure you have linked the authenticator via SteamBot.");
}
else
{
logOnDetails.TwoFactorCode = mobileAuthCode;
Log.Success("Generated 2FA code.");
}
}
else if (callback.Result == EResult.TwoFactorCodeMismatch)
{
SteamAuth.TimeAligner.AlignTime();
logOnDetails.TwoFactorCode = SteamGuardAccount.GenerateSteamGuardCode();
Log.Success("Regenerated 2FA code.");
}
else if (callback.Result == EResult.AccountLogonDenied)
{
Log.Interface ("This account is SteamGuard enabled. Enter the code via the `auth' command.");
// try to get the steamguard auth code from the event callback
var eva = new SteamGuardRequiredEventArgs();
FireOnSteamGuardRequired(eva);
if (!String.IsNullOrEmpty(eva.SteamGuard))
logOnDetails.AuthCode = eva.SteamGuard;
else
logOnDetails.AuthCode = Console.ReadLine();
}
else if (callback.Result == EResult.InvalidLoginAuthCode)
{
Log.Interface("The given SteamGuard code was invalid. Try again using the `auth' command.");
logOnDetails.AuthCode = Console.ReadLine();
}
});
msg.Handle<SteamUser.LoginKeyCallback> (callback =>
{
myUniqueId = callback.UniqueID.ToString();
UserWebLogOn();
SteamFriends.SetPersonaName (DisplayNamePrefix+DisplayName);
SteamFriends.SetPersonaState (EPersonaState.Online);
Log.Success ("Steam Bot Logged In Completely!");
GetUserHandler(SteamClient.SteamID).OnLoginCompleted();
});
msg.Handle<SteamUser.WebAPIUserNonceCallback>(webCallback =>
{
Log.Debug("Received new WebAPIUserNonce.");
if (webCallback.Result == EResult.OK)
{
myUserNonce = webCallback.Nonce;
UserWebLogOn();
}
else
{
Log.Error("WebAPIUserNonce Error: " + webCallback.Result);
}
});
msg.Handle<SteamUser.UpdateMachineAuthCallback>(
authCallback => OnUpdateMachineAuthCallback(authCallback)
);
#endregion
#region Friends
msg.Handle<SteamFriends.FriendsListCallback>(callback =>
{
foreach (SteamFriends.FriendsListCallback.Friend friend in callback.FriendList)
{
switch (friend.SteamID.AccountType)
{
case EAccountType.Clan:
if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnGroupAdd())
{
AcceptGroupInvite(friend.SteamID);
}
else
{
DeclineGroupInvite(friend.SteamID);
}
}
break;
default:
CreateFriendsListIfNecessary();
if (friend.Relationship == EFriendRelationship.None)
{
friends.Remove(friend.SteamID);
GetUserHandler(friend.SteamID).OnFriendRemove();
RemoveUserHandler(friend.SteamID);
}
else if (friend.Relationship == EFriendRelationship.RequestRecipient)
{
if (GetUserHandler(friend.SteamID).OnFriendAdd())
{
if (!friends.Contains(friend.SteamID))
{
friends.Add(friend.SteamID);
}
else
{
Log.Error("Friend was added who was already in friends list: " + friend.SteamID);
}
SteamFriends.AddFriend(friend.SteamID);
}
else
{
SteamFriends.RemoveFriend(friend.SteamID);
RemoveUserHandler(friend.SteamID);
}
}
break;
}
}
});
msg.Handle<SteamFriends.FriendMsgCallback> (callback =>
{
EChatEntryType type = callback.EntryType;
if (callback.EntryType == EChatEntryType.ChatMsg)
{
Log.Info ("Chat Message from {0}: {1}",
SteamFriends.GetFriendPersonaName (callback.Sender),
callback.Message
);
GetUserHandler(callback.Sender).OnMessageHandler(callback.Message, type);
}
});
#endregion
#region Group Chat
msg.Handle<SteamFriends.ChatMsgCallback>(callback =>
{
GetUserHandler(callback.ChatterID).OnChatRoomMessage(callback.ChatRoomID, callback.ChatterID, callback.Message);
});
#endregion
#region Disconnect
msg.Handle<SteamUser.LoggedOffCallback> (callback =>
{
IsLoggedIn = false;
Log.Warn("Logged off Steam. Reason: {0}", callback.Result);
});
msg.Handle<SteamClient.DisconnectedCallback> (callback =>
{
if(IsLoggedIn)
{
IsLoggedIn = false;
Log.Warn("Disconnected from Steam Network!");
}
SteamClient.Connect ();
});
#endregion
}
string GetMobileAuthCode()
{
var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username));
if (File.Exists(authFile))
{
SteamGuardAccount = JsonConvert.DeserializeObject<SteamGuardAccount>(File.ReadAllText(authFile));
return SteamGuardAccount.GenerateSteamGuardCode();
}
return string.Empty;
}
/// <summary>
/// Link a mobile authenticator to bot account, using SteamTradeOffersBot as the authenticator.
/// Called from bot manager console. Usage: "exec [index] linkauth"
/// If successful, 2FA will be required upon the next login.
/// Use "exec [index] getauth" if you need to get a Steam Guard code for the account.
/// </summary>
void LinkMobileAuth()
{
new Thread(() =>
{
var login = new UserLogin(logOnDetails.Username, logOnDetails.Password);
var loginResult = login.DoLogin();
if (loginResult == LoginResult.NeedEmail)
{
while (loginResult == LoginResult.NeedEmail)
{
Log.Interface("Enter Steam Guard code from email (type \"input [index] [code]\"):");
var emailCode = WaitForInput();
login.EmailCode = emailCode;
loginResult = login.DoLogin();
}
}
if (loginResult == LoginResult.LoginOkay)
{
Log.Info("Linking mobile authenticator...");
var authLinker = new AuthenticatorLinker(login.Session);
var addAuthResult = authLinker.AddAuthenticator();
if (addAuthResult == AuthenticatorLinker.LinkResult.MustProvidePhoneNumber)
{
while (addAuthResult == AuthenticatorLinker.LinkResult.MustProvidePhoneNumber)
{
Log.Interface("Enter phone number with country code, e.g. +1XXXXXXXXXXX (type \"input [index] [number]\"):");
var phoneNumber = WaitForInput();
authLinker.PhoneNumber = phoneNumber;
addAuthResult = authLinker.AddAuthenticator();
}
}
if (addAuthResult == AuthenticatorLinker.LinkResult.AwaitingFinalization)
{
SteamGuardAccount = authLinker.LinkedAccount;
try
{
var authFile = Path.Combine("authfiles", String.Format("{0}.auth", logOnDetails.Username));
Directory.CreateDirectory(Path.Combine(System.Windows.Forms.Application.StartupPath, "authfiles"));
File.WriteAllText(authFile, Newtonsoft.Json.JsonConvert.SerializeObject(SteamGuardAccount));
Log.Interface("Enter SMS code (type \"input [index] [code]\"):");
var smsCode = WaitForInput();
var authResult = authLinker.FinalizeAddAuthenticator(smsCode);
if (authResult == AuthenticatorLinker.FinalizeResult.Success)
{
Log.Success("Linked authenticator.");
}
else
{
Log.Error("Error linking authenticator: " + authResult);
}
}
catch (IOException)
{
Log.Error("Failed to save auth file. Aborting authentication.");
}
}
else
{
Log.Error("Error adding authenticator: " + addAuthResult);
}
}
else
{
if (loginResult == LoginResult.Need2FA)
{
Log.Error("Mobile authenticator has already been linked!");
}
else
{
Log.Error("Error performing mobile login: " + loginResult);
}
}
}).Start();
}
void UserLogOn()
{
// get sentry file which has the machine hw info saved
// from when a steam guard code was entered
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
FileInfo fi = new FileInfo(System.IO.Path.Combine("sentryfiles",String.Format("{0}.sentryfile", logOnDetails.Username)));
if (fi.Exists && fi.Length > 0)
logOnDetails.SentryFileHash = SHAHash(File.ReadAllBytes(fi.FullName));
else
logOnDetails.SentryFileHash = null;
SteamUser.LogOn(logOnDetails);
}
void UserWebLogOn()
{
do
{
IsLoggedIn = SteamWeb.Authenticate(myUniqueId, SteamClient, myUserNonce);
if(!IsLoggedIn)
{
Log.Warn("Authentication failed, retrying in 2s...");
Thread.Sleep(2000);
}
} while(!IsLoggedIn);
Log.Success("User Authenticated!");
cookiesAreInvalid = false;
TradeOffers = new TradeOffers(SteamUser.SteamID, SteamWeb, ApiKey, TradeOfferRefreshRate);
TradeOffers.TradeOfferChecked += TradeOffers_TradeOfferChecked;
TradeOffers.TradeOfferReceived += TradeOffers_TradeOfferReceived;
TradeOffers.TradeOfferAccepted += TradeOffers_TradeOfferAccepted;
TradeOffers.TradeOfferDeclined += TradeOffers_TradeOfferDeclined;
TradeOffers.TradeOfferCanceled += TradeOffers_TradeOfferCanceled;
TradeOffers.TradeOfferInvalid += TradeOffers_TradeOfferInvalid;
TradeOffers.TradeOfferNeedsConfirmation += TradeOffers_TradeOfferNeedsConfirmation;
TradeOffers.TradeOfferInEscrow += TradeOffers_TradeOfferInEscrow;
TradeOffers.TradeOfferNoData += TradeOffers_TradeOfferNoData;
}
private void TradeOffers_TradeOfferChecked(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferChecked(e.TradeOffer);
}
private void TradeOffers_TradeOfferReceived(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferReceived(e.TradeOffer);
}
private void TradeOffers_TradeOfferAccepted(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferAccepted(e.TradeOffer);
}
private void TradeOffers_TradeOfferDeclined(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferDeclined(e.TradeOffer);
}
private void TradeOffers_TradeOfferCanceled(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferCanceled(e.TradeOffer);
}
private void TradeOffers_TradeOfferInvalid(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferInvalid(e.TradeOffer);
}
private void TradeOffers_TradeOfferNeedsConfirmation(object sender, TradeOffers.TradeOfferEventArgs e)
{
if (e.TradeOffer.ConfirmationMethod == TradeOfferConfirmationMethod.MobileApp)
{
if (SteamGuardAccount == null)
{
Log.Warn("Bot account does not have 2FA enabled.");
}
else
{
var confirmed = false;
// try to confirm up to 2 times, refreshing session after first failure
SteamGuardAccount.Session.SteamLogin = SteamWeb.Token;
SteamGuardAccount.Session.SteamLoginSecure = SteamWeb.TokenSecure;
for (var i = 0; i < 2; i++)
{
try
{
foreach (var confirmation in FetchConfirmations())
{
var tradeOfferId = (ulong) SteamGuardAccount.GetConfirmationTradeOfferID(confirmation);
if (tradeOfferId != e.TradeOffer.Id) continue;
if (SteamGuardAccount.AcceptConfirmation(confirmation))
{
Log.Debug("Confirmed {0}. (Confirmation ID #{1})",
confirmation.ConfirmationDescription, confirmation.ConfirmationID);
confirmed = true;
}
break;
}
}
catch (SteamGuardAccount.WGTokenInvalidException)
{
Log.Error("Invalid session when trying to fetch trade confirmations.");
}
catch
{
Log.Error("Unexpected response from Steam when trying to fetch trade confirmations.");
}
if (confirmed)
{
break;
}
SteamGuardAccount.RefreshSession();
CheckCookies();
}
if (confirmed)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferConfirmed(e.TradeOffer);
}
else
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferFailedConfirmation(e.TradeOffer);
}
}
}
else if (e.TradeOffer.ConfirmationMethod == TradeOfferConfirmationMethod.Email)
{
if (e.TradeOffer.IsOurOffer)
{
TradeOffers.CancelTrade(e.TradeOffer);
Log.Error("Cancelling our trade offer #{0} because it needs email confirmation. You need to disable trade confirmations or use the bot as a mobile authenticator.", e.TradeOffer.Id);
}
else
{
TradeOffers.DeclineTrade(e.TradeOffer);
Log.Error("Declining trade offer #{0} because it needs email confirmation. You need to disable trade confirmations or use the bot as a mobile authenticator.", e.TradeOffer.Id);
}
}
}
private void TradeOffers_TradeOfferInEscrow(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferInEscrow(e.TradeOffer);
}
private void TradeOffers_TradeOfferNoData(object sender, TradeOffers.TradeOfferEventArgs e)
{
GetUserHandler(e.TradeOffer.OtherSteamId).OnTradeOfferNoData(e.TradeOffer);
}
private Confirmation[] FetchConfirmations()
{
while (isFetchingConfirmations)
{
Thread.Sleep(1);
}
isFetchingConfirmations = true;
var diffInSeconds = (int)Math.Floor((DateTime.Now - lastConfirmationFetchTime).TotalSeconds);
var secondsToWait = 10 - diffInSeconds;
if (secondsToWait > 0)
{
Thread.Sleep(secondsToWait * 1000);
}
var confirmations = SteamGuardAccount.FetchConfirmations();
lastConfirmationFetchTime = DateTime.Now;
isFetchingConfirmations = false;
return confirmations;
}
/// <summary>
/// Checks if sessionId and token cookies are still valid.
/// Sets cookie flag if they are invalid.
/// </summary>
/// <returns>true if cookies are valid; otherwise false</returns>
bool CheckCookies()
{
// We still haven't re-authenticated
if (cookiesAreInvalid)
return false;
try
{
if (!SteamWeb.VerifyCookies())
{
// Cookies are no longer valid
Log.Warn("Cookies are invalid. Need to re-authenticate.");
cookiesAreInvalid = true;
SteamUser.RequestWebAPIUserNonce();
return false;
}
}
catch
{
// Even if exception is caught, we should still continue.
Log.Warn("Cookie check failed. http://steamcommunity.com is possibly down.");
}
return true;
}
UserHandler GetUserHandler(SteamID sid)
{
if (!userHandlers.ContainsKey(sid))
userHandlers[sid] = createHandler(this, sid);
return userHandlers[sid];
}
void RemoveUserHandler(SteamID sid)
{
if (userHandlers.ContainsKey(sid))
userHandlers.Remove(sid);
}
static byte [] SHAHash (byte[] input)
{
SHA1Managed sha = new SHA1Managed();
byte[] output = sha.ComputeHash( input );
sha.Clear();
return output;
}
void OnUpdateMachineAuthCallback(SteamUser.UpdateMachineAuthCallback machineAuth)
{
byte[] hash = SHAHash (machineAuth.Data);
Directory.CreateDirectory(System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, "sentryfiles"));
File.WriteAllBytes (System.IO.Path.Combine("sentryfiles", String.Format("{0}.sentryfile", logOnDetails.Username)), machineAuth.Data);
var authResponse = new SteamUser.MachineAuthDetails
{
BytesWritten = machineAuth.BytesToWrite,
FileName = machineAuth.FileName,
FileSize = machineAuth.BytesToWrite,
Offset = machineAuth.Offset,
SentryFileHash = hash, // should be the sha1 hash of the sentry file we just wrote
OneTimePassword = machineAuth.OneTimePassword, // not sure on this one yet, since we've had no examples of steam using OTPs
LastError = 0, // result from win32 GetLastError
Result = EResult.OK, // if everything went okay, otherwise ~who knows~
JobID = machineAuth.JobID, // so we respond to the correct server job
};
// send off our response
SteamUser.SendMachineAuthResponse (authResponse);
}
/// <summary>
/// Get duration of escrow in days. Call this before sending a trade offer.
/// Credit to: https://www.reddit.com/r/SteamBot/comments/3w8j7c/code_getescrowduration_for_c/
/// </summary>
/// <param name="steamId">Steam ID of user you want to send a trade offer to</param>
/// <param name="token">User's trade token. Can be an empty string if user is on bot's friends list.</param>
/// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception>
/// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception>
/// <returns>TradeOfferEscrowDuration</returns>
public TradeOfferEscrowDuration GetEscrowDuration(SteamID steamId, string token)
{
var url = "https://steamcommunity.com/tradeoffer/new/";
var data = new System.Collections.Specialized.NameValueCollection
{
{"partner", steamId.AccountID.ToString()}
};
if (!string.IsNullOrEmpty(token))
{
data.Add("token", token);
}
var resp = SteamWeb.Fetch(url, "GET", data, false);
if (string.IsNullOrWhiteSpace(resp))
{
throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration.");
}
return ParseEscrowResponse(resp);
}
/// <summary>
/// Get duration of escrow in days. Call this after receiving a trade offer.
/// </summary>
/// <param name="tradeOfferId">The ID of the trade offer</param>
/// <exception cref="NullReferenceException">Thrown when Steam returns an empty response.</exception>
/// <exception cref="TradeOfferEscrowDurationParseException">Thrown when the user is unavailable for trade or Steam returns invalid data.</exception>
/// <returns>TradeOfferEscrowDuration</returns>
public TradeOfferEscrowDuration GetEscrowDuration(string tradeOfferId)
{
var url = "http://steamcommunity.com/tradeoffer/" + tradeOfferId;
var resp = SteamWeb.Fetch(url, "GET", null, false);
if (string.IsNullOrWhiteSpace(resp))
{
throw new NullReferenceException("Empty response from Steam when trying to retrieve escrow duration.");
}
return ParseEscrowResponse(resp);
}
private TradeOfferEscrowDuration ParseEscrowResponse(string resp)
{
var myM = Regex.Match(resp, @"g_daysMyEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase);
var theirM = Regex.Match(resp, @"g_daysTheirEscrow(?:[\s=]+)(?<days>[\d]+);", RegexOptions.IgnoreCase);
if (!myM.Groups["days"].Success || !theirM.Groups["days"].Success)
{
var steamErrorM = Regex.Match(resp, @"<div id=""error_msg"">([^>]+)<\/div>", RegexOptions.IgnoreCase);
if (steamErrorM.Groups.Count > 1)
{
var steamError = Regex.Replace(steamErrorM.Groups[1].Value.Trim(), @"\t|\n|\r", ""); ;
throw new TradeOfferEscrowDurationParseException(steamError);
}
throw new TradeOfferEscrowDurationParseException(string.Empty);
}
return new TradeOfferEscrowDuration()
{
DaysMyEscrow = int.Parse(myM.Groups["days"].Value),
DaysTheirEscrow = int.Parse(theirM.Groups["days"].Value)
};
}
public class TradeOfferEscrowDuration
{
public int DaysMyEscrow { get; set; }
public int DaysTheirEscrow { get; set; }
}
public class TradeOfferEscrowDurationParseException : Exception
{
public TradeOfferEscrowDurationParseException() : base() { }
public TradeOfferEscrowDurationParseException(string message) : base(message) { }
}
#region Background Worker Methods
private void BackgroundWorkerOnRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs runWorkerCompletedEventArgs)
{
if (runWorkerCompletedEventArgs.Error != null)
{
Exception ex = runWorkerCompletedEventArgs.Error;
Log.Error("Unhandled exceptions in bot {0} callback thread: {1} {2}",
DisplayName,
Environment.NewLine,
ex);
Log.Info("This bot died. Stopping it..");
//backgroundWorker.RunWorkerAsync();
//Thread.Sleep(10000);
StopBot();
//StartBot();
}
DisposeLog();
}
private void BackgroundWorkerOnDoWork(object sender, DoWorkEventArgs doWorkEventArgs)
{
ICallbackMsg msg;
while (!botThread.CancellationPending)
{
try
{
msg = SteamClient.WaitForCallback(true);
HandleSteamMessage(msg);
}
catch (WebException e)
{
Log.Error("URI: {0} >> {1}", (e.Response != null && e.Response.ResponseUri != null ? e.Response.ResponseUri.ToString() : "unknown"), e.ToString());
System.Threading.Thread.Sleep(45000);//Steam is down, retry in 45 seconds.
}
catch (Exception e)
{
Log.Error(e.ToString());
Log.Warn("Restarting bot...");
}
}
}
#endregion Background Worker Methods
private void FireOnSteamGuardRequired(SteamGuardRequiredEventArgs e)
{
// Set to null in case this is another attempt
this.AuthCode = null;
EventHandler<SteamGuardRequiredEventArgs> handler = OnSteamGuardRequired;
if (handler != null)
handler(this, e);
else
{
while (true)
{
if (this.AuthCode != null)
{
e.SteamGuard = this.AuthCode;
break;
}
Thread.Sleep(5);
}
}
}
#region Group Methods
/// <summary>
/// Accepts the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to accept the invite from.</param>
private void AcceptGroupInvite(SteamID group)
{
var AcceptInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
AcceptInvite.Body.GroupID = group.ConvertToUInt64();
AcceptInvite.Body.AcceptInvite = true;
this.SteamClient.Send(AcceptInvite);
}
/// <summary>
/// Declines the invite to a Steam Group
/// </summary>
/// <param name="group">SteamID of the group to decline the invite from.</param>
private void DeclineGroupInvite(SteamID group)
{
var DeclineInvite = new ClientMsg<CMsgGroupInviteAction>((int)EMsg.ClientAcknowledgeClanInvite);
DeclineInvite.Body.GroupID = group.ConvertToUInt64();
DeclineInvite.Body.AcceptInvite = false;
this.SteamClient.Send(DeclineInvite);
}
/// <summary>
/// Invites a use to the specified Steam Group
/// </summary>
/// <param name="user">SteamID of the user to invite.</param>
/// <param name="groupId">SteamID of the group to invite the user to.</param>
public void InviteUserToGroup(SteamID user, SteamID groupId)
{
var InviteUser = new ClientMsg<CMsgInviteUserToGroup>((int)EMsg.ClientInviteUserToClan);
InviteUser.Body.GroupID = groupId.ConvertToUInt64();
InviteUser.Body.Invitee = user.ConvertToUInt64();
InviteUser.Body.UnknownInfo = true;
this.SteamClient.Send(InviteUser);
}
#endregion
public void Dispose()
{
DisposeBot();
GC.SuppressFinalize(this);
}
private void DisposeBot()
{
if (disposed)
return;
disposed = true;
StopBot();
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Buffers;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace HtcSharp.HttpModule.Http.WebUtilities {
// SourceTools-Start
// Remote-File C:\ASP\src\Http\WebUtilities\src\BufferedReadStream.cs
// Start-At-Remote-Line 12
// SourceTools-End
/// <summary>
/// A Stream that wraps another stream and allows reading lines.
/// The data is buffered in memory.
/// </summary>
public class BufferedReadStream : Stream {
private const byte CR = (byte) '\r';
private const byte LF = (byte) '\n';
private readonly Stream _inner;
private readonly byte[] _buffer;
private readonly ArrayPool<byte> _bytePool;
private int _bufferOffset = 0;
private int _bufferCount = 0;
private bool _disposed;
/// <summary>
/// Creates a new stream.
/// </summary>
/// <param name="inner">The stream to wrap.</param>
/// <param name="bufferSize">Size of buffer in bytes.</param>
public BufferedReadStream(Stream inner, int bufferSize)
: this(inner, bufferSize, ArrayPool<byte>.Shared) {
}
/// <summary>
/// Creates a new stream.
/// </summary>
/// <param name="inner">The stream to wrap.</param>
/// <param name="bufferSize">Size of buffer in bytes.</param>
/// <param name="bytePool">ArrayPool for the buffer.</param>
public BufferedReadStream(Stream inner, int bufferSize, ArrayPool<byte> bytePool) {
if (inner == null) {
throw new ArgumentNullException(nameof(inner));
}
_inner = inner;
_bytePool = bytePool;
_buffer = bytePool.Rent(bufferSize);
}
/// <summary>
/// The currently buffered data.
/// </summary>
public ArraySegment<byte> BufferedData {
get { return new ArraySegment<byte>(_buffer, _bufferOffset, _bufferCount); }
}
/// <inheritdoc/>
public override bool CanRead {
get { return _inner.CanRead || _bufferCount > 0; }
}
/// <inheritdoc/>
public override bool CanSeek {
get { return _inner.CanSeek; }
}
/// <inheritdoc/>
public override bool CanTimeout {
get { return _inner.CanTimeout; }
}
/// <inheritdoc/>
public override bool CanWrite {
get { return _inner.CanWrite; }
}
/// <inheritdoc/>
public override long Length {
get { return _inner.Length; }
}
/// <inheritdoc/>
public override long Position {
get { return _inner.Position - _bufferCount; }
set {
if (value < 0) {
throw new ArgumentOutOfRangeException(nameof(value), value, "Position must be positive.");
}
if (value == Position) {
return;
}
// Backwards?
if (value <= _inner.Position) {
// Forward within the buffer?
var innerOffset = (int) (_inner.Position - value);
if (innerOffset <= _bufferCount) {
// Yes, just skip some of the buffered data
_bufferOffset += innerOffset;
_bufferCount -= innerOffset;
} else {
// No, reset the buffer
_bufferOffset = 0;
_bufferCount = 0;
_inner.Position = value;
}
} else {
// Forward, reset the buffer
_bufferOffset = 0;
_bufferCount = 0;
_inner.Position = value;
}
}
}
/// <inheritdoc/>
public override long Seek(long offset, SeekOrigin origin) {
if (origin == SeekOrigin.Begin) {
Position = offset;
} else if (origin == SeekOrigin.Current) {
Position = Position + offset;
} else // if (origin == SeekOrigin.End)
{
Position = Length + offset;
}
return Position;
}
/// <inheritdoc/>
public override void SetLength(long value) {
_inner.SetLength(value);
}
/// <inheritdoc/>
protected override void Dispose(bool disposing) {
if (!_disposed) {
_disposed = true;
_bytePool.Return(_buffer);
if (disposing) {
_inner.Dispose();
}
}
}
/// <inheritdoc/>
public override void Flush() {
_inner.Flush();
}
/// <inheritdoc/>
public override Task FlushAsync(CancellationToken cancellationToken) {
return _inner.FlushAsync(cancellationToken);
}
/// <inheritdoc/>
public override void Write(byte[] buffer, int offset, int count) {
_inner.Write(buffer, offset, count);
}
/// <inheritdoc/>
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) {
return _inner.WriteAsync(buffer, offset, count, cancellationToken);
}
/// <inheritdoc/>
public override int Read(byte[] buffer, int offset, int count) {
ValidateBuffer(buffer, offset, count);
// Drain buffer
if (_bufferCount > 0) {
int toCopy = Math.Min(_bufferCount, count);
Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy);
_bufferOffset += toCopy;
_bufferCount -= toCopy;
return toCopy;
}
return _inner.Read(buffer, offset, count);
}
/// <inheritdoc/>
public async override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) {
ValidateBuffer(buffer, offset, count);
// Drain buffer
if (_bufferCount > 0) {
int toCopy = Math.Min(_bufferCount, count);
Buffer.BlockCopy(_buffer, _bufferOffset, buffer, offset, toCopy);
_bufferOffset += toCopy;
_bufferCount -= toCopy;
return toCopy;
}
return await _inner.ReadAsync(buffer, offset, count, cancellationToken);
}
/// <summary>
/// Ensures that the buffer is not empty.
/// </summary>
/// <returns>Returns <c>true</c> if the buffer is not empty; <c>false</c> otherwise.</returns>
public bool EnsureBuffered() {
if (_bufferCount > 0) {
return true;
}
// Downshift to make room
_bufferOffset = 0;
_bufferCount = _inner.Read(_buffer, 0, _buffer.Length);
return _bufferCount > 0;
}
/// <summary>
/// Ensures that the buffer is not empty.
/// </summary>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Returns <c>true</c> if the buffer is not empty; <c>false</c> otherwise.</returns>
public async Task<bool> EnsureBufferedAsync(CancellationToken cancellationToken) {
if (_bufferCount > 0) {
return true;
}
// Downshift to make room
_bufferOffset = 0;
_bufferCount = await _inner.ReadAsync(_buffer, 0, _buffer.Length, cancellationToken);
return _bufferCount > 0;
}
/// <summary>
/// Ensures that a minimum amount of buffered data is available.
/// </summary>
/// <param name="minCount">Minimum amount of buffered data.</param>
/// <returns>Returns <c>true</c> if the minimum amount of buffered data is available; <c>false</c> otherwise.</returns>
public bool EnsureBuffered(int minCount) {
if (minCount > _buffer.Length) {
throw new ArgumentOutOfRangeException(nameof(minCount), minCount, "The value must be smaller than the buffer size: " + _buffer.Length.ToString());
}
while (_bufferCount < minCount) {
// Downshift to make room
if (_bufferOffset > 0) {
if (_bufferCount > 0) {
Buffer.BlockCopy(_buffer, _bufferOffset, _buffer, 0, _bufferCount);
}
_bufferOffset = 0;
}
int read = _inner.Read(_buffer, _bufferOffset + _bufferCount, _buffer.Length - _bufferCount - _bufferOffset);
_bufferCount += read;
if (read == 0) {
return false;
}
}
return true;
}
/// <summary>
/// Ensures that a minimum amount of buffered data is available.
/// </summary>
/// <param name="minCount">Minimum amount of buffered data.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>Returns <c>true</c> if the minimum amount of buffered data is available; <c>false</c> otherwise.</returns>
public async Task<bool> EnsureBufferedAsync(int minCount, CancellationToken cancellationToken) {
if (minCount > _buffer.Length) {
throw new ArgumentOutOfRangeException(nameof(minCount), minCount, "The value must be smaller than the buffer size: " + _buffer.Length.ToString());
}
while (_bufferCount < minCount) {
// Downshift to make room
if (_bufferOffset > 0) {
if (_bufferCount > 0) {
Buffer.BlockCopy(_buffer, _bufferOffset, _buffer, 0, _bufferCount);
}
_bufferOffset = 0;
}
int read = await _inner.ReadAsync(_buffer, _bufferOffset + _bufferCount, _buffer.Length - _bufferCount - _bufferOffset, cancellationToken);
_bufferCount += read;
if (read == 0) {
return false;
}
}
return true;
}
/// <summary>
/// Reads a line. A line is defined as a sequence of characters followed by
/// a carriage return immediately followed by a line feed. The resulting string does not
/// contain the terminating carriage return and line feed.
/// </summary>
/// <param name="lengthLimit">Maximum allowed line length.</param>
/// <returns>A line.</returns>
public string ReadLine(int lengthLimit) {
CheckDisposed();
using (var builder = new MemoryStream(200)) {
bool foundCR = false, foundCRLF = false;
while (!foundCRLF && EnsureBuffered()) {
if (builder.Length > lengthLimit) {
throw new InvalidDataException($"Line length limit {lengthLimit} exceeded.");
}
ProcessLineChar(builder, ref foundCR, ref foundCRLF);
}
return DecodeLine(builder, foundCRLF);
}
}
/// <summary>
/// Reads a line. A line is defined as a sequence of characters followed by
/// a carriage return immediately followed by a line feed. The resulting string does not
/// contain the terminating carriage return and line feed.
/// </summary>
/// <param name="lengthLimit">Maximum allowed line length.</param>
/// <param name="cancellationToken">Cancellation token.</param>
/// <returns>A line.</returns>
public async Task<string> ReadLineAsync(int lengthLimit, CancellationToken cancellationToken) {
CheckDisposed();
using (var builder = new MemoryStream(200)) {
bool foundCR = false, foundCRLF = false;
while (!foundCRLF && await EnsureBufferedAsync(cancellationToken)) {
if (builder.Length > lengthLimit) {
throw new InvalidDataException($"Line length limit {lengthLimit} exceeded.");
}
ProcessLineChar(builder, ref foundCR, ref foundCRLF);
}
return DecodeLine(builder, foundCRLF);
}
}
private void ProcessLineChar(MemoryStream builder, ref bool foundCR, ref bool foundCRLF) {
var b = _buffer[_bufferOffset];
builder.WriteByte(b);
_bufferOffset++;
_bufferCount--;
if (b == LF && foundCR) {
foundCRLF = true;
return;
}
foundCR = b == CR;
}
private string DecodeLine(MemoryStream builder, bool foundCRLF) {
// Drop the final CRLF, if any
var length = foundCRLF ? builder.Length - 2 : builder.Length;
return Encoding.UTF8.GetString(builder.ToArray(), 0, (int) length);
}
private void CheckDisposed() {
if (_disposed) {
throw new ObjectDisposedException(nameof(BufferedReadStream));
}
}
private void ValidateBuffer(byte[] buffer, int offset, int count) {
// Delegate most of our validation.
var ignored = new ArraySegment<byte>(buffer, offset, count);
if (count == 0) {
throw new ArgumentOutOfRangeException(nameof(count), "The value must be greater than zero.");
}
}
}
}
| |
// 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.IO;
using System.Text;
using Microsoft.Xml.Schema;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
// using System.Security.Policy;
using System.Collections.Generic;
// using System.Security.Permissions;
using System.Runtime.Versioning;
namespace Microsoft.Xml
{
using System;
internal sealed partial class XmlValidatingReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
//
// Private helper types
//
// ParsingFunction = what should the reader do when the next Read() is called
private enum ParsingFunction
{
Read = 0,
Init,
ParseDtdFromContext,
ResolveEntityInternally,
InReadBinaryContent,
ReaderClosed,
Error,
None,
}
internal class ValidationEventHandling : IValidationEventHandling
{
// Fields
private XmlValidatingReaderImpl _reader;
private ValidationEventHandler _eventHandler;
// Constructor
internal ValidationEventHandling(XmlValidatingReaderImpl reader)
{
_reader = reader;
}
// IValidationEventHandling interface
#region IValidationEventHandling interface
object IValidationEventHandling.EventHandler
{
get { return _eventHandler; }
}
void IValidationEventHandling.SendEvent(Exception /*XmlSchemaException*/ exception, XmlSeverityType severity)
{
if (_eventHandler != null)
{
_eventHandler(_reader, new ValidationEventArgs((XmlSchemaException)exception, severity));
}
else if (_reader.ValidationType != ValidationType.None && severity == XmlSeverityType.Error)
{
throw exception;
}
}
#endregion
// XmlValidatingReaderImpl helper methods
internal void AddHandler(ValidationEventHandler handler)
{
_eventHandler += handler;
}
internal void RemoveHandler(ValidationEventHandler handler)
{
_eventHandler -= handler;
}
}
//
// Fields
//
// core text reader
private XmlReader _coreReader;
private XmlTextReaderImpl _coreReaderImpl;
private IXmlNamespaceResolver _coreReaderNSResolver;
// validation
private ValidationType _validationType;
private BaseValidator _validator;
#pragma warning disable 618
private XmlSchemaCollection _schemaCollection;
#pragma warning restore 618
private bool _processIdentityConstraints;
// parsing function (state)
private ParsingFunction _parsingFunction = ParsingFunction.Init;
// event handling
private ValidationEventHandling _eventHandling;
// misc
private XmlParserContext _parserContext;
// helper for Read[Element]ContentAs{Base64,BinHex} methods
private ReadContentAsBinaryHelper _readBinaryHelper;
// Outer XmlReader exposed to the user - either XmlValidatingReader or XmlValidatingReaderImpl (when created via XmlReader.Create).
// Virtual methods called from within XmlValidatingReaderImpl must be called on the outer reader so in case the user overrides
// some of the XmlValidatingReader methods we will call the overriden version.
private XmlReader _outerReader;
//
// Constructors
//
// Initializes a new instance of XmlValidatingReaderImpl class with the specified XmlReader.
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
internal XmlValidatingReaderImpl(XmlReader reader)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(ResXml.Arg_ExpectingXmlTextReader, "reader");
}
_coreReaderImpl.EntityHandling = EntityHandling.ExpandEntities;
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_processIdentityConstraints = true;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.Auto;
SetupValidation(ValidationType.Auto);
#pragma warning restore 618
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified string, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to disable the SxS warning.
internal XmlValidatingReaderImpl(string xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class for parsing fragments with the specified stream, fragment type and parser context
// This constructor is used when creating XmlValidatingReaderImpl for V1 XmlValidatingReader
// SxS: This method resolves an Uri but does not expose it to the caller. It's OK to disable the SxS warning.
internal XmlValidatingReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this(new XmlTextReader(xmlFragment, fragType, context))
{
if (_coreReader.BaseURI.Length > 0)
{
_validator.BaseUri = GetResolver().ResolveUri(null, _coreReader.BaseURI);
}
if (context != null)
{
_parsingFunction = ParsingFunction.ParseDtdFromContext;
_parserContext = context;
}
}
// Initializes a new instance of XmlValidatingReaderImpl class with the specified arguments.
// This constructor is used when creating XmlValidatingReaderImpl reader via "XmlReader.Create(..)"
internal XmlValidatingReaderImpl(XmlReader reader, ValidationEventHandler settingsEventHandler, bool processIdentityConstraints)
{
XmlAsyncCheckReader asyncCheckReader = reader as XmlAsyncCheckReader;
if (asyncCheckReader != null)
{
reader = asyncCheckReader.CoreReader;
}
_outerReader = this;
_coreReader = reader;
_coreReaderImpl = reader as XmlTextReaderImpl;
if (_coreReaderImpl == null)
{
XmlTextReader tr = reader as XmlTextReader;
if (tr != null)
{
_coreReaderImpl = tr.Impl;
}
}
if (_coreReaderImpl == null)
{
throw new ArgumentException(ResXml.Arg_ExpectingXmlTextReader, "reader");
}
_coreReaderImpl.XmlValidatingReaderCompatibilityMode = true;
_coreReaderNSResolver = reader as IXmlNamespaceResolver;
_processIdentityConstraints = processIdentityConstraints;
#pragma warning disable 618
_schemaCollection = new XmlSchemaCollection(_coreReader.NameTable);
#pragma warning restore 618
_schemaCollection.XmlResolver = GetResolver();
_eventHandling = new ValidationEventHandling(this);
if (settingsEventHandler != null)
{
_eventHandling.AddHandler(settingsEventHandler);
}
_coreReaderImpl.ValidationEventHandling = _eventHandling;
_coreReaderImpl.OnDefaultAttributeUse = new XmlTextReaderImpl.OnDefaultAttributeUseDelegate(ValidateDefaultAttributeOnUse);
_validationType = ValidationType.DTD;
SetupValidation(ValidationType.DTD);
}
//
// XmlReader members
//
// Returns the current settings of the reader
public override XmlReaderSettings Settings
{
get
{
XmlReaderSettings settings;
if (_coreReaderImpl.V1Compat)
{
settings = null;
}
else
{
settings = _coreReader.Settings;
}
if (settings != null)
{
settings = settings.Clone();
}
else
{
settings = new XmlReaderSettings();
}
settings.ValidationType = ValidationType.DTD;
if (!_processIdentityConstraints)
{
settings.ValidationFlags &= ~XmlSchemaValidationFlags.ProcessIdentityConstraints;
}
settings.ReadOnly = true;
return settings;
}
}
// Returns the type of the current node.
public override XmlNodeType NodeType
{
get
{
return _coreReader.NodeType;
}
}
// Returns the name of the current node, including prefix.
public override string Name
{
get
{
return _coreReader.Name;
}
}
// Returns local name of the current node (without prefix)
public override string LocalName
{
get
{
return _coreReader.LocalName;
}
}
// Returns namespace name of the current node.
public override string NamespaceURI
{
get
{
return _coreReader.NamespaceURI;
}
}
// Returns prefix associated with the current node.
public override string Prefix
{
get
{
return _coreReader.Prefix;
}
}
// Returns true if the current node can have Value property != string.Empty.
public override bool HasValue
{
get
{
return _coreReader.HasValue;
}
}
// Returns the text value of the current node.
public override string Value
{
get
{
return _coreReader.Value;
}
}
// Returns the depth of the current node in the XML element stack
public override int Depth
{
get
{
return _coreReader.Depth;
}
}
// Returns the base URI of the current node.
public override string BaseURI
{
get
{
return _coreReader.BaseURI;
}
}
// Returns true if the current node is an empty element (for example, <MyElement/>).
public override bool IsEmptyElement
{
get
{
return _coreReader.IsEmptyElement;
}
}
// Returns true of the current node is a default attribute declared in DTD.
public override bool IsDefault
{
get
{
return _coreReader.IsDefault;
}
}
// Returns the quote character used in the current attribute declaration
public override char QuoteChar
{
get
{
return _coreReader.QuoteChar;
}
}
// Returns the current xml:space scope.
public override XmlSpace XmlSpace
{
get
{
return _coreReader.XmlSpace;
}
}
// Returns the current xml:lang scope.</para>
public override string XmlLang
{
get
{
return _coreReader.XmlLang;
}
}
// Returns the current read state of the reader
public override ReadState ReadState
{
get
{
return (_parsingFunction == ParsingFunction.Init) ? ReadState.Initial : _coreReader.ReadState;
}
}
// Returns true if the reader reached end of the input data
public override bool EOF
{
get
{
return _coreReader.EOF;
}
}
// Returns the XmlNameTable associated with this XmlReader
public override XmlNameTable NameTable
{
get
{
return _coreReader.NameTable;
}
}
// Returns encoding of the XML document
internal Encoding Encoding
{
get
{
return _coreReaderImpl.Encoding;
}
}
// Returns the number of attributes on the current node.
public override int AttributeCount
{
get
{
return _coreReader.AttributeCount;
}
}
// Returns value of an attribute with the specified Name
public override string GetAttribute(string name)
{
return _coreReader.GetAttribute(name);
}
// Returns value of an attribute with the specified LocalName and NamespaceURI
public override string GetAttribute(string localName, string namespaceURI)
{
return _coreReader.GetAttribute(localName, namespaceURI);
}
// Returns value of an attribute at the specified index (position)
public override string GetAttribute(int i)
{
return _coreReader.GetAttribute(i);
}
// Moves to an attribute with the specified Name
public override bool MoveToAttribute(string name)
{
if (!_coreReader.MoveToAttribute(name))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute with the specified LocalName and NamespceURI
public override bool MoveToAttribute(string localName, string namespaceURI)
{
if (!_coreReader.MoveToAttribute(localName, namespaceURI))
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to an attribute at the specified index (position)
public override void MoveToAttribute(int i)
{
_coreReader.MoveToAttribute(i);
_parsingFunction = ParsingFunction.Read;
}
// Moves to the first attribute of the current node
public override bool MoveToFirstAttribute()
{
if (!_coreReader.MoveToFirstAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Moves to the next attribute of the current node
public override bool MoveToNextAttribute()
{
if (!_coreReader.MoveToNextAttribute())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// If on attribute, moves to the element that contains the attribute node
public override bool MoveToElement()
{
if (!_coreReader.MoveToElement())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
// Reads and validated next node from the input data
public override bool Read()
{
switch (_parsingFunction)
{
case ParsingFunction.Read:
if (_coreReader.Read())
{
ProcessCoreReaderEvent();
return true;
}
else
{
_validator.CompleteValidation();
return false;
}
case ParsingFunction.ParseDtdFromContext:
_parsingFunction = ParsingFunction.Read;
ParseDtdFromParserContext();
goto case ParsingFunction.Read;
case ParsingFunction.Error:
case ParsingFunction.ReaderClosed:
return false;
case ParsingFunction.Init:
_parsingFunction = ParsingFunction.Read; // this changes the value returned by ReadState
if (_coreReader.ReadState == ReadState.Interactive)
{
ProcessCoreReaderEvent();
return true;
}
else
{
goto case ParsingFunction.Read;
}
case ParsingFunction.ResolveEntityInternally:
_parsingFunction = ParsingFunction.Read;
ResolveEntityInternally();
goto case ParsingFunction.Read;
case ParsingFunction.InReadBinaryContent:
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
goto case ParsingFunction.Read;
default:
Debug.Assert(false);
return false;
}
}
// Closes the input stream ot TextReader, changes the ReadState to Closed and sets all properties to zero/string.Empty
public override void Close()
{
_coreReader.Close();
_parsingFunction = ParsingFunction.ReaderClosed;
}
// Returns NamespaceURI associated with the specified prefix in the current namespace scope.
public override String LookupNamespace(String prefix)
{
return _coreReaderImpl.LookupNamespace(prefix);
}
// Iterates through the current attribute value's text and entity references chunks.
public override bool ReadAttributeValue()
{
if (_parsingFunction == ParsingFunction.InReadBinaryContent)
{
_parsingFunction = ParsingFunction.Read;
_readBinaryHelper.Finish();
}
if (!_coreReader.ReadAttributeValue())
{
return false;
}
_parsingFunction = ParsingFunction.Read;
return true;
}
public override bool CanReadBinaryContent
{
get
{
return true;
}
}
public override int ReadContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBase64(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper if called the first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count)
{
if (ReadState != ReadState.Interactive)
{
return 0;
}
// init ReadChunkHelper when called first time
if (_parsingFunction != ParsingFunction.InReadBinaryContent)
{
_readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, _outerReader);
}
// set parsingFunction to Read state in order to have a normal Read() behavior when called from readBinaryHelper
_parsingFunction = ParsingFunction.Read;
// call to the helper
int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count);
// setup parsingFunction
_parsingFunction = ParsingFunction.InReadBinaryContent;
return readCount;
}
// Returns true if the XmlReader knows how to resolve general entities
public override bool CanResolveEntity
{
get
{
return true;
}
}
// Resolves the current entity reference node
public override void ResolveEntity()
{
if (_parsingFunction == ParsingFunction.ResolveEntityInternally)
{
_parsingFunction = ParsingFunction.Read;
}
_coreReader.ResolveEntity();
}
internal XmlReader OuterReader
{
get
{
return _outerReader;
}
set
{
#pragma warning disable 618
Debug.Assert(value is XmlValidatingReader);
#pragma warning restore 618
_outerReader = value;
}
}
internal void MoveOffEntityReference()
{
if (_outerReader.NodeType == XmlNodeType.EntityReference && _parsingFunction != ParsingFunction.ResolveEntityInternally)
{
if (!_outerReader.Read())
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
}
}
public override string ReadString()
{
MoveOffEntityReference();
return base.ReadString();
}
//
// IXmlLineInfo members
//
public bool HasLineInfo()
{
return true;
}
// Returns the line number of the current node
public int LineNumber
{
get
{
return ((IXmlLineInfo)_coreReader).LineNumber;
}
}
// Returns the line number of the current node
public int LinePosition
{
get
{
return ((IXmlLineInfo)_coreReader).LinePosition;
}
}
//
// IXmlNamespaceResolver members
//
IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope)
{
return this.GetNamespacesInScope(scope);
}
string IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return this.LookupNamespace(prefix);
}
string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return this.LookupPrefix(namespaceName);
}
// Internal IXmlNamespaceResolver methods
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
return _coreReaderNSResolver.GetNamespacesInScope(scope);
}
internal string LookupPrefix(string namespaceName)
{
return _coreReaderNSResolver.LookupPrefix(namespaceName);
}
//
// XmlValidatingReader members
//
// Specufies the validation event handler that wil get warnings and errors related to validation
internal event ValidationEventHandler ValidationEventHandler
{
add
{
_eventHandling.AddHandler(value);
}
remove
{
_eventHandling.RemoveHandler(value); ;
}
}
// returns the schema type of the current node
internal object SchemaType
{
get
{
if (_validationType != ValidationType.None)
{
XmlSchemaType schemaTypeObj = _coreReaderImpl.InternalSchemaType as XmlSchemaType;
if (schemaTypeObj != null && schemaTypeObj.QualifiedName.Namespace == XmlReservedNs.NsXs)
{
return schemaTypeObj.Datatype;
}
return _coreReaderImpl.InternalSchemaType;
}
else
return null;
}
}
// returns the underlying XmlTextReader or XmlTextReaderImpl
internal XmlReader Reader
{
get
{
return (XmlReader)_coreReader;
}
}
// returns the underlying XmlTextReaderImpl
internal XmlTextReaderImpl ReaderImpl
{
get
{
return _coreReaderImpl;
}
}
// specifies the validation type (None, DDT, XSD, XDR, Auto)
internal ValidationType ValidationType
{
get
{
return _validationType;
}
set
{
if (ReadState != ReadState.Initial)
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
_validationType = value;
SetupValidation(value);
}
}
// current schema collection used for validationg
#pragma warning disable 618
internal XmlSchemaCollection Schemas
{
get
{
return _schemaCollection;
}
}
#pragma warning restore 618
// Spefifies whether general entities should be automatically expanded or not
internal EntityHandling EntityHandling
{
get
{
return _coreReaderImpl.EntityHandling;
}
set
{
_coreReaderImpl.EntityHandling = value;
}
}
// Specifies XmlResolver used for opening the XML document and other external references
internal XmlResolver XmlResolver
{
set
{
_coreReaderImpl.XmlResolver = value;
_validator.XmlResolver = value;
_schemaCollection.XmlResolver = value;
}
}
// Disables or enables support of W3C XML 1.0 Namespaces
internal bool Namespaces
{
get
{
return _coreReaderImpl.Namespaces;
}
set
{
_coreReaderImpl.Namespaces = value;
}
}
// Returns typed value of the current node (based on the type specified by schema)
public object ReadTypedValue()
{
if (_validationType == ValidationType.None)
{
return null;
}
switch (_outerReader.NodeType)
{
case XmlNodeType.Attribute:
return _coreReaderImpl.InternalTypedValue;
case XmlNodeType.Element:
if (SchemaType == null)
{
return null;
}
XmlSchemaDatatype dtype = (SchemaType is XmlSchemaDatatype) ? (XmlSchemaDatatype)SchemaType : ((XmlSchemaType)SchemaType).Datatype;
if (dtype != null)
{
if (!_outerReader.IsEmptyElement)
{
for (; ; )
{
if (!_outerReader.Read())
{
throw new InvalidOperationException(ResXml.Xml_InvalidOperation);
}
XmlNodeType type = _outerReader.NodeType;
if (type != XmlNodeType.CDATA && type != XmlNodeType.Text &&
type != XmlNodeType.Whitespace && type != XmlNodeType.SignificantWhitespace &&
type != XmlNodeType.Comment && type != XmlNodeType.ProcessingInstruction)
{
break;
}
}
if (_outerReader.NodeType != XmlNodeType.EndElement)
{
throw new XmlException(ResXml.Xml_InvalidNodeType, _outerReader.NodeType.ToString());
}
}
return _coreReaderImpl.InternalTypedValue;
}
return null;
case XmlNodeType.EndElement:
return null;
default:
if (_coreReaderImpl.V1Compat)
{ //If v1 XmlValidatingReader return null
return null;
}
else
{
return Value;
}
}
}
//
// Private implementation methods
//
private void ParseDtdFromParserContext()
{
Debug.Assert(_parserContext != null);
Debug.Assert(_coreReaderImpl.DtdInfo == null);
if (_parserContext.DocTypeName == null || _parserContext.DocTypeName.Length == 0)
{
return;
}
IDtdParser dtdParser = DtdParser.Create();
XmlTextReaderImpl.DtdParserProxy proxy = new XmlTextReaderImpl.DtdParserProxy(_coreReaderImpl);
IDtdInfo dtdInfo = dtdParser.ParseFreeFloatingDtd(_parserContext.BaseURI, _parserContext.DocTypeName, _parserContext.PublicId,
_parserContext.SystemId, _parserContext.InternalSubset, proxy);
_coreReaderImpl.SetDtdInfo(dtdInfo);
ValidateDtd();
}
private void ValidateDtd()
{
IDtdInfo dtdInfo = _coreReaderImpl.DtdInfo;
if (dtdInfo != null)
{
switch (_validationType)
{
#pragma warning disable 618
case ValidationType.Auto:
SetupValidation(ValidationType.DTD);
goto case ValidationType.DTD;
#pragma warning restore 618
case ValidationType.DTD:
case ValidationType.None:
_validator.DtdInfo = dtdInfo;
break;
}
}
}
private void ResolveEntityInternally()
{
Debug.Assert(_coreReader.NodeType == XmlNodeType.EntityReference);
int initialDepth = _coreReader.Depth;
_outerReader.ResolveEntity();
while (_outerReader.Read() && _coreReader.Depth > initialDepth) ;
}
// SxS: This method resolves an Uri but does not expose it to caller. It's OK to disable the SxS warning.
private void SetupValidation(ValidationType valType)
{
_validator = BaseValidator.CreateInstance(valType, this, _schemaCollection, _eventHandling, _processIdentityConstraints);
XmlResolver resolver = GetResolver();
_validator.XmlResolver = resolver;
if (_outerReader.BaseURI.Length > 0)
{
_validator.BaseUri = (resolver == null) ? new Uri(_outerReader.BaseURI, UriKind.RelativeOrAbsolute) : resolver.ResolveUri(null, _outerReader.BaseURI);
}
_coreReaderImpl.ValidationEventHandling = (_validationType == ValidationType.None) ? null : _eventHandling;
}
private static XmlResolver s_tempResolver;
// This is needed because we can't have the setter for XmlResolver public and with internal getter.
private XmlResolver GetResolver()
{
XmlResolver tempResolver = _coreReaderImpl.GetResolver();
if (tempResolver == null && !_coreReaderImpl.IsResolverSet &&
!Microsoft.Xml.XmlReaderSettings.EnableLegacyXmlSettings())
{
// it is safe to return valid resolver as it'll be used in the schema validation
if (s_tempResolver == null)
s_tempResolver = new XmlUrlResolver();
return s_tempResolver;
}
return tempResolver;
}
//
// Internal methods for validators, DOM, XPathDocument etc.
//
private void ProcessCoreReaderEvent()
{
switch (_coreReader.NodeType)
{
case XmlNodeType.Whitespace:
if (_coreReader.Depth > 0 || _coreReaderImpl.FragmentType != XmlNodeType.Document)
{
if (_validator.PreserveWhitespace)
{
_coreReaderImpl.ChangeCurrentNodeType(XmlNodeType.SignificantWhitespace);
}
}
goto default;
case XmlNodeType.DocumentType:
ValidateDtd();
break;
case XmlNodeType.EntityReference:
_parsingFunction = ParsingFunction.ResolveEntityInternally;
goto default;
default:
_coreReaderImpl.InternalSchemaType = null;
_coreReaderImpl.InternalTypedValue = null;
_validator.Validate();
break;
}
}
internal void Close(bool closeStream)
{
_coreReaderImpl.Close(closeStream);
_parsingFunction = ParsingFunction.ReaderClosed;
}
internal BaseValidator Validator
{
get
{
return _validator;
}
set
{
_validator = value;
}
}
internal override XmlNamespaceManager NamespaceManager
{
get
{
return _coreReaderImpl.NamespaceManager;
}
}
internal bool StandAlone
{
get
{
return _coreReaderImpl.StandAlone;
}
}
internal object SchemaTypeObject
{
set
{
_coreReaderImpl.InternalSchemaType = value;
}
}
internal object TypedValueObject
{
get
{
return _coreReaderImpl.InternalTypedValue;
}
set
{
_coreReaderImpl.InternalTypedValue = value;
}
}
internal bool Normalization
{
get
{
return _coreReaderImpl.Normalization;
}
}
internal bool AddDefaultAttribute(SchemaAttDef attdef)
{
return _coreReaderImpl.AddDefaultAttributeNonDtd(attdef);
}
internal override IDtdInfo DtdInfo
{
get { return _coreReaderImpl.DtdInfo; }
}
internal void ValidateDefaultAttributeOnUse(IDtdDefaultAttributeInfo defaultAttribute, XmlTextReaderImpl coreReader)
{
SchemaAttDef attdef = defaultAttribute as SchemaAttDef;
if (attdef == null)
{
return;
}
if (!attdef.DefaultValueChecked)
{
SchemaInfo schemaInfo = coreReader.DtdInfo as SchemaInfo;
if (schemaInfo == null)
{
return;
}
DtdValidator.CheckDefaultValue(attdef, schemaInfo, _eventHandling, coreReader.BaseURI);
}
}
}
}
| |
//
// TextPart.cs
//
// Author: Jeffrey Stedfast <jeff@xamarin.com>
//
// Copyright (c) 2013 Jeffrey Stedfast
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
using System;
using System.IO;
using System.Text;
using MimeKit.IO;
using MimeKit.IO.Filters;
using MimeKit.Utils;
namespace MimeKit {
/// <summary>
/// A Textual MIME part.
/// </summary>
/// <remarks>
/// <para>Unless overridden, all textual parts parsed by the <see cref="MimeParser"/>,
/// such as text/plain or text/html, will be represented by a <see cref="TextPart"/>.</para>
/// <para>For more information about text media types, see section 4.1 of
/// http://www.ietf.org/rfc/rfc2046.txt</para>
/// </remarks>
public class TextPart : MimePart
{
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.TextPart"/> class.
/// </summary>
/// <remarks>This constructor is used by <see cref="MimeKit.MimeParser"/>.</remarks>
/// <param name="entity">Information used by the constructor.</param>
public TextPart (MimeEntityConstructorInfo entity) : base (entity)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.TextPart"/>
/// class with the specified text subtype.
/// </summary>
/// <param name="subtype">The media subtype.</param>
/// <param name="args">An array of initialization parameters: headers, charset encoding and text.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="subtype"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> is <c>null</c>.</para>
/// </exception>
/// <exception cref="System.ArgumentException">
/// <para><paramref name="args"/> contains more than one <see cref="System.Text.Encoding"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> contains more than one <see cref="System.String"/>.</para>
/// <para>-or-</para>
/// <para><paramref name="args"/> contains one or more arguments of an unknown type.</para>
/// </exception>
public TextPart (string subtype, params object[] args) : this (subtype)
{
if (args == null)
throw new ArgumentNullException ("args");
// Default to UTF8 if not given.
Encoding encoding = null;
string text = null;
foreach (object obj in args) {
if (obj == null || TryInit (obj))
continue;
var enc = obj as Encoding;
if (enc != null) {
if (encoding != null)
throw new ArgumentException ("An encoding should not be specified more than once.");
encoding = enc;
continue;
}
var str = obj as string;
if (str != null) {
if (text != null)
throw new ArgumentException ("The text should not be specified more than once.");
text = str;
continue;
}
throw new ArgumentException ("Unknown initialization parameter: " + obj.GetType ());
}
if (text != null)
SetText (encoding ?? Encoding.UTF8, text);
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.TextPart"/>
/// class with the specified text subtype.
/// </summary>
/// <param name="subtype">The media subtype.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="subtype"/> is <c>null</c>.
/// </exception>
public TextPart (string subtype) : base ("text", subtype)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MimeKit.TextPart"/>
/// class with a Content-Type of text/plain.
/// </summary>
public TextPart () : base ("text", "plain")
{
}
/// <summary>
/// Gets the decoded text content.
/// </summary>
/// <remarks>
/// <para>If the charset parameter on the <see cref="MimeEntity.ContentType"/>
/// is set, it will be used in order to convert the raw content into unicode.
/// If that fails or if the charset parameter is not set, iso-8859-1 will be
/// used instead.</para>
/// <para>For more control, use the <see cref="GetText"/> method.</para>
/// </remarks>
/// <value>The text.</value>
public string Text {
get {
var charset = ContentType.Parameters["charset"];
using (var memory = new MemoryStream ()) {
ContentObject.DecodeTo (memory);
var content = memory.GetBuffer ();
Encoding encoding = null;
if (charset != null) {
try {
encoding = CharsetUtils.GetEncoding (charset);
} catch (NotSupportedException) {
}
}
if (encoding == null)
encoding = Encoding.GetEncoding (28591); // iso-8859-1
return encoding.GetString (content, 0, (int) memory.Length);
}
}
set {
SetText (Encoding.UTF8, value);
}
}
/// <summary>
/// Gets the decoded text content using the provided charset to override
/// the charset specified in the Content-Type parameters.
/// </summary>
/// <returns>The decoded text.</returns>
/// <param name="charset">The charset encoding to use.</param>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="charset"/> is <c>null</c>.
/// </exception>
public string GetText (Encoding charset)
{
if (charset == null)
throw new ArgumentNullException ("charset");
using (var memory = new MemoryStream ()) {
using (var filtered = new FilteredStream (memory)) {
filtered.Add (new CharsetFilter (charset, Encoding.UTF8));
ContentObject.DecodeTo (filtered);
filtered.Flush ();
return Encoding.UTF8.GetString (memory.GetBuffer (), 0, (int) memory.Length);
}
}
}
/// <summary>
/// Sets the text content and the charset parameter in the Content-Type header.
/// </summary>
/// <param name="charset">The charset encoding.</param>
/// <param name="text">The text content.</param>
/// <exception cref="System.ArgumentNullException">
/// <para><paramref name="charset"/> is <c>null</c>.</para>
/// <para>-or-</para>
/// <para><paramref name="text"/> is <c>null</c>.</para>
/// </exception>
public void SetText (Encoding charset, string text)
{
if (charset == null)
throw new ArgumentNullException ("charset");
if (text == null)
throw new ArgumentNullException ("text");
var content = new MemoryStream (charset.GetBytes (text));
ContentObject = new ContentObject (content, ContentEncoding.Default);
ContentType.Parameters["charset"] = CharsetUtils.GetMimeCharset (charset);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="OrderLineReportModel.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Defines the order line report model class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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 Sitecore.Ecommerce.Report
{
using System.Collections.Generic;
using System.Linq;
using Common;
using Diagnostics;
using OrderManagement.Orders;
using Stimulsoft.Base.Design;
/// <summary>
/// Defines the order line report model class.
/// </summary>
public class OrderLineReportModel
{
/// <summary>
/// Gets or sets the order line.
/// </summary>
/// <value>The order line.</value>
[StiBrowsable(false)]
[CanBeNull]
public OrderLine OrderLine { get; set; }
/// <summary>
/// Gets the order line item code.
/// </summary>
/// <value>The order line item code.</value>
[NotNull]
public virtual string OrderLineItemCode
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.Item != null))
{
return this.OrderLine.LineItem.Item.Code;
}
return string.Empty;
}
}
/// <summary>
/// Gets the name of the order line item.
/// </summary>
/// <value>The name of the order line item.</value>
[NotNull]
public virtual string OrderLineItemName
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.Item != null))
{
return this.OrderLine.LineItem.Item.Name;
}
return string.Empty;
}
}
/// <summary>
/// Gets the order line item description.
/// </summary>
/// <value>The order line item description.</value>
[NotNull]
public virtual string OrderLineItemDescription
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.Item != null))
{
return StringUtil.RemoveTags(this.OrderLine.LineItem.Item.Description);
}
return string.Empty;
}
}
/// <summary>
/// Gets the quantity.
/// </summary>
/// <value>The quantity.</value>
public virtual decimal OrderLineQuantity
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null))
{
return this.OrderLine.LineItem.Quantity;
}
return 0;
}
}
/// <summary>
/// Gets the order line price.
/// </summary>
/// <value>The order line price.</value>
[NotNull]
public virtual string OrderLinePrice
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.Price != null) && (this.OrderLine.LineItem.Price.PriceAmount != null))
{
return this.GetAmountRepresentation(this.OrderLine.LineItem.Price.PriceAmount);
}
return string.Empty;
}
}
/// <summary>
/// Gets the order line extension price.
/// </summary>
/// <value>The order line extension price.</value>
[NotNull]
public virtual string OrderLineExtensionPrice
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.LineExtensionAmount != null))
{
return this.GetAmountRepresentation(this.OrderLine.LineItem.LineExtensionAmount);
}
return string.Empty;
}
}
/// <summary>
/// Gets the order line sub-lines.
/// </summary>
/// <value>The order line sub-lines.</value>
[NotNull]
public virtual IEnumerable<SublineReportModel> OrderLineSublines
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.SubLineItem != null))
{
return this.OrderLine.LineItem.SubLineItem.Select(subline => new SublineReportModel { Subline = subline });
}
return Enumerable.Empty<SublineReportModel>();
}
}
/// <summary>
/// Gets the order line total tax amount.
/// </summary>
public virtual string OrderLineTotalTaxAmount
{
get
{
if ((this.OrderLine != null) && (this.OrderLine.LineItem != null) && (this.OrderLine.LineItem.TotalTaxAmount != null))
{
return this.GetAmountRepresentation(this.OrderLine.LineItem.TotalTaxAmount);
}
return string.Empty;
}
}
/// <summary>
/// Gets the order line total tax percent.
/// </summary>
public virtual string OrderLineTotalTaxPercent
{
get
{
if (this.OrderLine != null)
{
int i = this.OrderLine.Order.OrderLines.ToList().IndexOf(this.OrderLine);
TaxSubTotal taxSubtotal = this.OrderLine.Order.TaxTotal.TaxSubtotal.First(ts => ts.CalculationSequenceNumeric == i);
if (null != taxSubtotal)
{
return Utils.MainUtil.FormatPrice(taxSubtotal.TaxCategory.Percent, false, null, null);
}
}
return string.Empty;
}
}
/// <summary>
/// Gets the amount representation.
/// </summary>
/// <param name="amount">The amount.</param>
/// <returns>The amount representation.</returns>
[NotNull]
protected virtual string GetAmountRepresentation([NotNull] Amount amount)
{
Debug.ArgumentNotNull(amount, "amount");
return Utils.MainUtil.FormatPrice(amount.Value, true, null, amount.CurrencyID);
}
}
}
| |
using System;
using System.Collections;
using System.Drawing;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System.Windows.Forms;
using System.Diagnostics;
namespace Voyage.Terraingine.DXViewport
{
/// <summary>
/// A DirectX viewport wrapper.
/// </summary>
public class Viewport
{
#region Data Members
private Device _device;
private Control _window;
private Form _parent;
private Color _clearColor;
private QuaternionCamera _camera;
private Mouse _mouse;
private Keyboard _keyboard;
private bool _deviceLost;
private PresentParameters _presentParams;
private ArrayList _effects;
// Frames per second counters
private int _fps;
private DateTime _lastRender;
#endregion
#region Properties
/// <summary>
/// Gets the DirectX device.
/// </summary>
public Device Device
{
get { return _device; }
}
/// <summary>
/// Gets or sets the window DirectX is loaded in.
/// </summary>
public Control Window
{
get { return _window; }
set
{
ReleaseDevice();
_window = value;
InitializeDevice();
}
}
/// <summary>
/// Gets the parent window of the DirectX control.
/// </summary>
public Form ParentWindow
{
get { return _parent; }
}
/// <summary>
/// Gets or sets the background color of the DirectX window.
/// </summary>
public Color ClearColor
{
get { return _clearColor; }
set { _clearColor = value; }
}
/// <summary>
/// Gets or sets the maximum number of frames rendered per second.
/// </summary>
public int FramesPerSecond
{
get { return _fps; }
set { _fps = value; }
}
/// <summary>
/// Gets or sets the quaternion camera used by the DirectX window.
/// </summary>
public QuaternionCamera Camera
{
get { return _camera; }
set { _camera = value; }
}
/// <summary>
/// Gets the mouse device as polled by the viewport window.
/// </summary>
public Mouse Mouse
{
get { return _mouse; }
}
/// <summary>
/// Gets the keyboard device as polled by the viewport window.
/// </summary>
public Keyboard Keyboard
{
get { return _keyboard; }
}
/// <summary>
/// Gets if the Direct3D device has been lost.
/// </summary>
public bool LostDevice
{
get { return _deviceLost; }
}
/// <summary>
/// Gets or sets the present parameters used by the device.
/// </summary>
public PresentParameters PresentParameters
{
get { return _presentParams; }
set { _presentParams = value; }
}
/// <summary>
/// Gets or sets the list of DirectX Effects usable in rendering.
/// </summary>
public ArrayList Effects
{
get { return _effects; }
set { _effects = value; }
}
/// <summary>
/// Gets the supported version for Vertex Shaders.
/// </summary>
public Version SupportedVertexShaderVersion
{
get { return Manager.GetDeviceCaps( 0, DeviceType.Hardware ).VertexShaderVersion; }
}
/// <summary>
/// Gets the supported version for Pixel Shaders.
/// </summary>
public Version SupportedPixelShaderVersion
{
get { return Manager.GetDeviceCaps( 0, DeviceType.Hardware ).PixelShaderVersion; }
}
/// <summary>
/// Gets the time at the last rendering from the previous rendering.
/// </summary>
public DateTime LastRenderTime
{
get { return _lastRender; }
}
#endregion
#region Initialization And Basic Methods
/// <summary>
/// Creates a DirectX viewport window.
/// </summary>
public Viewport()
{
_camera = null;
_effects = new ArrayList();
}
/// <summary>
/// Creates a DirectX viewport window.
/// </summary>
/// <param name="window">Window to load DirectX into.</param>
/// <param name="parent">Parent form of the DirectX control.</param>
public Viewport( Control window, Form parent )
{
_camera = null;
_effects = new ArrayList();
InitializeDXWindow( window, parent );
}
/// <summary>
/// Safely releases the data within the viewport.
/// </summary>
public void Dispose()
{
ReleaseDevice();
Camera.Dispose();
// Clean up user interface devices
Mouse.Dispose();
Keyboard.Dispose();
// Clean up Effects used
foreach ( Effect e in _effects )
e.Dispose();
_effects.Clear();
}
/// <summary>
/// Initializes the DirectX window.
/// </summary>
/// <param name="window">Window to load DirectX into.</param>
/// <param name="parent">Parent form of the DirectX control.</param>
public void InitializeDXWindow( Control window, Form parent )
{
_window = window;
_parent = parent;
_clearColor = Color.Blue;
_fps = 60;
_lastRender = DateTime.Now;
InitializeDevice();
}
#endregion
#region Device Handling
/// <summary>
/// Initialize the DirectX device.
/// </summary>
/// <returns>Whether the initialization succeeded.</returns>
private bool InitializeDevice()
{
if ( _device != null && !_device.Disposed )
ReleaseDevice();
try
{
_presentParams = new PresentParameters();
_presentParams.Windowed = true;
_presentParams.SwapEffect = SwapEffect.Discard;
_presentParams.EnableAutoDepthStencil = true;
_presentParams.AutoDepthStencilFormat = DepthFormat.D16;
// A window must be specified to load into
// NOTE: If the adapter is updated to become dynamic, make sure to update
// all adapter references
if ( _window != null )
_device = new Device( 0, DeviceType.Hardware, _window.Handle,
CreateFlags.HardwareVertexProcessing, _presentParams );
else
return false;
_device.DeviceReset += new EventHandler( this.OnDeviceReset );
_device.DeviceLost += new EventHandler( this.OnDeviceLost );
InitializeCamera();
OnDeviceReset( this, new System.EventArgs() );
_deviceLost = false;
return true;
}
catch ( DirectXException e )
{
ThrowException( e, true );
if ( _device != null )
{
_device.Dispose();
_device = null;
}
_deviceLost = true;
return false;
}
}
/// <summary>
/// The Direct3D device has been reset; re-initialize information related to
/// DirectX.
/// </summary>
protected void OnDeviceReset( object sender, EventArgs e )
{
ResetCamera();
try
{
_mouse = new Mouse( _parent );
_keyboard = new Keyboard( _parent );
foreach ( Effect fx in _effects )
fx.CreateEffect( _device );
}
catch ( DirectXException exc )
{
ThrowException( exc, true );
if ( _mouse != null )
{
_mouse.Dispose();
_mouse = null;
}
if ( _keyboard != null )
{
_keyboard.Dispose();
_keyboard = null;
}
}
}
/// <summary>
/// Disposes of data lost when the DirectX device was lost.
/// Note: Managed index/vertex buffers are unaffected.
/// </summary>
protected void OnDeviceLost( object sender, EventArgs e )
{
// We would normally dispose of any vertex/index buffers here.
// For the purposes of this library, the user should overload
// the "_device.DeviceLost" property manually, as shown below:
//
// _device.DeviceLost += new EventHandler( this.OnDeviceLost );
//
// This overloading should be done in the user-side code.
// Index/Vertex buffers created using "Pool.Managed" will be
// unaffected.
}
/// <summary>
/// Attemps to recover a lost Direct3D device.
/// </summary>
private void RecoverDevice()
{
try
{
_device.TestCooperativeLevel();
}
catch ( DeviceLostException )
{
// Do nothing
}
catch ( DeviceNotResetException )
{
try
{
_device.Reset( _presentParams );
_deviceLost = false;
Debug.WriteLine( "Device successfully reset." );
}
catch ( DeviceLostException )
{
// Do nothing
}
}
}
/// <summary>
/// Releases the DirectX device.
/// </summary>
protected void ReleaseDevice()
{
_device.Dispose();
}
#endregion
#region Rendering
/// <summary>
/// Checks if it is time to render again (based on the Viewport's frames per second).
/// </summary>
/// <returns>Whether rendering should occur.</returns>
public bool IsTimeToRender()
{
DateTime now = DateTime.Now;
TimeSpan time = now - _lastRender;
bool render = false;
double ms = time.Milliseconds + time.Seconds * 1000 + time.Minutes * 60000 +
time.Hours * 3600000;
if ( ms > ( 1000f / _fps ) )
{
_lastRender = now;
render = true;
}
return render;
}
/// <summary>
/// Begins rendering the DirectX scene.
/// </summary>
public void BeginRender()
{
if ( !_device.Disposed )
{
if ( _deviceLost )
{
RecoverDevice();
}
if ( !_deviceLost )
{
try
{
if ( _presentParams.EnableAutoDepthStencil == true )
_device.Clear( ClearFlags.Target | ClearFlags.ZBuffer, _clearColor, 1.0f, 0 );
else
_device.Clear( ClearFlags.Target, _clearColor, 1.0f, 0 );
_device.BeginScene();
_device.Transform.View = _camera.View;
_device.Transform.World = UpdateCamera();
}
catch ( DeviceLostException )
{
_deviceLost = true;
Debug.WriteLine( "Device was lost." );
}
catch ( DirectXException e )
{
ThrowException( e, false );
}
}
}
}
/// <summary>
/// Ends rendering the DirectX scene.
/// </summary>
public void EndRender()
{
if ( !_device.Disposed )
{
try
{
_device.EndScene();
_device.Present();
}
catch ( DeviceLostException )
{
_deviceLost = true;
}
catch ( DirectXException e )
{
ThrowException( e, false );
}
}
}
#endregion
#region Camera
/// <summary>
/// Initializes the camera used in the DirectX window.
/// </summary>
private void InitializeCamera()
{
if ( _camera == null )
{
Vector3 camEye = new Vector3( 0.0f, 0.0f, 1.0f );
Vector3 camTarget = new Vector3( 0.0f, 0.0f, 0.0f );
_camera = new QuaternionCamera();
_camera.SetViewParameters( camEye, camTarget );
}
}
/// <summary>
/// Updates the world matrix of the camera.
/// </summary>
/// <returns>World transform of the camera.</returns>
private Matrix UpdateCamera()
{
Matrix world = Matrix.Identity;
Vector3 offset = new Vector3();
if ( _mouse != null && _camera.Moving && _mouse.Buttons[0] == false )
_camera.EndMove();
if ( _camera.Moving )
_camera.Move( _mouse.Location );
offset = _camera.Offset;
world = Matrix.Translation( _camera.Offset );
return world;
}
/// <summary>
/// Resets the camera projection parameters.
/// </summary>
public void ResetCamera()
{
_camera.SetProjectionParameters( _camera.FieldOfView,
( float ) _window.Width / _window.Height, _camera.NearPlane, _camera.FarPlane );
_device.Transform.Projection = _camera.Projection;
}
/// <summary>
/// Sets the world matrix of the DirectX device to create a billboard effect.
/// </summary>
public Matrix GetBillboardWorldMatrix()
{
Vector3 normal = _camera.LookVector;
Vector3 right = _camera.RightVector;
Vector3 up = _camera.UpVector;
Matrix billboardMatrix = new Matrix();
// Set Right vector
billboardMatrix.M11 = right.X;
billboardMatrix.M12 = right.Y;
billboardMatrix.M13 = right.Z;
// Set Up vector
billboardMatrix.M21 = up.X;
billboardMatrix.M22 = up.Y;
billboardMatrix.M23 = up.Z;
// Set Look vector
billboardMatrix.M31 = normal.X;
billboardMatrix.M32 = normal.Y;
billboardMatrix.M33 = normal.Z;
billboardMatrix.M44 = 1;
return billboardMatrix;
}
#endregion
#region Other Methods
/// <summary>
/// Alert the user of a DirectX exception.
/// </summary>
/// <param name="e">Exception thrown.</param>
/// <param name="displayMessageBox">Whether or not to display a message box warning.</param>
private void ThrowException( DirectXException e, bool displayMessageBox )
{
string message = "";
message += "Error: " + e.Message + "\n";
message += "\nDirectX Error Message: " + e.ErrorString + "\n";
message += "\nSource: " + e.Source;
if ( displayMessageBox )
{
MessageBox.Show( message,
"Voyage.Terraingine.DXViewport.Viewport.InitializeDevice()",
MessageBoxButtons.OK, MessageBoxIcon.Error );
}
Debug.WriteLine( message );
}
/// <summary>
/// Resize the DirectX window.
/// </summary>
public void ResizeWindow()
{
// Device reset is necessary to prevent line-thickness (pixellation) stretching
_presentParams.BackBufferHeight = _window.Height;
_presentParams.BackBufferWidth = _window.Width;
if ( _window.Height > 0 && _window.Width > 0 )
_device.Reset( _presentParams );
}
#endregion
}
}
| |
using System;
using System.Diagnostics;
using FarseerGames.FarseerPhysics.Mathematics;
#if (XNA)
using Microsoft.Xna.Framework;
#else
using FarseerGames.FarseerPhysics.Mathematics;
#endif
namespace FarseerGames.FarseerPhysics.Dynamics.Joints
{
/// <summary>
/// Creates a revolute joint between 2 bodies.
/// Can be used as wheels on a car.
/// </summary>
public class RevoluteJoint : Joint
{
public event JointDelegate JointUpdated;
private Vector2 _accumulatedImpulse;
private Vector2 _anchor;
private Matrix _b;
private Body _body1;
private Body _body2;
private Vector2 _currentAnchor;
private Vector2 _dv;
private Vector2 _dvBias;
private Vector2 _impulse;
private Vector2 _localAnchor1;
private Vector2 _localAnchor2;
private Matrix _matrix;
private Vector2 _r1;
private Vector2 _r2;
private Vector2 _velocityBias;
public RevoluteJoint()
{
}
public RevoluteJoint(Body body1, Body body2, Vector2 anchor)
{
_body1 = body1;
_body2 = body2;
_anchor = anchor;
body1.GetLocalPosition(ref anchor, out _localAnchor1);
body2.GetLocalPosition(ref anchor, out _localAnchor2);
_accumulatedImpulse = Vector2.Zero;
}
/// <summary>
/// Gets or sets the first body.
/// </summary>
/// <Value>The body1.</Value>
public Body Body1
{
get { return _body1; }
set { _body1 = value; }
}
/// <summary>
/// Gets or sets the second body.
/// </summary>
/// <Value>The body2.</Value>
public Body Body2
{
get { return _body2; }
set { _body2 = value; }
}
/// <summary>
/// Gets or sets the anchor.
/// </summary>
/// <Value>The anchor.</Value>
public Vector2 Anchor
{
get { return _anchor; }
set
{
_anchor = value;
_body1.GetLocalPosition(ref _anchor, out _localAnchor1);
_body2.GetLocalPosition(ref _anchor, out _localAnchor2);
}
}
/// <summary>
/// This gives the anchor position after the simulation starts
/// </summary>
/// <Value>The current anchor.</Value>
public Vector2 CurrentAnchor
{
get
{
Vector2.Add(ref _body1.position, ref _r1, out _currentAnchor); //_anchor moves once simulator starts
return _currentAnchor;
}
}
/// <summary>
/// Sets the initial anchor.
/// </summary>
/// <param name="initialAnchor">The initial anchor.</param>
/// <exception cref="ArgumentNullException"><c>_body1</c> is null.</exception>
public void SetInitialAnchor(Vector2 initialAnchor)
{
_anchor = initialAnchor;
if (_body1 == null)
{
throw new ArgumentNullException("initialAnchor",
"Body must be set prior to setting the _anchor of the Revolute Joint");
}
_body1.GetLocalPosition(ref initialAnchor, out _localAnchor1);
_body2.GetLocalPosition(ref initialAnchor, out _localAnchor2);
}
/// <summary>
/// Validates this instance.
/// </summary>
public override void Validate()
{
if (_body1.IsDisposed || _body2.IsDisposed)
{
Dispose();
}
}
/// <summary>
/// Calculates all the work needed before updating the joint.
/// </summary>
/// <param name="inverseDt">The inverse dt.</param>
public override void PreStep(float inverseDt)
{
if (_body1.isStatic && _body2.isStatic)
return;
if (!_body1.Enabled && !_body2.Enabled)
return;
_body1InverseMass = _body1.inverseMass;
_body1InverseMomentOfInertia = _body1.inverseMomentOfInertia;
_body2InverseMass = _body2.inverseMass;
_body2InverseMomentOfInertia = _body2.inverseMomentOfInertia;
_body1.GetBodyMatrix(out _body1MatrixTemp);
_body2.GetBodyMatrix(out _body2MatrixTemp);
Vector2.TransformNormal(ref _localAnchor1, ref _body1MatrixTemp, out _r1);
Vector2.TransformNormal(ref _localAnchor2, ref _body2MatrixTemp, out _r2);
_k1.M11 = _body1InverseMass + _body2InverseMass;
_k1.M12 = 0;
_k1.M21 = 0;
_k1.M22 = _body1InverseMass + _body2InverseMass;
_k2.M11 = _body1InverseMomentOfInertia * _r1.Y * _r1.Y;
_k2.M12 = -_body1InverseMomentOfInertia * _r1.X * _r1.Y;
_k2.M21 = -_body1InverseMomentOfInertia * _r1.X * _r1.Y;
_k2.M22 = _body1InverseMomentOfInertia * _r1.X * _r1.X;
_k3.M11 = _body2InverseMomentOfInertia * _r2.Y * _r2.Y;
_k3.M12 = -_body2InverseMomentOfInertia * _r2.X * _r2.Y;
_k3.M21 = -_body2InverseMomentOfInertia * _r2.X * _r2.Y;
_k3.M22 = _body2InverseMomentOfInertia * _r2.X * _r2.X;
//Matrix _k = _k1 + _k2 + _k3;
Matrix.Add(ref _k1, ref _k2, out _k);
Matrix.Add(ref _k, ref _k3, out _k);
_k.M11 += Softness;
_k.M12 += Softness;
//_matrix = MatrixInvert2D(_k);
MatrixInvert2D(ref _k, out _matrix);
Vector2.Add(ref _body1.position, ref _r1, out _vectorTemp1);
Vector2.Add(ref _body2.position, ref _r2, out _vectorTemp2);
Vector2.Subtract(ref _vectorTemp2, ref _vectorTemp1, out _vectorTemp3);
Vector2.Multiply(ref _vectorTemp3, -BiasFactor * inverseDt, out _velocityBias);
JointError = _vectorTemp3.Length();
_body2.ApplyImmediateImpulse(ref _accumulatedImpulse);
Calculator.Cross(ref _r2, ref _accumulatedImpulse, out _floatTemp1);
_body2.ApplyAngularImpulse(_floatTemp1);
Vector2.Multiply(ref _accumulatedImpulse, -1, out _vectorTemp1);
_body1.ApplyImmediateImpulse(ref _vectorTemp1);
Calculator.Cross(ref _r1, ref _accumulatedImpulse, out _floatTemp1);
_body1.ApplyAngularImpulse(-_floatTemp1);
}
private void MatrixInvert2D(ref Matrix matrix, out Matrix invertedMatrix)
{
float a = matrix.M11, b = matrix.M12, c = matrix.M21, d = matrix.M22;
float det = a * d - b * c;
Debug.Assert(det != 0.0f);
det = 1.0f / det;
_b.M11 = det * d;
_b.M12 = -det * b;
_b.M21 = -det * c;
_b.M22 = det * a;
invertedMatrix = _b;
}
/// <summary>
/// Updates this instance.
/// </summary>
public override void Update()
{
base.Update();
if (_body1.isStatic && _body2.isStatic)
return;
if (!_body1.Enabled && !_body2.Enabled)
return;
#region INLINE: Calculator.Cross(ref _body2.AngularVelocity, ref _r2, out _vectorTemp1);
_vectorTemp1.X = -_body2.AngularVelocity * _r2.Y;
_vectorTemp1.Y = _body2.AngularVelocity * _r2.X;
#endregion
#region INLINE: Calculator.Cross(ref _body1.AngularVelocity, ref _r1, out _vectorTemp2);
_vectorTemp2.X = -_body1.AngularVelocity * _r1.Y;
_vectorTemp2.Y = _body1.AngularVelocity * _r1.X;
#endregion
#region INLINE: Vector2.Add(ref _body2.linearVelocity, ref _vectorTemp1, out _vectorTemp3);
_vectorTemp3.X = _body2.LinearVelocity.X + _vectorTemp1.X;
_vectorTemp3.Y = _body2.LinearVelocity.Y + _vectorTemp1.Y;
#endregion
#region INLINE: Vector2.Add(ref _body1.linearVelocity, ref _vectorTemp2, out _vectorTemp4);
_vectorTemp4.X = _body1.LinearVelocity.X + _vectorTemp2.X;
_vectorTemp4.Y = _body1.LinearVelocity.Y + _vectorTemp2.Y;
#endregion
#region INLINE: Vector2.Subtract(ref _vectorTemp3, ref _vectorTemp4, out _dv);
_dv.X = _vectorTemp3.X - _vectorTemp4.X;
_dv.Y = _vectorTemp3.Y - _vectorTemp4.Y;
#endregion
#region INLINE: Vector2.Subtract(ref _velocityBias, ref _dv, out _vectorTemp1);
_vectorTemp1.X = _velocityBias.X - _dv.X;
_vectorTemp1.Y = _velocityBias.Y - _dv.Y;
#endregion
#region INLINE: Vector2.Multiply(ref _accumulatedImpulse, _softness, out _vectorTemp2);
_vectorTemp2.X = _accumulatedImpulse.X * Softness;
_vectorTemp2.Y = _accumulatedImpulse.Y * Softness;
#endregion
#region INLINE: Vector2.Subtract(ref _vectorTemp1, ref _vectorTemp2, out _dvBias);
_dvBias.X = _vectorTemp1.X - _vectorTemp2.X;
_dvBias.Y = _vectorTemp1.Y - _vectorTemp2.Y;
#endregion
#region INLINE: Vector2.Transform(ref _dvBias, ref _matrix, out _impulse);
float num2 = ((_dvBias.X * _matrix.M11) + (_dvBias.Y * _matrix.M21)) + _matrix.M41;
float num = ((_dvBias.X * _matrix.M12) + (_dvBias.Y * _matrix.M22)) + _matrix.M42;
_impulse.X = num2;
_impulse.Y = num;
#endregion
#region INLINE: Vector2.Add(ref _accumulatedImpulse, ref _impulse, out _accumulatedImpulse);
_accumulatedImpulse.X = _accumulatedImpulse.X + _impulse.X;
_accumulatedImpulse.Y = _accumulatedImpulse.Y + _impulse.Y;
#endregion
if (_impulse != Vector2.Zero)
{
#region INLINE: _body2.ApplyImpulse(ref _impulse);
_dv.X = _impulse.X * _body2.inverseMass;
_dv.Y = _impulse.Y * _body2.inverseMass;
_body2.LinearVelocity.X = _dv.X + _body2.LinearVelocity.X;
_body2.LinearVelocity.Y = _dv.Y + _body2.LinearVelocity.Y;
#endregion
#region INLINE: Calculator.Cross(ref _r2, ref _impulse, out _floatTemp1);
_floatTemp1 = _r2.X * _impulse.Y - _r2.Y * _impulse.X;
#endregion
#region INLINE: _body2.ApplyAngularImpulse(ref _floatTemp1);
_body2.AngularVelocity += _floatTemp1 * _body2.inverseMomentOfInertia;
#endregion
#region INLINE: Vector2.Multiply(ref _impulse, -1, out _vectorTemp1);
_vectorTemp1.X = _impulse.X * -1;
_vectorTemp1.Y = _impulse.Y * -1;
#endregion
#region INLINE: _body1.ApplyImpulse(ref _vectorTemp1);
_dv.X = _vectorTemp1.X * _body1.inverseMass;
_dv.Y = _vectorTemp1.Y * _body1.inverseMass;
_body1.LinearVelocity.X = _dv.X + _body1.LinearVelocity.X;
_body1.LinearVelocity.Y = _dv.Y + _body1.LinearVelocity.Y;
#endregion
#region INLINE: Calculator.Cross(ref _r1, ref _impulse, out _floatTemp1);
_floatTemp1 = _r1.X * _impulse.Y - _r1.Y * _impulse.X;
#endregion
_floatTemp1 = -_floatTemp1;
#region INLINE: _body1.ApplyAngularImpulse(ref _floatTemp1);
_body1.AngularVelocity += _floatTemp1 * _body1.inverseMomentOfInertia;
#endregion
if (JointUpdated != null)
JointUpdated(this, _body1, _body2);
}
}
#region PreStep variables
private float _body1InverseMass;
private float _body1InverseMomentOfInertia;
private Matrix _body1MatrixTemp;
private float _body2InverseMass;
private float _body2InverseMomentOfInertia;
private Matrix _body2MatrixTemp;
private float _floatTemp1;
private Matrix _k;
private Matrix _k1;
private Matrix _k2;
private Matrix _k3;
private Vector2 _vectorTemp1 = Vector2.Zero;
private Vector2 _vectorTemp2 = Vector2.Zero;
private Vector2 _vectorTemp3 = Vector2.Zero;
private Vector2 _vectorTemp4 = Vector2.Zero;
#endregion
}
}
| |
using UnityEngine;
using System.Collections.Generic;
#if UNITY_EDITOR || !UNITY_FLASH
namespace tk2dRuntime.TileMap
{
public static class ColliderBuilder2D
{
public static void Build(tk2dTileMap tileMap, bool forceBuild)
{
bool incremental = !forceBuild;
int numLayers = tileMap.Layers.Length;
for (int layerId = 0; layerId < numLayers; ++layerId)
{
var layer = tileMap.Layers[layerId];
if (layer.IsEmpty || !tileMap.data.Layers[layerId].generateCollider)
continue;
for (int cellY = 0; cellY < layer.numRows; ++cellY)
{
int baseY = cellY * layer.divY;
for (int cellX = 0; cellX < layer.numColumns; ++cellX)
{
int baseX = cellX * layer.divX;
var chunk = layer.GetChunk(cellX, cellY);
if (incremental && !chunk.Dirty)
continue;
if (chunk.IsEmpty)
continue;
BuildForChunk(tileMap, chunk, baseX, baseY);
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
PhysicsMaterial2D material = tileMap.data.Layers[layerId].physicsMaterial2D;
foreach (EdgeCollider2D ec in chunk.edgeColliders) {
if (ec != null) {
ec.sharedMaterial = material;
}
}
#endif
}
}
}
}
public static void BuildForChunk(tk2dTileMap tileMap, SpriteChunk chunk, int baseX, int baseY)
{
#if !(UNITY_3_5 || UNITY_4_0 || UNITY_4_0_1 || UNITY_4_1 || UNITY_4_2)
////////////////////////////////////////////////////////////////////////////////////////
// 1. Build local edge list
////////////////////////////////////////////////////////////////////////////////////////
Vector2[] localVerts = new Vector2[0];
int[] localIndices = new int[0];
List<Vector2[]> mergedEdges = new List<Vector2[]>();
BuildLocalMeshForChunk(tileMap, chunk, baseX, baseY, ref localVerts, ref localIndices);
////////////////////////////////////////////////////////////////////////////////////////
// 2. Optimize
////////////////////////////////////////////////////////////////////////////////////////
if (localIndices.Length > 4) {
// Remove duplicate verts, reindex
localVerts = WeldVertices(localVerts, ref localIndices);
// Remove duplicate and back-to-back edges
// Removes inside edges
localIndices = RemoveDuplicateEdges(localIndices);
}
////////////////////////////////////////////////////////////////////////////////////////
// 3. Build and optimize an edge list
////////////////////////////////////////////////////////////////////////////////////////
mergedEdges = MergeEdges( localVerts, localIndices );
////////////////////////////////////////////////////////////////////////////////////////
// 4. Build the edge colliders
////////////////////////////////////////////////////////////////////////////////////////
if (chunk.meshCollider != null) {
tk2dUtil.DestroyImmediate(chunk.meshCollider);
chunk.meshCollider = null;
}
if (mergedEdges.Count == 0) {
for (int i = 0; i < chunk.edgeColliders.Count; ++i) {
if (chunk.edgeColliders[i] != null) {
tk2dUtil.DestroyImmediate(chunk.edgeColliders[i]);
}
}
chunk.edgeColliders.Clear();
}
else {
int numEdges = mergedEdges.Count;
// Destroy surplus
for (int i = numEdges; i < chunk.edgeColliders.Count; ++i) {
if (chunk.edgeColliders[i] != null) {
tk2dUtil.DestroyImmediate(chunk.edgeColliders[i]);
}
}
int numToRemove = chunk.edgeColliders.Count - numEdges;
if (numToRemove > 0) {
chunk.edgeColliders.RemoveRange(chunk.edgeColliders.Count - numToRemove, numToRemove);
}
// Make sure existing ones are not null
for (int i = 0; i < chunk.edgeColliders.Count; ++i) {
if (chunk.edgeColliders[i] == null) {
chunk.edgeColliders[i] = tk2dUtil.AddComponent<EdgeCollider2D>(chunk.gameObject);
}
}
// Create missing
while (chunk.edgeColliders.Count < numEdges) {
chunk.edgeColliders.Add( tk2dUtil.AddComponent<EdgeCollider2D>(chunk.gameObject) );
}
for (int i = 0; i < numEdges; ++i) {
chunk.edgeColliders[i].points = mergedEdges[i];
}
}
#endif
}
// Builds an unoptimized mesh for this chunk
static void BuildLocalMeshForChunk(tk2dTileMap tileMap, SpriteChunk chunk, int baseX, int baseY, ref Vector2[] vertices, ref int[] indices)
{
List<Vector2> verts = new List<Vector2>();
List<int> inds = new List<int>();
Vector2[] boxPos = new Vector2[4]; // used for box collider
int[] boxInds = { 0, 1, 1, 2, 2, 3, 3, 0 };
int[] boxIndsFlipped = { 0, 3, 3, 2, 2, 1, 1, 0 };
int spriteCount = tileMap.SpriteCollectionInst.spriteDefinitions.Length;
Vector2 tileSize = new Vector3(tileMap.data.tileSize.x, tileMap.data.tileSize.y);
var tilePrefabs = tileMap.data.tilePrefabs;
float xOffsetMult = 0.0f, yOffsetMult = 0.0f;
tileMap.data.GetTileOffset(out xOffsetMult, out yOffsetMult);
var chunkData = chunk.spriteIds;
for (int y = 0; y < tileMap.partitionSizeY; ++y)
{
float xOffset = ((baseY + y) & 1) * xOffsetMult;
for (int x = 0; x < tileMap.partitionSizeX; ++x)
{
int spriteId = chunkData[y * tileMap.partitionSizeX + x];
int spriteIdx = BuilderUtil.GetTileFromRawTile(spriteId);
Vector2 currentPos = new Vector2(tileSize.x * (x + xOffset), tileSize.y * y);
if (spriteIdx < 0 || spriteIdx >= spriteCount)
continue;
if (tilePrefabs[spriteIdx])
continue;
bool flipH = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.FlipX);
bool flipV = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.FlipY);
bool rot90 = BuilderUtil.IsRawTileFlagSet(spriteId, tk2dTileFlags.Rot90);
bool reverseIndices = false;
if (flipH) reverseIndices = !reverseIndices;
if (flipV) reverseIndices = !reverseIndices;
tk2dSpriteDefinition spriteData = tileMap.SpriteCollectionInst.spriteDefinitions[spriteIdx];
int baseVertexIndex = verts.Count;
if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Box)
{
Vector3 origin = spriteData.colliderVertices[0];
Vector3 extents = spriteData.colliderVertices[1];
Vector3 min = origin - extents;
Vector3 max = origin + extents;
boxPos[0] = new Vector2(min.x, min.y);
boxPos[1] = new Vector2(max.x, min.y);
boxPos[2] = new Vector2(max.x, max.y);
boxPos[3] = new Vector2(min.x, max.y);
for (int i = 0; i < 4; ++i) {
verts.Add( BuilderUtil.ApplySpriteVertexTileFlags(tileMap, spriteData, boxPos[i], flipH, flipV, rot90) + currentPos );
}
int[] boxIndices = reverseIndices ? boxIndsFlipped : boxInds;
for (int i = 0; i < 8; ++i) {
inds.Add( baseVertexIndex + boxIndices[i] );
}
}
else if (spriteData.colliderType == tk2dSpriteDefinition.ColliderType.Mesh)
{
foreach (tk2dCollider2DData dat in spriteData.edgeCollider2D) {
baseVertexIndex = verts.Count;
foreach (Vector2 pos in dat.points) {
verts.Add( BuilderUtil.ApplySpriteVertexTileFlags(tileMap, spriteData, pos, flipH, flipV, rot90) + currentPos );
}
int numVerts = dat.points.Length;
if (reverseIndices) {
for (int i = numVerts - 1; i > 0; --i) {
inds.Add( baseVertexIndex + i );
inds.Add( baseVertexIndex + i - 1 );
}
}
else {
for (int i = 0; i < numVerts - 1; ++i) {
inds.Add(baseVertexIndex + i);
inds.Add(baseVertexIndex + i + 1);
}
}
}
foreach (tk2dCollider2DData dat in spriteData.polygonCollider2D) {
baseVertexIndex = verts.Count;
foreach (Vector2 pos in dat.points) {
verts.Add( BuilderUtil.ApplySpriteVertexTileFlags(tileMap, spriteData, pos, flipH, flipV, rot90) + currentPos );
}
int numVerts = dat.points.Length;
if (reverseIndices) {
for (int i = numVerts; i > 0; --i) {
inds.Add( baseVertexIndex + (i % numVerts) );
inds.Add( baseVertexIndex + i - 1 );
}
}
else {
for (int i = 0; i < numVerts; ++i) {
inds.Add(baseVertexIndex + i);
inds.Add(baseVertexIndex + (i + 1) % numVerts);
}
}
}
}
}
}
vertices = verts.ToArray();
indices = inds.ToArray();
}
static int CompareWeldVertices(Vector2 a, Vector2 b)
{
// Compare one component at a time, using epsilon
float epsilon = 0.01f;
float dx = a.x - b.x;
if (Mathf.Abs(dx) > epsilon) return (int)Mathf.Sign(dx);
float dy = a.y - b.y;
if (Mathf.Abs(dy) > epsilon) return (int)Mathf.Sign(dy);
return 0;
}
static Vector2[] WeldVertices(Vector2[] vertices, ref int[] indices)
{
// Sort by x, y and z
// Adjacent values could be the same after this sort
int[] sortIndex = new int[vertices.Length];
for (int i = 0; i < vertices.Length; ++i) {
sortIndex[i] = i;
}
System.Array.Sort<int>(sortIndex, (a, b) => CompareWeldVertices(vertices[a], vertices[b]) );
// Step through the list, comparing current with previous value
// If they are the same, use the current index
// Otherwise add a new vertex to the vertex list, and use this index
// Welding all similar vertices
List<Vector2> newVertices = new List<Vector2>();
int[] vertexRemap = new int[vertices.Length];
// prime first value
Vector2 previousValue = vertices[sortIndex[0]];
newVertices.Add(previousValue);
vertexRemap[sortIndex[0]] = newVertices.Count - 1;
for (int i = 1; i < sortIndex.Length; ++i) {
Vector2 v = vertices[sortIndex[i]];
if (CompareWeldVertices(v, previousValue) != 0) {
// add new vertex
previousValue = v;
newVertices.Add(previousValue);
vertexRemap[sortIndex[i]] = newVertices.Count - 1;
}
vertexRemap[sortIndex[i]] = newVertices.Count - 1;
}
// remap indices
for (int i = 0; i < indices.Length; ++i) {
indices[i] = vertexRemap[indices[i]];
}
return newVertices.ToArray();
}
static int CompareDuplicateFaces(int[] indices, int face0index, int face1index)
{
for (int i = 0; i < 2; ++i)
{
int d = indices[face0index + i] - indices[face1index + i];
if (d != 0) return d;
}
return 0;
}
static int[] RemoveDuplicateEdges(int[] indices)
{
// Create an ascending sorted list of edge indices
// If 2 sets of indices are identical, then the edges share the same vertices, and either
// is a duplicate, or back-to-back
int[] sortedFaceIndices = new int[indices.Length];
for (int i = 0; i < indices.Length; i += 2)
{
if (indices[i] > indices[i + 1]) {
sortedFaceIndices[i] = indices[i+1];
sortedFaceIndices[i+1] = indices[i];
}
else {
sortedFaceIndices[i] = indices[i];
sortedFaceIndices[i+1] = indices[i+1];
}
}
// Sort by faces
int[] sortIndex = new int[indices.Length / 2];
for (int i = 0; i < indices.Length; i += 2) {
sortIndex[i / 2] = i;
}
System.Array.Sort<int>(sortIndex, (a, b) => CompareDuplicateFaces(sortedFaceIndices, a, b));
List<int> newIndices = new List<int>();
for (int i = 0; i < sortIndex.Length; ++i)
{
if (i != sortIndex.Length - 1 && CompareDuplicateFaces(sortedFaceIndices, sortIndex[i], sortIndex[i+1]) == 0)
{
// skip both faces
// this will fail in the case where there are 3 coplanar faces
// but that is probably likely user error / intentional
i++;
continue;
}
for (int j = 0; j < 2; ++j)
newIndices.Add(indices[sortIndex[i] + j]);
}
return newIndices.ToArray();
}
static List<Vector2[]> MergeEdges(Vector2[] verts, int[] indices) {
// Brute force search, but almost entirely deals with ints
// Search area significantly reduced by previous welding and other opts
// While possible to optimize further, this is almost never the bottleneck.
// Normals are generated exactly once per vertex
List<Vector2[]> edges = new List<Vector2[]>();
List<Vector2> edgeVerts = new List<Vector2>();
List<int> edgeIndices = new List<int>();
Vector2 d0 = Vector2.zero;
Vector2 d1 = Vector2.zero;
bool[] edgeUsed = new bool[indices.Length / 2];
bool processedEdge = true;
while (processedEdge) {
processedEdge = false;
for (int i = 0; i < edgeUsed.Length; ++i) {
if (!edgeUsed[i]) {
edgeUsed[i] = true;
int v0 = indices[i * 2 + 0];
int v1 = indices[i * 2 + 1];
d0 = (verts[v1] - verts[v0]).normalized;
edgeIndices.Add(v0);
edgeIndices.Add(v1);
// The connecting vertex for this edge list
for (int k = i + 1; k < edgeUsed.Length; ++k) {
if (edgeUsed[k]) {
continue;
}
int w0 = indices[k * 2 + 0];
if (w0 == v1) {
int w1 = indices[k * 2 + 1];
d1 = (verts[w1] - verts[w0]).normalized;
// Same direction?
if (Vector2.Dot(d1, d0) > 0.999f) {
edgeIndices.RemoveAt(edgeIndices.Count - 1); // remove last
}
edgeIndices.Add(w1);
edgeUsed[k] = true;
d0 = d1; // new normal
k = i; // restart the loop
v1 = w1; // continuing from the end of the loop
continue;
}
}
processedEdge = true;
break;
}
}
if (processedEdge) {
edgeVerts.Clear();
edgeVerts.Capacity = Mathf.Max(edgeVerts.Capacity, edgeIndices.Count);
for (int i = 0; i < edgeIndices.Count; ++i) {
edgeVerts.Add( verts[edgeIndices[i]] );
}
edges.Add(edgeVerts.ToArray());
edgeIndices.Clear();
}
}
return edges;
}
}
}
#endif
| |
// Copyright (C) 2014 - 2015 Stephan Bouchard - All Rights Reserved
// This code can only be used under the standard Unity Asset Store End User License Agreement
// A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms
// Beta Release 0.1.52 Beta 1c
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace TMPro
{
public enum TextAlignmentOptions { TopLeft = 0, Top = 1, TopRight = 2, TopJustified = 3,
Left = 4, Center = 5, Right = 6, Justified = 7,
BottomLeft = 8, Bottom = 9, BottomRight = 10, BottomJustified = 11,
BaselineLeft = 12, Baseline = 13, BaselineRight = 14, BaselineJustified = 15,
MidlineLeft = 16, Midline = 17, MidlineRight = 18, MidlineJustified = 19 };
public enum TextRenderFlags { Render, DontRender, GetPreferredSizes };
public enum MaskingTypes { MaskOff = 0, MaskHard = 1, MaskSoft = 2 }; //, MaskTex = 4 };
public enum TextOverflowModes { Overflow = 0, Ellipsis = 1, Masking = 2, Truncate = 3, ScrollRect = 4, Page = 5 };
public enum MaskingOffsetMode { Percentage = 0, Pixel = 1 };
public enum TextureMappingOptions { Character = 0, Line = 1, Paragraph = 2, MatchAspect = 3 };
public enum FontStyles { Normal = 0x0, Bold = 0x1, Italic = 0x2, Underline = 0x4, LowerCase = 0x8, UpperCase = 0x10, SmallCaps = 0x20, Strikethrough = 0x40, Superscript = 0x80, Subscript = 0x100 };
public enum TagUnits { Pixels = 0, FontUnits = 1, Percentage = 2};
[ExecuteInEditMode]
[RequireComponent(typeof(TextContainer))]
[RequireComponent(typeof(MeshRenderer))]
[RequireComponent(typeof(MeshFilter))]
[AddComponentMenu("Mesh/TextMesh Pro")]
public partial class TextMeshPro : MonoBehaviour
{
// Public Properties and Serializable Properties
/// <summary>
/// A string containing the text to be displayed.
/// </summary>
public string text
{
get { return m_text; }
set { m_inputSource = TextInputSources.Text; havePropertiesChanged = true; isInputParsingRequired = true; m_text = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// The TextMeshPro font asset to be assigned to this text object.
/// </summary>
public TextMeshProFont font
{
get { return m_fontAsset; }
set { if (m_fontAsset != value) { m_fontAsset = value; LoadFontAsset(); havePropertiesChanged = true; /* hasFontAssetChanged = true;*/ /* ScheduleUpdate(); */} }
}
/// <summary>
/// The material to be assigned to this text object. An instance of the material will be assigned to the object's renderer.
/// </summary>
public Material fontMaterial
{
// Return a new Instance of the Material if none exists. Otherwise return the current Material Instance.
get
{
if (m_fontMaterial == null)
{
SetFontMaterial(m_sharedMaterial);
return m_sharedMaterial;
}
return m_sharedMaterial;
}
// Assigning fontMaterial always returns an instance of the material.
set { SetFontMaterial(value); havePropertiesChanged = true; /* ScheduleUpdate(); */ }
}
/// <summary>
/// The material to be assigned to this text object.
/// </summary>
public Material fontSharedMaterial
{
get { return m_renderer.sharedMaterial; }
set { if (m_sharedMaterial != value) { SetSharedFontMaterial(value); havePropertiesChanged = true; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the RenderQueue along with Ztest to force the text to be drawn last and on top of scene elements.
/// </summary>
public bool isOverlay
{
get { return m_isOverlay; }
set { m_isOverlay = value; SetShaderType(); havePropertiesChanged = true; /* ScheduleUpdate(); */ }
}
/// <summary>
/// This is the default vertex color assigned to each vertices. Color tags will override vertex colors unless the overrideColorTags is set.
/// </summary>
public Color color
{
get { return m_fontColor; }
set { if (!m_fontColor.Compare(value)) { havePropertiesChanged = true; m_fontColor = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the vertex color alpha value.
/// </summary>
public float alpha
{
get { return m_fontColor.a; }
set { Color c = m_fontColor; c.a = value; m_fontColor = c; havePropertiesChanged = true; }
}
/// <summary>
/// Sets the vertex colors for each of the 4 vertices of the character quads.
/// </summary>
/// <value>The color gradient.</value>
public VertexGradient colorGradient
{
get { return m_fontColorGradient;}
set { havePropertiesChanged = true; m_fontColorGradient = value; }
}
/// <summary>
/// Determines if Vertex Color Gradient should be used
/// </summary>
/// <value><c>true</c> if enable vertex gradient; otherwise, <c>false</c>.</value>
public bool enableVertexGradient
{
get { return m_enableVertexGradient; }
set { havePropertiesChanged = true; m_enableVertexGradient = value; }
}
/// <summary>
/// Sets the color of the _FaceColor property of the assigned material. Changing face color will result in an instance of the material.
/// </summary>
public Color32 faceColor
{
get { return m_faceColor; }
set { if (m_faceColor.Compare(value) == false) { SetFaceColor(value); havePropertiesChanged = true; m_faceColor = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the color of the _OutlineColor property of the assigned material. Changing outline color will result in an instance of the material.
/// </summary>
public Color32 outlineColor
{
get { return m_outlineColor; }
set { if (m_outlineColor.Compare(value) == false) { SetOutlineColor(value); havePropertiesChanged = true; m_outlineColor = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets the thickness of the outline of the font. Setting this value will result in an instance of the material.
/// </summary>
public float outlineWidth
{
get { return m_outlineWidth; }
set { SetOutlineThickness(value); havePropertiesChanged = true; checkPaddingRequired = true; m_outlineWidth = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// The size of the font.
/// </summary>
public float fontSize
{
get { return m_fontSize; }
set { if (m_fontSize != value) { havePropertiesChanged = true; /* hasFontScaleChanged = true; */ m_fontSize = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// The scale of the current text.
/// </summary>
public float fontScale
{
get { return m_fontScale; }
}
/// <summary>
/// The style of the text
/// </summary>
public FontStyles fontStyle
{
get { return m_fontStyle; }
set { m_fontStyle = value; havePropertiesChanged = true; checkPaddingRequired = true; }
}
/// <summary>
/// The amount of additional spacing between characters.
/// </summary>
public float characterSpacing
{
get { return m_characterSpacing; }
set { if (m_characterSpacing != value) { havePropertiesChanged = true; m_characterSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Enables or Disables Rich Text Tags
/// </summary>
public bool richText
{
get { return m_isRichText; }
set { m_isRichText = value; havePropertiesChanged = true; isInputParsingRequired = true; }
}
/// <summary>
/// Enables or Disables parsing of CTRL characters in input text.
/// </summary>
public bool parseCtrlCharacters
{
get { return m_parseCtrlCharacters; }
set { m_parseCtrlCharacters = value; havePropertiesChanged = true; isInputParsingRequired = true; }
}
/// <summary>
/// Determines where word wrap will occur.
/// </summary>
[Obsolete("The length of the line is now controlled by the size of the text container and margins.")]
public float lineLength
{
get { return m_lineLength; }
set { Debug.Log("lineLength set called."); }
}
/// <summary>
/// Controls the Text Overflow Mode
/// </summary>
public TextOverflowModes OverflowMode
{
get { return m_overflowMode; }
set { m_overflowMode = value; havePropertiesChanged = true; }
}
/// <summary>
/// Contains the bounds of the text object.
/// </summary>
public Bounds bounds
{
get { if (m_mesh != null) return m_mesh.bounds; return new Bounds(); }
//set { if (_meshExtents != value) havePropertiesChanged = true; _meshExtents = value; }
}
/// <summary>
/// The amount of additional spacing to add between each lines of text.
/// </summary>
public float lineSpacing
{
get { return m_lineSpacing; }
set { if (m_lineSpacing != value) { havePropertiesChanged = true; m_lineSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// The amount of additional spacing to add between each lines of text.
/// </summary>
public float paragraphSpacing
{
get { return m_paragraphSpacing; }
set { if (m_paragraphSpacing != value) { havePropertiesChanged = true; m_paragraphSpacing = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Determines the anchor position of the text object.
/// </summary>
[Obsolete("The length of the line is now controlled by the size of the text container and margins.")]
public TMP_Compatibility.AnchorPositions anchor
{
get { return m_anchor; }
}
/// <summary>
/// Text alignment options
/// </summary>
public TextAlignmentOptions alignment
{
get { return m_textAlignment; }
set { if (m_textAlignment != value) { havePropertiesChanged = true; m_textAlignment = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Determines if kerning is enabled or disabled.
/// </summary>
public bool enableKerning
{
get { return m_enableKerning; }
set { if (m_enableKerning != value) { havePropertiesChanged = true; m_enableKerning = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Anchor dampening prevents the anchor position from being adjusted unless the positional change exceeds about 40% of the width of the underline character. This essentially stabilizes the anchor position.
/// </summary>
//public bool anchorDampening
//{
// get { return m_anchorDampening; }
// set { if (m_anchorDampening != value) { havePropertiesChanged = true; m_anchorDampening = value; /* ScheduleUpdate(); */ } }
//}
/// <summary>
/// This overrides the color tags forcing the vertex colors to be the default font color.
/// </summary>
public bool overrideColorTags
{
get { return m_overrideHtmlColors; }
set { if (m_overrideHtmlColors != value) { havePropertiesChanged = true; m_overrideHtmlColors = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Adds extra padding around each character. This may be necessary when the displayed text is very small to prevent clipping.
/// </summary>
public bool extraPadding
{
get { return m_enableExtraPadding; }
set { if (m_enableExtraPadding != value) { havePropertiesChanged = true; checkPaddingRequired = true; m_enableExtraPadding = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls whether or not word wrapping is applied. When disabled, the text will be displayed on a single line.
/// </summary>
public bool enableWordWrapping
{
get { return m_enableWordWrapping; }
set { if (m_enableWordWrapping != value) { havePropertiesChanged = true; isInputParsingRequired = true; m_enableWordWrapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls how the face and outline textures will be applied to the text object.
/// </summary>
public TextureMappingOptions horizontalMapping
{
get { return m_horizontalMapping; }
set { if (m_horizontalMapping != value) { havePropertiesChanged = true; m_horizontalMapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Controls how the face and outline textures will be applied to the text object.
/// </summary>
public TextureMappingOptions verticalMapping
{
get { return m_verticalMapping; }
set { if (m_verticalMapping != value) { havePropertiesChanged = true; m_verticalMapping = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Forces objects that are not visible to get refreshed.
/// </summary>
public bool ignoreVisibility
{
get { return m_ignoreCulling; }
set { if (m_ignoreCulling != value) { havePropertiesChanged = true; m_ignoreCulling = value; /* ScheduleUpdate(); */ } }
}
/// <summary>
/// Sets Perspective Correction to Zero for Orthographic Camera mode and 0.875f for Perspective Camera mode.
/// </summary>
public bool isOrthographic
{
get { return m_isOrthographic; }
set { havePropertiesChanged = true; m_isOrthographic = value; /* ScheduleUpdate(); */ }
}
/// <summary>
/// Sets the culling on the shader. Note changing this value will result in an instance of the material.
/// </summary>
public bool enableCulling
{
get { return m_isCullingEnabled; }
set { m_isCullingEnabled = value; SetCulling(); havePropertiesChanged = true; }
}
/// <summary>
/// Sets the Renderer's sorting Layer ID
/// </summary>
public int sortingLayerID
{
get { return m_renderer.sortingLayerID; }
set { m_renderer.sortingLayerID = value; }
}
/// <summary>
/// Sets the Renderer's sorting order within the assigned layer.
/// </summary>
public int sortingOrder
{
get { return m_renderer.sortingOrder; }
set { m_renderer.sortingOrder = value; }
}
public bool hasChanged
{
get { return havePropertiesChanged; }
set { havePropertiesChanged = value; }
}
/// <summary>
/// Determines if the Mesh will be uploaded.
/// </summary>
public TextRenderFlags renderMode
{
get { return m_renderMode; }
set { m_renderMode = value; havePropertiesChanged = true; }
}
/// <summary>
/// Returns a reference to the Text Container
/// </summary>
public TextContainer textContainer
{
get
{
if (m_textContainer == null)
m_textContainer = GetComponent<TextContainer>();
return m_textContainer; }
}
/// <summary>
/// Returns a reference to the Transform
/// </summary>
public new Transform transform
{
get
{
if (m_transform == null)
m_transform = GetComponent<Transform>();
return m_transform;
}
}
/// <summary>
/// Allows to control how many characters are visible from the input. Non-visible character are set to fully transparent.
/// </summary>
public int maxVisibleCharacters
{
get { return m_maxVisibleCharacters; }
set { if (m_maxVisibleCharacters != value) { havePropertiesChanged = true; m_maxVisibleCharacters = value; } }
}
/// <summary>
/// Allows control over how many lines of text are displayed.
/// </summary>
public int maxVisibleLines
{
get { return m_maxVisibleLines; }
set { if (m_maxVisibleLines != value) { havePropertiesChanged = true; isInputParsingRequired = true; m_maxVisibleLines = value; } }
}
/// <summary>
/// Controls which page of text is shown
/// </summary>
public int pageToDisplay
{
get { return m_pageToDisplay; }
set { havePropertiesChanged = true; m_pageToDisplay = value; }
}
// Width of the text object if layout on a single line
public float preferredWidth
{
get { return m_preferredWidth; }
}
//public int characterCount
//{
// get { return m_textInfo.characterCount; }
//}
//public int lineCount
//{
// get { return m_textInfo.lineCount; }
//}
//public Vector2[] spacePositions
//{
// get { return m_spacePositions; }
//}
public bool enableAutoSizing
{
get { return m_enableAutoSizing; }
set { m_enableAutoSizing = value; }
}
public float fontSizeMin
{
get { return m_fontSizeMin; }
set { m_fontSizeMin = value; }
}
public float fontSizeMax
{
get { return m_fontSizeMax; }
set { m_fontSizeMax = value; }
}
// MASKING RELATED PROPERTIES
/// <summary>
/// Sets the mask type
/// </summary>
public MaskingTypes maskType
{
get { return m_maskType; }
set { m_maskType = value; SetMask(m_maskType); }
}
/// <summary>
/// Function used to set the mask type and coordinates in World Space
/// </summary>
/// <param name="type"></param>
/// <param name="maskCoords"></param>
public void SetMask(MaskingTypes type, Vector4 maskCoords)
{
SetMask(type);
SetMaskCoordinates(maskCoords);
}
/// <summary>
/// Function used to set the mask type, coordinates and softness
/// </summary>
/// <param name="type"></param>
/// <param name="maskCoords"></param>
/// <param name="softnessX"></param>
/// <param name="softnessY"></param>
public void SetMask(MaskingTypes type, Vector4 maskCoords, float softnessX, float softnessY)
{
SetMask(type);
SetMaskCoordinates(maskCoords, softnessX, softnessY);
}
/*
/// <summary>
/// Set the masking offset mode (as percentage or pixels)
/// </summary>
public MaskingOffsetMode maskOffsetMode
{
get { return m_maskOffsetMode; }
set { m_maskOffsetMode = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Sets the masking offset from the bounds of the object
/// </summary>
public Vector4 maskOffset
{
get { return m_maskOffset; }
set { m_maskOffset = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Sets the softness of the mask
/// </summary>
public Vector2 maskSoftness
{
get { return m_maskSoftness; }
set { m_maskSoftness = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
/// <summary>
/// Allows to move / offset the mesh vertices by a set amount
/// </summary>
public Vector2 vertexOffset
{
get { return m_vertexOffset; }
set { m_vertexOffset = value; havePropertiesChanged = true; isMaskUpdateRequired = true; }
}
*/
public TMP_TextInfo textInfo
{
get { return m_textInfo; }
}
#pragma warning disable 0108
public Renderer renderer
{
get { return m_renderer; }
}
public Mesh mesh
{
get { return m_mesh; }
}
/// <summary>
/// Function to be used to force recomputing of character padding when Shader / Material properties have been changed via script.
/// </summary>
public void UpdateMeshPadding()
{
m_padding = ShaderUtilities.GetPadding(m_renderer.sharedMaterials, m_enableExtraPadding, m_isUsingBold);
havePropertiesChanged = true;
/* ScheduleUpdate(); */
}
/// <summary>
/// Function to force regeneration of the mesh before its normal process time. This is useful when changes to the text object properties need to be applied immediately.
/// </summary>
public void ForceMeshUpdate()
{
//Debug.Log("ForceMeshUpdate() called.");
havePropertiesChanged = true;
OnWillRenderObject();
}
public void UpdateFontAsset()
{
LoadFontAsset();
}
/// <summary>
/// Function used to evaluate the length of a text string.
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
public TMP_TextInfo GetTextInfo(string text)
{
//TextInfo temp_textInfo = new TextInfo();
StringToCharArray(text, ref m_char_buffer);
m_renderMode = TextRenderFlags.DontRender;
GenerateTextMesh();
m_renderMode = TextRenderFlags.Render;
return this.textInfo;
}
//public Vector2[] SetTextWithSpaces(string text, int numPositions)
//{
// m_spacePositions = new Vector2[numPositions];
// this.text = text;
// return m_spacePositions;
//}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("Number is {0:1}.", 5.56f);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
public void SetText (string text, float arg0)
{
SetText(text, arg0, 255, 255);
}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("First number is {0} and second is {1:2}.", 10, 5.756f);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
/// <param name="arg1">Value is a float.</param>
public void SetText (string text, float arg0, float arg1)
{
SetText(text, arg0, arg1, 255);
}
/// <summary>
/// <para>Formatted string containing a pattern and a value representing the text to be rendered.</para>
/// <para>ex. TextMeshPro.SetText ("A = {0}, B = {1} and C = {2}.", 2, 5, 7);</para>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="text">String containing the pattern."</param>
/// <param name="arg0">Value is a float.</param>
/// <param name="arg1">Value is a float.</param>
/// <param name="arg2">Value is a float.</param>
public void SetText (string text, float arg0, float arg1, float arg2)
{
// Early out if nothing has been changed from previous invocation.
if (text == old_text && arg0 == old_arg0 && arg1 == old_arg1 && arg2 == old_arg2)
{
return;
}
// Make sure Char[] can hold the input string
if (m_input_CharArray.Length < text.Length)
m_input_CharArray = new char[Mathf.NextPowerOfTwo(text.Length + 1)];
old_text = text;
old_arg1 = 255;
old_arg2 = 255;
int decimalPrecision = 0;
int index = 0;
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == 123) // '{'
{
// Check if user is requesting some decimal precision. Format is {0:2}
if (text[i + 2] == 58) // ':'
{
decimalPrecision = text[i + 3] - 48;
}
switch (text[i + 1] - 48)
{
case 0: // 1st Arg
old_arg0 = arg0;
AddFloatToCharArray(arg0, ref index, decimalPrecision);
break;
case 1: // 2nd Arg
old_arg1 = arg1;
AddFloatToCharArray(arg1, ref index, decimalPrecision);
break;
case 2: // 3rd Arg
old_arg2 = arg2;
AddFloatToCharArray(arg2, ref index, decimalPrecision);
break;
}
if (text[i + 2] == 58)
i += 4;
else
i += 2;
continue;
}
m_input_CharArray[index] = c;
index += 1;
}
m_input_CharArray[index] = (char)0;
m_charArray_Length = index; // Set the length to where this '0' termination is.
#if UNITY_EDITOR
// Create new string to be displayed in the Input Text Box of the Editor Panel.
m_text = new string(m_input_CharArray, 0, index);
#endif
m_inputSource = TextInputSources.SetText;
isInputParsingRequired = true;
havePropertiesChanged = true;
/* ScheduleUpdate(); */
}
/// <summary>
/// Character array containing the text to be displayed.
/// </summary>
/// <param name="charArray"></param>
public void SetCharArray(char[] charArray)
{
if (charArray == null || charArray.Length == 0)
return;
// Check to make sure chars_buffer is large enough to hold the content of the string.
if (m_char_buffer.Length <= charArray.Length)
{
int newSize = Mathf.NextPowerOfTwo(charArray.Length + 1);
m_char_buffer = new int[newSize];
}
int index = 0;
for (int i = 0; i < charArray.Length; i++)
{
if (charArray[i] == 92 && i < charArray.Length - 1)
{
switch ((int)charArray[i + 1])
{
case 110: // \n LineFeed
m_char_buffer[index] = (char)10;
i += 1;
index += 1;
continue;
case 114: // \r LineFeed
m_char_buffer[index] = (char)13;
i += 1;
index += 1;
continue;
case 116: // \t Tab
m_char_buffer[index] = (char)9;
i += 1;
index += 1;
continue;
}
}
m_char_buffer[index] = charArray[i];
index += 1;
}
m_char_buffer[index] = (char)0;
m_inputSource = TextInputSources.SetCharArray;
havePropertiesChanged = true;
isInputParsingRequired = true;
}
}
}
| |
#region Copyright (c) Roni Schuetz - All Rights Reserved
// * --------------------------------------------------------------------- *
// * Roni Schuetz *
// * Copyright (c) 2008 All Rights reserved *
// * *
// * Shared Cache high-performance, distributed caching and *
// * replicated caching system, generic in nature, but intended to *
// * speeding up dynamic web and / or win applications by alleviating *
// * database load. *
// * *
// * This Software is written by Roni Schuetz (schuetz AT gmail DOT 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., 59 Temple Place, Suite 330, *
// * Boston, MA 02111-1307 USA *
// * *
// * THIS COPYRIGHT NOTICE MAY NOT BE REMOVED FROM THIS FILE. *
// * --------------------------------------------------------------------- *
#endregion
// *************************************************************************
//
// Name: Version.cs
//
// Created: 21-07-2007 SharedCache.com, rschuetz
// Modified: 21-07-2007 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
using System.Data;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.ComponentModel;
using System.Reflection;
using System.Web.Configuration;
using System.Configuration;
using COM = SharedCache.WinServiceCommon;
using System.EnterpriseServices;
namespace SharedCache.Version
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://sharedcache.indeXus.Net/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
public class Version : System.Web.Services.WebService
{
[WebMethod]
[COM.Attributes.SharedCacheSoapExtension(CacheInSecond=60000)]
public string HelloWorld()
{
return DateTime.Now.ToString("dd.MM.yyyy - hh:mm:ss");
}
/// <summary>
/// Gets the version of the public available release.
/// </summary>
/// <returns></returns>
[WebMethod]
[COM.Attributes.SharedCacheSoapExtension(CacheInSecond=60000)]
public string GetVersion()
{
COM.Handler.LogHandler.Info("****************************************************** " + DateTime.Now.ToString() + " ********************************************************");
COM.Handler.LogHandler.Info("Assembly Info:");
AssemblyInfo ai = new AssemblyInfo();
COM.Handler.LogHandler.Info("AsmFQName: " + ai.AsmFQName);
COM.Handler.LogHandler.Info("AsmName: " + ai.AsmName);
COM.Handler.LogHandler.Info("CodeBase: " + ai.CodeBase);
COM.Handler.LogHandler.Info("Company: " + ai.Company);
COM.Handler.LogHandler.Info("Copyright: " + ai.Copyright);
COM.Handler.LogHandler.Info("Description: " + ai.Description);
COM.Handler.LogHandler.Info("Product: " + ai.Product);
COM.Handler.LogHandler.Info("Title: " + ai.Title);
COM.Handler.LogHandler.Info("Version: " + ai.Version);
COM.Handler.LogHandler.Info("Client Info:");
COM.Handler.LogHandler.Info("*************************************************");
if (this.Context != null)
{
if (this.Context.Request != null)
{
if (this.Context.Request.UserLanguages != null)
{
foreach (string s in this.Context.Request.UserLanguages)
{
COM.Handler.LogHandler.Info(s);
}
}
if (this.Context.Request.UserHostName != null)
COM.Handler.LogHandler.Info(this.Context.Request.UserHostName);
if (this.Context.Request.UserHostAddress != null)
COM.Handler.LogHandler.Info(this.Context.Request.UserHostAddress);
if (this.Context.Request.UserAgent != null)
COM.Handler.LogHandler.Info(this.Context.Request.UserAgent);
if (this.Context.Request.UrlReferrer != null)
COM.Handler.LogHandler.Info(this.Context.Request.UrlReferrer.ToString());
if (this.Context.Request.ServerVariables != null)
{
COM.Handler.LogHandler.Info("ServerVariables:");
COM.Handler.LogHandler.Info("*************************************************");
foreach (string s in this.Context.Request.ServerVariables.AllKeys)
{
COM.Handler.LogHandler.Info(string.Format(" {0,-10} {1}", s, this.Context.Request.ServerVariables[s]));
}
}
if (this.Context.Request.Headers != null)
{
COM.Handler.LogHandler.Info("Headers:");
COM.Handler.LogHandler.Info("*************************************************");
foreach (string s in this.Context.Request.Headers.AllKeys)
{
COM.Handler.LogHandler.Info(string.Format(" {0,-10} {1}", s, this.Context.Request.Headers[s]));
}
}
}
}
return Config.GetStringValueFromConfigByKey("SharedCacheVersionNumber") + " - " + DateTime.Now.ToString("hh:mm:ss");
}
}
/// <summary>
/// Summary description for ConfigHandler.
/// </summary>
public class Config
{
/// <summary>
/// Initializes a new instance of the <see cref="Config"/> class.
/// </summary>
public Config()
{ }
#region Methods
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>string value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static string GetStringValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return ConfigurationManager.AppSettings[key];
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return string.Empty;
}
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static int GetIntValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return int.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
/// <summary>
/// Get the value based on the key from the app.config
/// </summary>
/// <param name="key"><see cref="string"/> Key-Name</param>
/// <returns>int value of a applied key</returns>
[System.Diagnostics.DebuggerStepThrough]
public static double GetDoubleValueFromConfigByKey(string key)
{
try
{
if (ConfigurationManager.AppSettings[key] != null)
return double.Parse(ConfigurationManager.AppSettings[key]);
}
catch (FormatException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (ArgumentException e)
{
System.Diagnostics.Debug.WriteLine(((object)MethodBase.GetCurrentMethod()).ToString() + Environment.NewLine + e.ToString());
}
catch (Exception e)
{
// Todo: RSC: add Logging
System.Diagnostics.Debug.WriteLine(e);
}
return -1;
}
/// <summary>
/// Gets the num of defined app settings.
/// </summary>
/// <returns>A <see cref="T:System.Int32"/> Object.</returns>
[System.Diagnostics.DebuggerStepThrough]
public static int GetNumOfDefinedAppSettings()
{
return ConfigurationManager.AppSettings.Count;
}
///// <summary>
///// Displays the app.config settings.
///// </summary>
///// <returns></returns>
//public static string DisplayAppSettings()
//{
// StringBuilder sb = new StringBuilder();
// NameValueCollection appSettings = ConfigurationManager.AppSettings;
// string[] keys = appSettings.AllKeys;
// sb.Append(string.Empty + Environment.NewLine);
// sb.Append("Application appSettings:" + Environment.NewLine);
// sb.Append(string.Empty + Environment.NewLine);
// // Loop to get key/value pairs.
// for (int i = 0; i < appSettings.Count; i++)
// {
// sb.AppendFormat("#{0} Name: {1} - Value: {2}" + Environment.NewLine, i, keys[i], appSettings[i]);
// }
// return sb.ToString();
//}
#endregion
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Positioning.dll
// Description: A library for managing GPS connections.
// ********************************************************************************************************
// The contents of this file are subject to the MIT License (MIT)
// you may not use this file except in compliance with the License. You may obtain a copy of the License at
// http://dotspatial.codeplex.com/license
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either expressed or implied. See the License for the specific language governing rights and
// limitations under the License.
//
// The Original Code is from http://geoframework.codeplex.com/ version 2.0
//
// The Initial Developer of this original code is Jon Pearson. Submitted Oct. 21, 2010 by Ben Tombs (tidyup)
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// -------------------------------------------------------------------------------------------------------
// | Developer | Date | Comments
// |--------------------------|------------|--------------------------------------------------------------
// | Tidyup (Ben Tombs) | 10/21/2010 | Original copy submitted from modified GeoFrameworks 2.0
// | Shade1974 (Ted Dunsford) | 10/21/2010 | Added file headers reviewed formatting with resharper.
// ********************************************************************************************************
using System;
using System.Globalization;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
#if !PocketPC || DesignTime
using System.ComponentModel;
#endif
namespace DotSpatial.Positioning
{
#if !PocketPC || DesignTime
/// <summary>
/// Represents a highly-precise pixel coordinate.
/// </summary>
/// <remarks><para>This class behaves similar to the <strong>PointF</strong> structure in the
/// <strong>System.Drawing</strong> namespace, except that it supports double-precision
/// values and can be converted into a geographic coordinate. This structure is also
/// supported on the Compact Framework version of the <strong>DotSpatial.Positioning</strong>,
/// whereas <strong>PointF</strong> is not.</para>
/// <para>Instances of this class are guaranteed to be thread-safe because the class is
/// immutable (its properties can only be changed via constructors).</para></remarks>
[TypeConverter("DotSpatial.Positioning.Design.PointDConverter, DotSpatial.Positioning.Design, Culture=neutral, Version=1.0.0.0, PublicKeyToken=b4b0b185210c9dae")]
#endif
public struct PointD : IFormattable, IEquatable<PointD>, IXmlSerializable
{
/// <summary>
///
/// </summary>
private double _x;
/// <summary>
///
/// </summary>
private double _y;
#region Fields
/// <summary>
/// Returns a point with no value.
/// </summary>
public static readonly PointD Empty = new PointD(0, 0);
/// <summary>
/// Represents an invalid coordinate.
/// </summary>
public static readonly PointD Invalid = new PointD(double.NaN, double.NaN);
#endregion Fields
#region Constructors
/// <summary>
/// Creates a new instance for the specified coordinates.
/// </summary>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
public PointD(double x, double y)
{
_x = x;
_y = y;
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
public PointD(string value)
: this(value, CultureInfo.CurrentCulture)
{ }
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
public PointD(string value, CultureInfo culture)
{
// Trim the string and remove double spaces
value = value.Replace(" ", " ").Trim();
// And separate it via the list separator
string[] values = value.Split(Convert.ToChar(culture.TextInfo.ListSeparator, culture));
// Return the converted values
_x = double.Parse(values[0], NumberStyles.Any, culture);
_y = double.Parse(values[1], NumberStyles.Any, culture);
}
/// <summary>
/// Initializes a new instance of the <see cref="PointD"/> struct.
/// </summary>
/// <param name="reader">The reader.</param>
public PointD(XmlReader reader)
{
_x = _y = 0.0;
ReadXml(reader);
}
#endregion Constructors
#region Public Properties
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The X.</value>
public double X
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Lamda or the longitude parameter.
/// For readability only, the value is X.
/// </summary>
/// <value>The lam.</value>
public double Lam
{
get
{
return _x;
}
set
{
_x = value;
}
}
/// <summary>
/// Gets or sets the x-coordinate of this PointD.
/// </summary>
/// <value>The Y.</value>
public double Y
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// For projected coordinates, this is the factor Phi or the latitude parameter.
/// For readability only, the value is Y.
/// </summary>
/// <value>The phi.</value>
public double Phi
{
get
{
return _y;
}
set
{
_y = value;
}
}
/// <summary>
/// Returns whether the current instance has no value.
/// </summary>
public bool IsEmpty
{
get
{
return (_x == 0 && _y == 0);
}
}
/// <summary>
/// Returns whether the current instance has an invalid value.
/// </summary>
public bool IsInvalid
{
get
{
double fail = _x * _y;
return (double.IsNaN(fail) || double.IsInfinity(fail));
}
}
#endregion Public Properties
#region Public Methods
/*
/// <summary>Calculates the direction from one point to another.</summary>
public Azimuth BearingTo(PointD value)
{
double Result = value.Subtract(this).ToPolarCoordinate().Theta.DecimalDegrees;
return new Azimuth(Result).Normalize();
}
*/
/// <summary>
/// Calculates the distance to another pixel.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public double DistanceTo(PointD value)
{
return Math.Sqrt(Math.Abs(value.X - _x) * Math.Abs(value.X - _x)
+ Math.Abs(value.Y - _y) * Math.Abs(value.Y - _y));
}
/// <summary>
/// Indicates if the current instance is closer to the top of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is above; otherwise, <c>false</c>.</returns>
public bool IsAbove(PointD value)
{
return _y < value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the bottom of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if the specified value is below; otherwise, <c>false</c>.</returns>
public bool IsBelow(PointD value)
{
return _y > value.Y;
}
/// <summary>
/// Indicates if the current instance is closer to the left of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is left of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsLeftOf(PointD value)
{
return _x < value.X;
}
/// <summary>
/// Indicates if the current instance is closer to the right of the monitor than the
/// specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns><c>true</c> if [is right of] [the specified value]; otherwise, <c>false</c>.</returns>
public bool IsRightOf(PointD value)
{
return _x > value.X;
}
/// <summary>
/// Returns the current instance with its signs switched.
/// </summary>
/// <returns></returns>
/// <remarks>This method returns a new point where the signs of X and Y are flipped. For example, if
/// a point, represents (20, 40), this function will return (-20, -40).</remarks>
public PointD Mirror()
{
return new PointD(-_x, -_y);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format)
{
return ToString(format, CultureInfo.CurrentCulture);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(Angle angle)
{
return Rotate(angle.DecimalDegrees);
}
/// <summary>
/// Returns the current instance rotated about (0, 0).
/// </summary>
/// <param name="angle">The angle.</param>
/// <returns></returns>
public PointD Rotate(double angle)
{
// Convert the angle to radians
double angleRadians = Radian.FromDegrees(angle).Value;
double angleCos = Math.Cos(angleRadians);
double angleSin = Math.Sin(angleRadians);
// Yes. Rotate the point about 0, 0
return new PointD(angleCos * _x - angleSin * _y, angleSin * _x + angleCos * _y);
}
/// <summary>
/// Returns the current instance rotated about the specified point.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(Angle angle, PointD center)
{
return RotateAt(angle.DecimalDegrees, center);
}
/// <summary>
/// Rotates at.
/// </summary>
/// <param name="angle">The angle.</param>
/// <param name="center">The center.</param>
/// <returns></returns>
public PointD RotateAt(double angle, PointD center)
{
if (angle == 0)
return this;
// Shift the point by its center, rotate, then add the center back in
return Subtract(center).Rotate(angle).Add(center);
}
#endregion Public Methods
#region Overrides
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
if (obj is PointD)
return Equals((PointD)obj);
return false;
}
/// <summary>
/// Returns a unique code used for hash tables.
/// </summary>
/// <returns>A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.</returns>
public override int GetHashCode()
{
return _x.GetHashCode() ^ _y.GetHashCode();
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public override string ToString()
{
return ToString("G", CultureInfo.CurrentCulture);
}
#endregion Overrides
#region Static Methods
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public static PointD Parse(string value)
{
return new PointD(value);
}
/// <summary>
/// Parses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public static PointD Parse(string value, CultureInfo culture)
{
return new PointD(value, culture);
}
#endregion Static Methods
#region Operators
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(PointD left, PointD right)
{
return left.Equals(right);
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(PointD left, PointD right)
{
return !left.Equals(right);
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator +(PointD left, PointD right)
{
return new PointD(left.X + right.X, left.Y + right.Y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator -(PointD left, PointD right)
{
return new PointD(left.X - right.X, left.Y - right.Y);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator *(PointD left, PointD right)
{
return new PointD(left.X * right.X, left.Y * right.Y);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="left">The left.</param>
/// <param name="right">The right.</param>
/// <returns>The result of the operator.</returns>
public static PointD operator /(PointD left, PointD right)
{
return new PointD(left.X / right.X, left.Y / right.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(PointD offset)
{
return new PointD(_x + offset.X, _y + offset.Y);
//return Offset(offset.X, offset.Y);
}
/// <summary>
/// Returns the sum of two points by adding X and Y values together.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method adds the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Add(double offsetX, double offsetY)
{
return new PointD(_x + offsetX, _y + offsetY);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(PointD offset)
{
return new PointD(_x - offset.X, _y - offset.Y);
}
/// <summary>
/// Returns the difference of two points by subtracting the specified X and Y values.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
/// <remarks>This method subtracts the X and Y coordinates and returns a new point at that location.</remarks>
public PointD Subtract(double offsetX, double offsetY)
{
return new PointD(_x - offsetX, _y - offsetY);
}
/// <summary>
/// Returns the product of two points by multiplying X and Y values together.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
/// <remarks>This method multiplies the X and Y coordinates together and returns a new point at that location. This
/// is typically used to scale a point from one coordinate system to another.</remarks>
public PointD Multiply(PointD offset)
{
return new PointD(_x * offset.X, _y * offset.Y);
}
/// <summary>
/// Multiplies the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Multiply(double offsetX, double offsetY)
{
return new PointD(_x * offsetX, _y * offsetY);
}
/// <summary>
/// Divides the specified offset.
/// </summary>
/// <param name="offset">The offset.</param>
/// <returns></returns>
public PointD Divide(PointD offset)
{
return new PointD(_x / offset.X, _y / offset.Y);
}
/// <summary>
/// Divides the specified offset X.
/// </summary>
/// <param name="offsetX">The offset X.</param>
/// <param name="offsetY">The offset Y.</param>
/// <returns></returns>
public PointD Divide(double offsetX, double offsetY)
{
return new PointD(_x / offsetX, _y / offsetY);
}
#endregion Operators
#region Conversions
/// <summary>
/// Performs an explicit conversion from <see cref="DotSpatial.Positioning.PointD"/> to <see cref="System.String"/>.
/// </summary>
/// <param name="value">The value.</param>
/// <returns>The result of the conversion.</returns>
public static explicit operator string(PointD value)
{
return value.ToString();
}
#endregion Conversions
#region IEquatable<PointD> Members
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <returns></returns>
public bool Equals(PointD value)
{
return (_x == value.X) && (_y == value.Y);
}
/// <summary>
/// Equalses the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="precision">The precision.</param>
/// <returns></returns>
public bool Equals(PointD value, int precision)
{
return ((Math.Round(_x, precision) == Math.Round(value.X, precision))
&& (Math.Round(_y, precision) == Math.Round(value.Y, precision)));
}
#endregion IEquatable<PointD> Members
#region IFormattable Members
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">The format to use.-or- A null reference (Nothing in Visual Basic) to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation.</param>
/// <param name="formatProvider">The provider to use to format the value.-or- A null reference (Nothing in Visual Basic) to obtain the numeric format information from the current locale setting of the operating system.</param>
/// <returns>A <see cref="System.String"/> that represents this instance.</returns>
public string ToString(string format, IFormatProvider formatProvider)
{
CultureInfo culture = (CultureInfo)formatProvider ?? CultureInfo.CurrentCulture;
if (string.IsNullOrEmpty(format))
format = "G";
return _x.ToString(format, formatProvider)
+ culture.TextInfo.ListSeparator
+ _y.ToString(format, formatProvider);
}
#endregion IFormattable Members
#region IXmlSerializable Members
/// <summary>
/// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class.
/// </summary>
/// <returns>An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method.</returns>
XmlSchema IXmlSerializable.GetSchema()
{
return null;
}
/// <summary>
/// Converts an object into its XML representation.
/// </summary>
/// <param name="writer">The <see cref="T:System.Xml.XmlWriter"/> stream to which the object is serialized.</param>
public void WriteXml(XmlWriter writer)
{
writer.WriteAttributeString("X",
_x.ToString("G17", CultureInfo.InvariantCulture));
writer.WriteAttributeString("Y",
_y.ToString("G", CultureInfo.InvariantCulture));
}
/// <summary>
/// Generates an object from its XML representation.
/// </summary>
/// <param name="reader">The <see cref="T:System.Xml.XmlReader"/> stream from which the object is deserialized.</param>
public void ReadXml(XmlReader reader)
{
double.TryParse(reader.GetAttribute("X"), NumberStyles.Any, CultureInfo.InvariantCulture, out _x);
double.TryParse(reader.GetAttribute("Y"), NumberStyles.Any, CultureInfo.InvariantCulture, out _y);
reader.Read();
}
#endregion IXmlSerializable Members
}
}
| |
// ***********************************************************************
// Copyright (c) 2016 Charlie Poole, Rob Prouse
//
// 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.ComponentModel;
using NUnit.Framework.Constraints;
using NUnit.Framework.Internal;
namespace NUnit.Framework
{
/// <summary>
/// Provides static methods to express conditions
/// that must be met for the test to succeed. If
/// any test fails, a warning is issued.
/// </summary>
public class Warn
{
#region Equals and ReferenceEquals
/// <summary>
/// DO NOT USE!
/// The Equals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a">The left object.</param>
/// <param name="b">The right object.</param>
/// <returns>Not applicable</returns>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new bool Equals(object a, object b)
{
throw new InvalidOperationException("Warn.Equals should not be used for Assertions.");
}
/// <summary>
/// DO NOT USE!
/// The ReferenceEquals method throws an InvalidOperationException. This is done
/// to make sure there is no mistake by calling this function.
/// </summary>
/// <param name="a">The left object.</param>
/// <param name="b">The right object.</param>
[EditorBrowsable(EditorBrowsableState.Never)]
public static new void ReferenceEquals(object a, object b)
{
throw new InvalidOperationException("Warn.ReferenceEquals should not be used for Assertions.");
}
#endregion
#region Warn.Unless
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
public static void Unless<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Warn.Unless(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void Unless<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
IssueWarning(result, message, args);
}
private static void IssueWarning(ConstraintResult result, string message, object[] args)
{
MessageWriter writer = new TextMessageWriter(message, args);
result.WriteMessageTo(writer);
Assert.Warn(writer.ToString());
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void Unless<TActual>(
ActualValueDelegate<TActual> del,
IResolveConstraint expr,
Func<string> getExceptionMessage)
{
var constraint = expr.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
IssueWarning(result, getExceptionMessage(), null);
}
#endregion
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void Unless(bool condition, string message, params object[] args)
{
Warn.Unless(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public static void Unless(bool condition)
{
Warn.Unless(condition, Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void Unless(bool condition, Func<string> getExceptionMessage)
{
Warn.Unless(condition, Is.True, getExceptionMessage);
}
#endregion
#region Lambda returning Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="InconclusiveException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void Unless(Func<bool> condition, string message, params object[] args)
{
Warn.Unless(condition.Invoke(), Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="InconclusiveException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
public static void Unless(Func<bool> condition)
{
Warn.Unless(condition.Invoke(), Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false the method throws
/// an <see cref="InconclusiveException"/>.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void Unless(Func<bool> condition, Func<string> getExceptionMessage)
{
Warn.Unless(condition.Invoke(), Is.True, getExceptionMessage);
}
#endregion
#region TestDelegate
/// <summary>
/// Asserts that the code represented by a delegate throws an exception
/// that satisfies the constraint provided.
/// </summary>
/// <param name="code">A TestDelegate to be executed</param>
/// <param name="constraint">A Constraint expression to be applied</param>
public static void Unless(TestDelegate code, IResolveConstraint constraint)
{
Warn.Unless((object)code, constraint);
}
#endregion
#region Generic
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
public static void Unless<TActual>(TActual actual, IResolveConstraint expression)
{
Warn.Unless(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void Unless<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
IssueWarning(result, message, args);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void Unless<TActual>(
TActual actual,
IResolveConstraint expression,
Func<string> getExceptionMessage)
{
var constraint = expression.Resolve();
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
IssueWarning(result, getExceptionMessage(), null);
}
#endregion
#endregion
#region Warn.If
#region ActualValueDelegate
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// fails and issuing a warning on success.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
public static void If<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr)
{
Warn.If(del, expr.Resolve(), null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// fails and issuing a warning on success.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void If<TActual>(ActualValueDelegate<TActual> del, IResolveConstraint expr, string message, params object[] args)
{
var constraint = new NotConstraint(expr.Resolve());
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
IssueWarning(result, message, args);
}
//private static void IssueWarning(ConstraintResult result, string message, object[] args)
//{
// MessageWriter writer = new TextMessageWriter(message, args);
// result.WriteMessageTo(writer);
// Assert.Warn(writer.ToString());
//}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// fails and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="del">An ActualValueDelegate returning the value to be tested</param>
/// <param name="expr">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void If<TActual>(
ActualValueDelegate<TActual> del,
IResolveConstraint expr,
Func<string> getExceptionMessage)
{
var constraint = new NotConstraint(expr.Resolve());
IncrementAssertCount();
var result = constraint.ApplyTo(del);
if (!result.IsSuccess)
IssueWarning(result, getExceptionMessage(), null);
}
#endregion
#region Boolean
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="message">The message to display if the condition is false</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void If(bool condition, string message, params object[] args)
{
Warn.If(condition, Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
public static void If(bool condition)
{
Warn.If(condition, Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is true. If the condition is false a warning is issued.
/// </summary>
/// <param name="condition">The evaluated condition</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void If(bool condition, Func<string> getExceptionMessage)
{
Warn.If(condition, Is.True, getExceptionMessage);
}
#endregion
#region Lambda returning Boolean
/// <summary>
/// Asserts that a condition is false. If the condition is true a warning is issued.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="message">The message to display if the condition is true</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void If(Func<bool> condition, string message, params object[] args)
{
Warn.If(condition.Invoke(), Is.True, message, args);
}
/// <summary>
/// Asserts that a condition is false. If the condition is true a warning is issued.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
public static void If(Func<bool> condition)
{
Warn.If(condition.Invoke(), Is.True, null, null);
}
/// <summary>
/// Asserts that a condition is false. If the condition is true a warning is issued.
/// </summary>
/// <param name="condition">A lambda that returns a Boolean</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void If(Func<bool> condition, Func<string> getExceptionMessage)
{
Warn.If(condition.Invoke(), Is.True, getExceptionMessage);
}
#endregion
#region Generic
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// fails and issuing a warning if it succeeds.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
public static void If<TActual>(TActual actual, IResolveConstraint expression)
{
Warn.If(actual, expression, null, null);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// fails and issuing a warning if it succeeds.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="message">The message that will be displayed on failure</param>
/// <param name="args">Arguments to be used in formatting the message</param>
public static void If<TActual>(TActual actual, IResolveConstraint expression, string message, params object[] args)
{
var constraint = new NotConstraint(expression.Resolve());
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
IssueWarning(result, message, args);
}
/// <summary>
/// Apply a constraint to an actual value, succeeding if the constraint
/// is satisfied and issuing a warning on failure.
/// </summary>
/// <typeparam name="TActual">The Type being compared.</typeparam>
/// <param name="actual">The actual value to test</param>
/// <param name="expression">A Constraint expression to be applied</param>
/// <param name="getExceptionMessage">A function to build the message included with the Exception</param>
public static void If<TActual>(
TActual actual,
IResolveConstraint expression,
Func<string> getExceptionMessage)
{
var constraint = new NotConstraint(expression.Resolve());
IncrementAssertCount();
var result = constraint.ApplyTo(actual);
if (!result.IsSuccess)
IssueWarning(result, getExceptionMessage(), null);
}
#endregion
#endregion
#region Helper Methods
private static void IncrementAssertCount()
{
TestExecutionContext.CurrentContext.IncrementAssertCount();
}
#endregion
}
}
| |
using System;
using NUnit.Framework;
using System.Drawing;
using OpenQA.Selenium.Environment;
using System.Collections.ObjectModel;
namespace OpenQA.Selenium
{
[TestFixture]
public class VisibilityTest : DriverTestFixture
{
[Test]
public void ShouldAllowTheUserToTellIfAnElementIsDisplayedOrNot()
{
driver.Url = javascriptPage;
Assert.That(driver.FindElement(By.Id("displayed")).Displayed, Is.True, "Element with ID 'displayed' should be displayed");
Assert.That(driver.FindElement(By.Id("none")).Displayed, Is.False, "Element with ID 'none' should not be displayed");
Assert.That(driver.FindElement(By.Id("suppressedParagraph")).Displayed, Is.False, "Element with ID 'suppressedParagraph' should not be displayed");
Assert.That(driver.FindElement(By.Id("hidden")).Displayed, Is.False, "Element with ID 'hidden' should not be displayed");
}
[Test]
public void VisibilityShouldTakeIntoAccountParentVisibility()
{
driver.Url = javascriptPage;
IWebElement childDiv = driver.FindElement(By.Id("hiddenchild"));
IWebElement hiddenLink = driver.FindElement(By.Id("hiddenlink"));
Assert.That(childDiv.Displayed, Is.False, "Child div should not be displayed");
Assert.That(hiddenLink.Displayed, Is.False, "Hidden link should not be displayed");
}
[Test]
public void ShouldCountElementsAsVisibleIfStylePropertyHasBeenSet()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Id("visibleSubElement"));
Assert.That(shown.Displayed, Is.True);
}
[Test]
public void ShouldModifyTheVisibilityOfAnElementDynamically()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("hideMe"));
Assert.That(element.Displayed, Is.True);
element.Click();
Assert.That(element.Displayed, Is.False);
}
[Test]
public void HiddenInputElementsAreNeverVisible()
{
driver.Url = javascriptPage;
IWebElement shown = driver.FindElement(By.Name("hidden"));
Assert.That(shown.Displayed, Is.False);
}
[Test]
public void ShouldNotBeAbleToClickOnAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.That(() => element.Click(), Throws.InstanceOf<ElementNotInteractableException>());
}
[Test]
public void ShouldNotBeAbleToTypeAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("unclickable"));
Assert.That(() => element.SendKeys("You don't see me"), Throws.InstanceOf<ElementNotInteractableException>());
Assert.That(element.GetAttribute("value"), Is.Not.EqualTo("You don't see me"));
}
[Test]
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.That(element.Displayed, Is.True);
}
[Test]
public void ParentNodeVisibleWhenAllChildrenAreAbsolutelyPositionedAndOverflowIsHidden()
{
String url = EnvironmentManager.Instance.UrlBuilder.WhereIs("visibility-css.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("suggest"));
Assert.That(element.Displayed, Is.True);
}
[Test]
[IgnoreBrowser(Browser.Opera)]
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.That(right.Displayed, Is.False, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.That(bottomRight.Displayed, Is.False, "Failed for " + page);
}
}
[Test]
[IgnoreBrowser(Browser.Opera)]
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.That(bottom.Displayed, Is.False, "Failed for " + page);
IWebElement bottomRight = driver.FindElement(By.Id("bottom-right"));
Assert.That(bottomRight.Displayed, Is.False, "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.That(right.Displayed, Is.True, "Failed for " + page);
}
}
[Test]
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.That(bottom.Displayed, Is.True, "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.That(bottomRight.Displayed, Is.True, "Failed for " + page);
}
}
[Test]
[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.That(element.Displayed, Is.True);
}
finally
{
window.Size = originalSize;
}
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
public void ShouldShowElementNotVisibleWithHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("singleHidden"));
Assert.That(element.Displayed, Is.False);
}
[Test]
[IgnoreBrowser(Browser.IE, "IE does not support the hidden attribute")]
public void ShouldShowElementNotVisibleWhenParentElementHasHiddenAttribute()
{
string url = EnvironmentManager.Instance.UrlBuilder.WhereIs("hidden.html");
driver.Url = url;
IWebElement element = driver.FindElement(By.Id("child"));
Assert.That(element.Displayed, Is.False);
}
[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]
[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.That(apples.Selected, Is.True, "Apples should be selected");
Assert.That(oranges.Selected, Is.False, "Oranges shoudl be selected");
oranges.Click();
Assert.That(apples.Selected, Is.False, "Apples should not be selected");
Assert.That(oranges.Selected, Is.True, "Oranges should be selected");
}
[Test]
public void CorrectlyDetectMapElementsAreShown()
{
driver.Url = mapVisibilityPage;
IWebElement area = driver.FindElement(By.Id("mtgt_unnamed_0"));
bool isShown = area.Displayed;
Assert.That(isShown, Is.True, "The element and the enclosing map should be considered shown.");
}
//------------------------------------------------------------------
// Tests below here are not included in the Java test suite
//------------------------------------------------------------------
[Test]
public void ShouldNotBeAbleToSelectAnElementThatIsNotDisplayed()
{
driver.Url = javascriptPage;
IWebElement element = driver.FindElement(By.Id("untogglable"));
Assert.That(() => element.Click(), Throws.InstanceOf<ElementNotInteractableException>());
}
[Test]
public void ElementsWithOpacityZeroShouldNotBeVisible()
{
driver.Url = clickJackerPage;
IWebElement element = driver.FindElement(By.Id("clickJacker"));
Assert.That(element.Displayed, Is.False);
}
}
}
| |
namespace Lucene.Net.Index
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Lucene.Net.Analysis;
using NUnit.Framework;
using System.IO;
using BytesRef = Lucene.Net.Util.BytesRef;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using IndexInput = Lucene.Net.Store.IndexInput;
using IndexSearcher = Lucene.Net.Search.IndexSearcher;
using IOContext = Lucene.Net.Store.IOContext;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MockDirectoryWrapper = Lucene.Net.Store.MockDirectoryWrapper;
using PhraseQuery = Lucene.Net.Search.PhraseQuery;
using RAMDirectory = Lucene.Net.Store.RAMDirectory;
using ScoreDoc = Lucene.Net.Search.ScoreDoc;
using TestUtil = Lucene.Net.Util.TestUtil;
/// <summary>
/// Tests lazy skipping on the proximity file.
///
/// </summary>
[TestFixture]
public class TestLazyProxSkipping : LuceneTestCase
{
private IndexSearcher Searcher;
private int SeeksCounter = 0;
private string Field = "tokens";
private string Term1 = "xx";
private string Term2 = "yy";
private string Term3 = "zz";
private class SeekCountingDirectory : MockDirectoryWrapper
{
private readonly TestLazyProxSkipping OuterInstance;
public SeekCountingDirectory(TestLazyProxSkipping outerInstance, Directory @delegate)
: base(Random(), @delegate)
{
this.OuterInstance = outerInstance;
}
public override IndexInput OpenInput(string name, IOContext context)
{
IndexInput ii = base.OpenInput(name, context);
if (name.EndsWith(".prx") || name.EndsWith(".pos"))
{
// we decorate the proxStream with a wrapper class that allows to count the number of calls of seek()
ii = new SeeksCountingStream(OuterInstance, ii);
}
return ii;
}
}
private void CreateIndex(int numHits)
{
int numDocs = 500;
Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper(this);
Directory directory = new SeekCountingDirectory(this, new RAMDirectory());
// note: test explicitly disables payloads
IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, analyzer).SetMaxBufferedDocs(10).SetMergePolicy(NewLogMergePolicy(false)));
for (int i = 0; i < numDocs; i++)
{
Document doc = new Document();
string content;
if (i % (numDocs / numHits) == 0)
{
// add a document that matches the query "term1 term2"
content = this.Term1 + " " + this.Term2;
}
else if (i % 15 == 0)
{
// add a document that only contains term1
content = this.Term1 + " " + this.Term1;
}
else
{
// add a document that contains term2 but not term 1
content = this.Term3 + " " + this.Term2;
}
doc.Add(NewTextField(this.Field, content, Documents.Field.Store.YES));
writer.AddDocument(doc);
}
// make sure the index has only a single segment
writer.ForceMerge(1);
writer.Dispose();
SegmentReader reader = GetOnlySegmentReader(DirectoryReader.Open(directory));
this.Searcher = NewSearcher(reader);
}
private class AnalyzerAnonymousInnerClassHelper : Analyzer
{
private readonly TestLazyProxSkipping OuterInstance;
public AnalyzerAnonymousInnerClassHelper(TestLazyProxSkipping outerInstance)
{
this.OuterInstance = outerInstance;
}
public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader)
{
return new TokenStreamComponents(new MockTokenizer(reader, MockTokenizer.WHITESPACE, true));
}
}
private ScoreDoc[] Search()
{
// create PhraseQuery "term1 term2" and search
PhraseQuery pq = new PhraseQuery();
pq.Add(new Term(this.Field, this.Term1));
pq.Add(new Term(this.Field, this.Term2));
return this.Searcher.Search(pq, null, 1000).ScoreDocs;
}
private void PerformTest(int numHits)
{
CreateIndex(numHits);
this.SeeksCounter = 0;
ScoreDoc[] hits = Search();
// verify that the right number of docs was found
Assert.AreEqual(numHits, hits.Length);
// check if the number of calls of seek() does not exceed the number of hits
Assert.IsTrue(this.SeeksCounter > 0);
Assert.IsTrue(this.SeeksCounter <= numHits + 1, "seeksCounter=" + this.SeeksCounter + " numHits=" + numHits);
Searcher.IndexReader.Dispose();
}
[Test]
public virtual void TestLazySkipping()
{
string fieldFormat = TestUtil.GetPostingsFormat(this.Field);
AssumeFalse("this test cannot run with Memory postings format", fieldFormat.Equals("Memory"));
AssumeFalse("this test cannot run with Direct postings format", fieldFormat.Equals("Direct"));
AssumeFalse("this test cannot run with SimpleText postings format", fieldFormat.Equals("SimpleText"));
// test whether only the minimum amount of seeks()
// are performed
PerformTest(5);
PerformTest(10);
}
[Test]
public virtual void TestSeek()
{
Directory directory = NewDirectory();
IndexWriter writer = new IndexWriter(directory, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random())));
for (int i = 0; i < 10; i++)
{
Document doc = new Document();
doc.Add(NewTextField(this.Field, "a b", Documents.Field.Store.YES));
writer.AddDocument(doc);
}
writer.Dispose();
IndexReader reader = DirectoryReader.Open(directory);
DocsAndPositionsEnum tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), this.Field, new BytesRef("b"));
for (int i = 0; i < 10; i++)
{
tp.NextDoc();
Assert.AreEqual(tp.DocID(), i);
Assert.AreEqual(tp.NextPosition(), 1);
}
tp = MultiFields.GetTermPositionsEnum(reader, MultiFields.GetLiveDocs(reader), this.Field, new BytesRef("a"));
for (int i = 0; i < 10; i++)
{
tp.NextDoc();
Assert.AreEqual(tp.DocID(), i);
Assert.AreEqual(tp.NextPosition(), 0);
}
reader.Dispose();
directory.Dispose();
}
// Simply extends IndexInput in a way that we are able to count the number
// of invocations of seek()
internal class SeeksCountingStream : IndexInput
{
private readonly TestLazyProxSkipping OuterInstance;
internal IndexInput Input;
internal SeeksCountingStream(TestLazyProxSkipping outerInstance, IndexInput input)
: base("SeekCountingStream(" + input + ")")
{
this.OuterInstance = outerInstance;
this.Input = input;
}
public override byte ReadByte()
{
return this.Input.ReadByte();
}
public override void ReadBytes(byte[] b, int offset, int len)
{
this.Input.ReadBytes(b, offset, len);
}
public override void Dispose()
{
this.Input.Dispose();
}
public override long FilePointer
{
get
{
return this.Input.FilePointer;
}
}
public override void Seek(long pos)
{
OuterInstance.SeeksCounter++;
this.Input.Seek(pos);
}
public override long Length()
{
return this.Input.Length();
}
public override object Clone()
{
return new SeeksCountingStream(OuterInstance, (IndexInput)this.Input.Clone());
}
}
}
}
| |
// Copyright (c) Rotorz Limited. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root.
#if UNITY_EDITOR
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
namespace Lockstep.Rotorz.ReorderableList {
/// <summary>
/// Utility class for drawing reorderable lists.
/// </summary>
public static class ReorderableListGUI {
/// <summary>
/// Default list item height is 18 pixels.
/// </summary>
public const float DefaultItemHeight = 18;
/// <summary>
/// Gets or sets the zero-based index of the last item that was changed. A value of -1
/// indicates that no item was changed by list.
/// </summary>
/// <remarks>
/// <para>This property should not be set when items are added or removed.</para>
/// </remarks>
public static int IndexOfChangedItem { get; internal set; }
/// <summary>
/// Gets the control ID of the list that is currently being drawn.
/// </summary>
public static int CurrentListControlID {
get { return ReorderableListControl.CurrentListControlID; }
}
/// <summary>
/// Gets the position of the list control that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemTotalPosition"/>
public static Rect CurrentListPosition {
get { return ReorderableListControl.CurrentListPosition; }
}
/// <summary>
/// Gets the zero-based index of the list item that is currently being drawn;
/// or a value of -1 if no item is currently being drawn.
/// </summary>
public static int CurrentItemIndex {
get { return ReorderableListControl.CurrentItemIndex; }
}
/// <summary>
/// Gets the total position of the list item that is currently being drawn.
/// </summary>
/// <remarks>
/// <para>The value of this property should be ignored for <see cref="EventType.Layout"/>
/// type events when using reorderable list controls with automatic layout.</para>
/// </remarks>
/// <see cref="CurrentItemIndex"/>
/// <see cref="CurrentListPosition"/>
public static Rect CurrentItemTotalPosition {
get { return ReorderableListControl.CurrentItemTotalPosition; }
}
#region Basic Item Drawers
/// <summary>
/// Default list item drawer implementation.
/// </summary>
/// <remarks>
/// <para>Always presents the label "Item drawer not implemented.".</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Unmodified value of list item.
/// </returns>
/// <typeparam name="T">Type of list item.</typeparam>
public static T DefaultItemDrawer<T>(Rect position, T item) {
GUI.Label(position, "Item drawer not implemented.");
return item;
}
/// <summary>
/// Draws text field allowing list items to be edited.
/// </summary>
/// <remarks>
/// <para>Null values are automatically changed to empty strings since null
/// values cannot be edited using a text field.</para>
/// <para>Value of <c>GUI.changed</c> is set to <c>true</c> if value of item
/// is modified.</para>
/// </remarks>
/// <param name="position">Position to draw list item control(s).</param>
/// <param name="item">Value of list item.</param>
/// <returns>
/// Modified value of list item.
/// </returns>
public static string TextFieldItemDrawer(Rect position, string item) {
if (item == null) {
item = "";
GUI.changed = true;
}
return EditorGUI.TextField(position, item);
}
#endregion
/// <summary>
/// Gets the default list control implementation.
/// </summary>
private static ReorderableListControl DefaultListControl { get; set; }
static ReorderableListGUI() {
DefaultListControl = new ReorderableListControl();
// Duplicate default styles to prevent user scripts from interferring with
// the default list control instance.
DefaultListControl.ContainerStyle = new GUIStyle(ReorderableListStyles.Container);
DefaultListControl.FooterButtonStyle = new GUIStyle(ReorderableListStyles.FooterButton);
DefaultListControl.ItemButtonStyle = new GUIStyle(ReorderableListStyles.ItemButton);
IndexOfChangedItem = -1;
}
private static GUIContent s_Temp = new GUIContent();
#region Title Control
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title(titleContent);
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Content for title control.</param>
public static void Title(GUIContent title) {
Rect position = GUILayoutUtility.GetRect(title, ReorderableListStyles.Title);
position.height += 6;
Title(position, title);
}
/// <summary>
/// Draw title control for list field.
/// </summary>
/// <remarks>
/// <para>When needed, should be shown immediately before list field.</para>
/// </remarks>
/// <example>
/// <code language="csharp"><![CDATA[
/// ReorderableListGUI.Title("Your Title");
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// <code language="unityscript"><![CDATA[
/// ReorderableListGUI.Title('Your Title');
/// ReorderableListGUI.ListField(list, DynamicListGU.TextFieldItemDrawer);
/// ]]></code>
/// </example>
/// <param name="title">Text for title control.</param>
public static void Title(string title) {
s_Temp.text = title;
Title(s_Temp);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="title">Content for title control.</param>
public static void Title(Rect position, GUIContent title) {
if (Event.current.type == EventType.Repaint)
ReorderableListStyles.Title.Draw(position, title, false, false, false, false);
}
/// <summary>
/// Draw title control for list field with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="text">Text for title control.</param>
public static void Title(Rect position, string text) {
s_Temp.text = text;
Title(position, s_Temp);
}
#endregion
#region List<T> Control
/// <summary>
/// Draw list field control.
/// </summary>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control with absolute positioning.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="list">The list which can be reordered.</param>
/// <param name="drawItem">Callback to draw list item.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="itemHeight">Height of a single list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <typeparam name="T">Type of list item.</typeparam>
private static void DoListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
var adaptor = new GenericListAdaptor<T>(list, drawItem, itemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, float itemHeight) {
DoListField<T>(list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField<T>(list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute<T>(position, list, drawItem, drawEmpty, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListField<T>(list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, float itemHeight) {
DoListFieldAbsolute<T>(position, list, drawItem, null, itemHeight, 0);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem, ReorderableListFlags flags) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, flags);
}
/// <inheritdoc cref="DoListField{T}(IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmpty, float, ReorderableListFlags)"/>
public static void ListField<T>(IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListField<T>(list, drawItem, null, DefaultItemHeight, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute{T}(Rect, IList{T}, ReorderableListControl.ItemDrawer{T}, ReorderableListControl.DrawEmptyAbsolute, float, ReorderableListFlags)"/>
public static void ListFieldAbsolute<T>(Rect position, IList<T> list, ReorderableListControl.ItemDrawer<T> drawItem) {
DoListFieldAbsolute<T>(position, list, drawItem, null, DefaultItemHeight, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="itemCount">Count of items in list.</param>
/// <param name="itemHeight">Fixed height of list item.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(int itemCount, float itemHeight, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(itemCount, itemHeight);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, ReorderableListFlags flags) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, flags);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount, float itemHeight) {
return CalculateListFieldHeight(itemCount, itemHeight, 0);
}
/// <inheritdoc cref="CalculateListFieldHeight(int, float, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(int itemCount) {
return CalculateListFieldHeight(itemCount, DefaultItemHeight, 0);
}
#endregion
#region SerializedProperty Control
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for serializable property array.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="fixedItemHeight">Use fixed height for items rather than <see cref="UnityEditor.EditorGUI.GetPropertyHeight(SerializedProperty)"/>.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
var adaptor = new SerializedPropertyAdaptor(arrayProperty, fixedItemHeight);
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, 0, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListField(arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, 0, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty) {
DoListField(arrayProperty, 0, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty) {
DoListFieldAbsolute(position, arrayProperty, 0, null, 0);
}
/// <summary>
/// Calculate height of list field for absolute positioning.
/// </summary>
/// <param name="arrayProperty">Serializable property.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(new SerializedPropertyAdaptor(arrayProperty));
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(SerializedProperty, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(SerializedProperty arrayProperty) {
return CalculateListFieldHeight(arrayProperty, 0);
}
#endregion
#region SerializedProperty Control (Fixed Item Height)
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListField(arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight, ReorderableListFlags flags) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, flags);
}
/// <inheritdoc cref="DoListField(SerializedProperty, float, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(SerializedProperty arrayProperty, float fixedItemHeight) {
DoListField(arrayProperty, fixedItemHeight, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, SerializedProperty, float, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, SerializedProperty arrayProperty, float fixedItemHeight) {
DoListFieldAbsolute(position, arrayProperty, fixedItemHeight, null, 0);
}
#endregion
#region Adaptor Control
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(adaptor, drawEmpty, flags);
}
/// <summary>
/// Draw list field control for adapted collection.
/// </summary>
/// <param name="position">Position of control.</param>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="drawEmpty">Callback to draw custom content for empty list (optional).</param>
/// <param name="flags">Optional flags to pass into list field.</param>
private static void DoListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags = 0) {
ReorderableListControl.DrawControlFromState(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty, ReorderableListFlags flags) {
DoListField(adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, drawEmpty, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmpty drawEmpty) {
DoListField(adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListControl.DrawEmptyAbsolute drawEmpty) {
DoListFieldAbsolute(position, adaptor, drawEmpty, 0);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListField(adaptor, null, flags);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
DoListFieldAbsolute(position, adaptor, null, flags);
}
/// <inheritdoc cref="DoListField(IReorderableListAdaptor, ReorderableListControl.DrawEmpty, ReorderableListFlags)"/>
public static void ListField(IReorderableListAdaptor adaptor) {
DoListField(adaptor, null, 0);
}
/// <inheritdoc cref="DoListFieldAbsolute(Rect, IReorderableListAdaptor, ReorderableListControl.DrawEmptyAbsolute, ReorderableListFlags)"/>
public static void ListFieldAbsolute(Rect position, IReorderableListAdaptor adaptor) {
DoListFieldAbsolute(position, adaptor, null, 0);
}
/// <summary>
/// Calculate height of list field for adapted collection.
/// </summary>
/// <param name="adaptor">Reorderable list adaptor.</param>
/// <param name="flags">Optional flags to pass into list field.</param>
/// <returns>
/// Required list height in pixels.
/// </returns>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor, ReorderableListFlags flags) {
// We need to push/pop flags so that nested controls are properly calculated.
var restoreFlags = DefaultListControl.Flags;
try {
DefaultListControl.Flags = flags;
return DefaultListControl.CalculateListHeight(adaptor);
}
finally {
DefaultListControl.Flags = restoreFlags;
}
}
/// <inheritdoc cref="CalculateListFieldHeight(IReorderableListAdaptor, ReorderableListFlags)"/>
public static float CalculateListFieldHeight(IReorderableListAdaptor adaptor) {
return CalculateListFieldHeight(adaptor, 0);
}
#endregion
}
}
#endif
| |
//---------------------------------------------------------------------
// <copyright file="TypeInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Diagnostics; // Please use PlanCompiler.Assert instead of Debug.Assert in this class...
// It is fine to use Debug.Assert in cases where you assert an obvious thing that is supposed
// to prevent from simple mistakes during development (e.g. method argument validation
// in cases where it was you who created the variables or the variables had already been validated or
// in "else" clauses where due to code changes (e.g. adding a new value to an enum type) the default
// "else" block is chosen why the new condition should be treated separately). This kind of asserts are
// (can be) helpful when developing new code to avoid simple mistakes but have no or little value in
// the shipped product.
// PlanCompiler.Assert *MUST* be used to verify conditions in the trees. These would be assumptions
// about how the tree was built etc. - in these cases we probably want to throw an exception (this is
// what PlanCompiler.Assert does when the condition is not met) if either the assumption is not correct
// or the tree was built/rewritten not the way we thought it was.
// Use your judgment - if you rather remove an assert than ship it use Debug.Assert otherwise use
// PlanCompiler.Assert.
using System.Globalization;
using System.Data.Common;
using md = System.Data.Metadata.Edm;
using System.Data.Query.InternalTrees;
namespace System.Data.Query.PlanCompiler
{
/// <summary>
/// The kind of type-id in use
/// </summary>
internal enum TypeIdKind
{
UserSpecified = 0,
Generated
}
/// <summary>
/// The TypeInfo class encapsulates various pieces of information about a type.
/// The most important of these include the "flattened" record type - corresponding
/// to the type, and the TypeId field for nominal types
/// </summary>
internal class TypeInfo
{
#region private state
private readonly md.TypeUsage m_type; // the type
private object m_typeId; // the type's Id, assigned by the StructuredTypeInfo processing.
private List<TypeInfo> m_immediateSubTypes; // the list of children below this type in it's type hierarchy.
private readonly TypeInfo m_superType; // the type one level up in this types type hierarchy -- the base type.
private readonly RootTypeInfo m_rootType; // the top-most type in this types type hierarchy
#endregion
#region Constructors and factory methods
/// <summary>
/// Creates type information for a type
/// </summary>
/// <param name="type"></param>
/// <param name="superTypeInfo"></param>
/// <returns></returns>
internal static TypeInfo Create(md.TypeUsage type, TypeInfo superTypeInfo, ExplicitDiscriminatorMap discriminatorMap)
{
TypeInfo result;
if (superTypeInfo == null)
{
result = new RootTypeInfo(type, discriminatorMap);
}
else
{
result = new TypeInfo(type, superTypeInfo);
}
return result;
}
protected TypeInfo(md.TypeUsage type, TypeInfo superType)
{
m_type = type;
m_immediateSubTypes = new List<TypeInfo>();
m_superType = superType;
if (superType != null)
{
// Add myself to my supertype's list of subtypes
superType.m_immediateSubTypes.Add(this);
// my supertype's root type is mine as well
m_rootType = superType.RootType;
}
}
#endregion
#region "public" properties for all types
/// <summary>
/// Is this the root type?
/// True for entity, complex types and ref types, if this is the root of the
/// hierarchy.
/// Always true for Record types
/// </summary>
internal bool IsRootType
{
get
{
return m_rootType == null;
}
}
/// <summary>
/// the types that derive from this type
/// </summary>
internal List<TypeInfo> ImmediateSubTypes
{
get
{
return m_immediateSubTypes;
}
}
/// <summary>
/// the immediate parent type of this type.
/// </summary>
internal TypeInfo SuperType
{
get
{
return m_superType;
}
}
/// <summary>
/// the top most type in the hierarchy.
/// </summary>
internal RootTypeInfo RootType
{
get
{
return m_rootType ?? (RootTypeInfo)this;
}
}
/// <summary>
/// The metadata type
/// </summary>
internal md.TypeUsage Type
{
get
{
return m_type;
}
}
/// <summary>
/// The typeid value for this type - only applies to nominal types
/// </summary>
internal object TypeId
{
get
{
return m_typeId;
}
set
{
m_typeId = value;
}
}
#endregion
#region "public" properties for root types
// These properties are actually stored on the RootType but we let
// let folks use the TypeInfo class as the proxy to get to them.
// Essentially, they are mostly sugar to simplify coding.
//
// For example:
//
// You could either write:
//
// typeinfo.RootType.FlattenedType
//
// or you can write:
//
// typeinfo.FlattenedType
//
/// <summary>
/// Flattened record version of the type
/// </summary>
internal virtual md.RowType FlattenedType
{
get
{
return RootType.FlattenedType;
}
}
/// <summary>
/// TypeUsage that encloses the Flattened record version of the type
/// </summary>
internal virtual md.TypeUsage FlattenedTypeUsage
{
get
{
return RootType.FlattenedTypeUsage;
}
}
/// <summary>
/// Get the property describing the entityset (if any)
/// </summary>
internal virtual md.EdmProperty EntitySetIdProperty
{
get
{
return RootType.EntitySetIdProperty;
}
}
/// <summary>
/// Does this type have an entitySetId property
/// </summary>
internal bool HasEntitySetIdProperty
{
get
{
return RootType.EntitySetIdProperty != null;
}
}
/// <summary>
/// Get the nullSentinel property (if any)
/// </summary>
internal virtual md.EdmProperty NullSentinelProperty
{
get
{
return RootType.NullSentinelProperty;
}
}
/// <summary>
/// Does this type have a nullSentinel property?
/// </summary>
internal bool HasNullSentinelProperty
{
get
{
return RootType.NullSentinelProperty != null;
}
}
/// <summary>
/// The typeid property in the flattened type - applies only to nominal types
/// this will be used as the type discriminator column.
/// </summary>
internal virtual md.EdmProperty TypeIdProperty
{
get
{
return RootType.TypeIdProperty;
}
}
/// <summary>
/// Does this type need a typeid property? (Needed for complex types and entity types in general)
/// </summary>
internal bool HasTypeIdProperty
{
get
{
return RootType.TypeIdProperty != null;
}
}
/// <summary>
/// All the properties of this type.
/// </summary>
internal virtual IEnumerable<PropertyRef> PropertyRefList
{
get
{
return RootType.PropertyRefList;
}
}
/// <summary>
/// Get the new property for the supplied propertyRef
/// </summary>
/// <param name="propertyRef">property reference (on the old type)</param>
/// <returns></returns>
internal md.EdmProperty GetNewProperty(PropertyRef propertyRef)
{
md.EdmProperty property;
bool result = TryGetNewProperty(propertyRef, true, out property);
Debug.Assert(result, "Should have thrown if the property was not found");
return property;
}
/// <summary>
/// Try get the new property for the supplied propertyRef
/// </summary>
/// <param name="propertyRef">property reference (on the old type)</param>
/// <param name="throwIfMissing">throw if the property is not found</param>
/// <param name="newProperty">the corresponding property on the new type</param>
/// <returns></returns>
internal bool TryGetNewProperty(PropertyRef propertyRef, bool throwIfMissing, out md.EdmProperty newProperty)
{
return this.RootType.TryGetNewProperty(propertyRef, throwIfMissing, out newProperty);
}
/// <summary>
/// Get the list of "key" properties (in the flattened type)
/// </summary>
/// <returns>the key property equivalents in the flattened type</returns>
internal IEnumerable<PropertyRef> GetKeyPropertyRefs()
{
md.EntityTypeBase entityType = null;
md.RefType refType = null;
if (TypeHelpers.TryGetEdmType<md.RefType>(m_type, out refType))
{
entityType = refType.ElementType;
}
else
{
entityType = TypeHelpers.GetEdmType<md.EntityTypeBase>(m_type);
}
// Walk through the list of keys of the entity type, and find their analogs in the
// "flattened" type
foreach (md.EdmMember p in entityType.KeyMembers)
{
// Eventually this could be RelationshipEndMember, but currently only properties are suppported as key members
PlanCompiler.Assert(p is md.EdmProperty, "Non-EdmProperty key members are not supported");
SimplePropertyRef spr = new SimplePropertyRef(p);
yield return spr;
}
}
/// <summary>
/// Get the list of "identity" properties in the flattened type.
/// The identity properties include the entitysetid property, followed by the
/// key properties
/// </summary>
/// <returns>List of identity properties</returns>
internal IEnumerable<PropertyRef> GetIdentityPropertyRefs()
{
if (this.HasEntitySetIdProperty)
{
yield return EntitySetIdPropertyRef.Instance;
}
foreach (PropertyRef p in this.GetKeyPropertyRefs())
{
yield return p;
}
}
/// <summary>
/// Get the list of all properties in the flattened type
/// </summary>
/// <returns></returns>
internal IEnumerable<PropertyRef> GetAllPropertyRefs()
{
foreach (PropertyRef p in this.PropertyRefList)
{
yield return p;
}
}
/// <summary>
/// Get the list of all properties in the flattened type
/// </summary>
/// <returns></returns>
internal IEnumerable<md.EdmProperty> GetAllProperties()
{
foreach (md.EdmProperty m in this.FlattenedType.Properties)
{
yield return m;
}
}
/// <summary>
/// Gets all types in the hierarchy rooted at this.
/// </summary>
internal List<TypeInfo> GetTypeHierarchy()
{
List<TypeInfo> result = new List<TypeInfo>();
GetTypeHierarchy(result);
return result;
}
/// <summary>
/// Adds all types in the hierarchy to the given list.
/// </summary>
private void GetTypeHierarchy(List<TypeInfo> result)
{
result.Add(this);
foreach (TypeInfo subType in this.ImmediateSubTypes)
{
subType.GetTypeHierarchy(result);
}
}
#endregion
}
/// <summary>
/// A subclass of the TypeInfo class above that only represents information
/// about "root" types
/// </summary>
internal class RootTypeInfo : TypeInfo
{
#region private state
private readonly List<PropertyRef> m_propertyRefList;
private readonly Dictionary<PropertyRef, md.EdmProperty> m_propertyMap;
private md.EdmProperty m_nullSentinelProperty;
private md.EdmProperty m_typeIdProperty;
private TypeIdKind m_typeIdKind;
private md.TypeUsage m_typeIdType;
private readonly ExplicitDiscriminatorMap m_discriminatorMap;
private md.EdmProperty m_entitySetIdProperty;
private md.RowType m_flattenedType;
private md.TypeUsage m_flattenedTypeUsage;
#endregion
#region Constructor
/// <summary>
/// Constructor for a root type
/// </summary>
/// <param name="type"></param>
internal RootTypeInfo(md.TypeUsage type, ExplicitDiscriminatorMap discriminatorMap)
: base(type, null)
{
PlanCompiler.Assert(type.EdmType.BaseType == null, "only root types allowed here");
m_propertyMap = new Dictionary<PropertyRef, md.EdmProperty>();
m_propertyRefList = new List<PropertyRef>();
m_discriminatorMap = discriminatorMap;
m_typeIdKind = TypeIdKind.Generated;
}
#endregion
#region "public" surface area
/// <summary>
/// Kind of the typeid column (if any)
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal TypeIdKind TypeIdKind
{
get { return m_typeIdKind; }
set { m_typeIdKind = value; }
}
/// <summary>
/// Datatype of the typeid column (if any)
/// </summary>
internal md.TypeUsage TypeIdType
{
get { return m_typeIdType; }
set { m_typeIdType = value; }
}
/// <summary>
/// Add a mapping from the propertyRef (of the old type) to the
/// corresponding property in the new type.
///
/// NOTE: Only to be used by StructuredTypeInfo
/// </summary>
/// <param name="propertyRef"></param>
/// <param name="newProperty"></param>
internal void AddPropertyMapping(PropertyRef propertyRef, md.EdmProperty newProperty)
{
m_propertyMap[propertyRef] = newProperty;
if (propertyRef is TypeIdPropertyRef)
{
m_typeIdProperty = newProperty;
}
else if (propertyRef is EntitySetIdPropertyRef)
{
m_entitySetIdProperty = newProperty;
}
else if (propertyRef is NullSentinelPropertyRef)
{
m_nullSentinelProperty = newProperty;
}
}
/// <summary>
/// Adds a new property reference to the list of desired properties
/// NOTE: Only to be used by StructuredTypeInfo
/// </summary>
/// <param name="propertyRef"></param>
internal void AddPropertyRef(PropertyRef propertyRef)
{
m_propertyRefList.Add(propertyRef);
}
/// <summary>
/// Flattened record version of the type
/// </summary>
internal new md.RowType FlattenedType
{
get
{
return m_flattenedType;
}
set
{
m_flattenedType = value;
m_flattenedTypeUsage = md.TypeUsage.Create(value);
}
}
/// <summary>
/// TypeUsage that encloses the Flattened record version of the type
/// </summary>
internal new md.TypeUsage FlattenedTypeUsage
{
get
{
return m_flattenedTypeUsage;
}
}
/// <summary>
/// Gets map information for types mapped using simple discriminator pattern.
/// </summary>
internal ExplicitDiscriminatorMap DiscriminatorMap
{
get
{
return m_discriminatorMap;
}
}
/// <summary>
/// Get the property describing the entityset (if any)
/// </summary>
internal new md.EdmProperty EntitySetIdProperty
{
get
{
return m_entitySetIdProperty;
}
}
internal new md.EdmProperty NullSentinelProperty
{
get
{
return m_nullSentinelProperty;
}
}
/// <summary>
/// Get the list of property refs for this type
/// </summary>
internal new IEnumerable<PropertyRef> PropertyRefList
{
get
{
return m_propertyRefList;
}
}
/// <summary>
/// Determines the offset for structured types in Flattened type. For instance, if the original type is of the form:
///
/// { int X, ComplexType Y }
///
/// and the flattened type is of the form:
///
/// { int X, Y_ComplexType_Prop1, Y_ComplexType_Prop2 }
///
/// GetNestedStructureOffset(Y) returns 1
/// </summary>
/// <param name="property">Complex property.</param>
/// <returns>Offset.</returns>
internal int GetNestedStructureOffset(PropertyRef property)
{
// m_propertyRefList contains every element of the flattened type
for (int i = 0; i < m_propertyRefList.Count; i++)
{
NestedPropertyRef nestedPropertyRef = m_propertyRefList[i] as NestedPropertyRef;
// match offset of the first element of the complex type property
if (null != nestedPropertyRef && nestedPropertyRef.InnerProperty.Equals(property))
{
return i;
}
}
PlanCompiler.Assert(false, "no complex structure " + property + " found in TypeInfo");
// return something so that the compiler doesn't complain
return default(int);
}
/// <summary>
/// Try get the new property for the supplied propertyRef
/// </summary>
/// <param name="propertyRef">property reference (on the old type)</param>
/// <param name="throwIfMissing">throw if the property is not found</param>
/// <param name="property">the corresponding property on the new type</param>
/// <returns></returns>
internal new bool TryGetNewProperty(PropertyRef propertyRef, bool throwIfMissing, out md.EdmProperty property)
{
bool result = m_propertyMap.TryGetValue(propertyRef, out property);
if (throwIfMissing && !result)
{
{
PlanCompiler.Assert(false, "Unable to find property " + propertyRef.ToString() + " in type " + this.Type.EdmType.Identity);
}
}
return result;
}
/// <summary>
/// The typeid property in the flattened type - applies only to nominal types
/// this will be used as the type discriminator column.
/// </summary>
internal new md.EdmProperty TypeIdProperty
{
get
{
return m_typeIdProperty;
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading;
using Craft.Net.Common;
namespace Craft.Net.Anvil
{
public class World : IDisposable
{
public const int Height = 256;
public string Name { get; set; }
public string BaseDirectory { get; internal set; }
public Dictionary<Coordinates2D, Region> Regions { get; set; }
public IWorldGenerator WorldGenerator { get; set; }
public event EventHandler<BlockChangeEventArgs> BlockChange;
public event EventHandler<SpawnEntityEventArgs> SpawnEntityRequested;
public World(string name)
{
Name = name;
Regions = new Dictionary<Coordinates2D, Region>();
}
public World(string name, IWorldGenerator worldGenerator) : this(name)
{
WorldGenerator = worldGenerator;
}
public static World LoadWorld(string baseDirectory)
{
if (!Directory.Exists(baseDirectory))
throw new DirectoryNotFoundException();
var world = new World(Path.GetFileName(baseDirectory));
world.BaseDirectory = baseDirectory;
return world;
}
/// <summary>
/// Finds a chunk that contains the specified block coordinates.
/// </summary>
public Chunk FindChunk(Coordinates3D coordinates)
{
Chunk chunk;
FindBlockPosition(coordinates, out chunk);
return chunk;
}
public Chunk GetChunk(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ));
return region.GetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public void GenerateChunk(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ));
region.GenerateChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public Chunk GetChunkWithoutGeneration(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var regionPosition = new Coordinates2D(regionX, regionZ);
if (!Regions.ContainsKey(regionPosition)) return null;
return Regions[regionPosition].GetChunkWithoutGeneration(
new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public void SetChunk(Coordinates2D coordinates, Chunk chunk)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ));
lock (region)
{
chunk.IsModified = true;
region.SetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), chunk);
}
}
public void UnloadRegion(Coordinates2D coordinates)
{
lock (Regions)
{
Regions[coordinates].Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates)));
Regions.Remove(coordinates);
}
}
public void UnloadChunk(Coordinates2D coordinates)
{
int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0);
int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0);
var regionPosition = new Coordinates2D(regionX, regionZ);
if (!Regions.ContainsKey(regionPosition))
throw new ArgumentOutOfRangeException("coordinates");
Regions[regionPosition].UnloadChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32));
}
public short GetBlockId(Coordinates3D coordinates)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetBlockId(coordinates);
}
public byte GetMetadata(Coordinates3D coordinates)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetMetadata(coordinates);
}
public byte GetSkyLight(Coordinates3D coordinates)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetSkyLight(coordinates);
}
public byte GetBlockLight(Coordinates3D coordinates)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
return chunk.GetBlockLight(coordinates);
}
public void SetBlockId(Coordinates3D coordinates, short value)
{
Chunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
chunk.SetBlockId(adjustedCoordinates, value);
OnBlockChange(coordinates);
}
public void SetMetadata(Coordinates3D coordinates, byte value)
{
Chunk chunk;
var adjustedCoordinates = FindBlockPosition(coordinates, out chunk);
chunk.SetMetadata(adjustedCoordinates, value);
OnBlockChange(coordinates);
}
public void SetSkyLight(Coordinates3D coordinates, byte value)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
chunk.SetSkyLight(coordinates, value);
}
public void SetBlockLight(Coordinates3D coordinates, byte value)
{
Chunk chunk;
coordinates = FindBlockPosition(coordinates, out chunk);
chunk.SetBlockLight(coordinates, value);
}
public void Save()
{
lock (Regions)
{
foreach (var region in Regions)
region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key)));
}
}
public void Save(string path)
{
if (!System.IO.Directory.Exists(path))
System.IO.Directory.CreateDirectory(path);
BaseDirectory = path;
lock (Regions)
{
foreach (var region in Regions)
region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key)));
}
}
public Coordinates3D FindBlockPosition(Coordinates3D coordinates, out Chunk chunk)
{
if (coordinates.Y < 0 || coordinates.Y >= Chunk.Height)
throw new ArgumentOutOfRangeException("coordinates", "Coordinates are out of range");
var chunkX = (int)Math.Floor((double)coordinates.X / Chunk.Width);
var chunkZ = (int)Math.Floor((double)coordinates.Z / Chunk.Depth);
chunk = GetChunk(new Coordinates2D(chunkX, chunkZ));
return new Coordinates3D(
(coordinates.X - chunkX * Chunk.Width) % Chunk.Width,
coordinates.Y,
(coordinates.Z - chunkZ * Chunk.Depth) % Chunk.Depth);
}
public static bool IsValidPosition(Coordinates3D position)
{
return position.Y >= 0 && position.Y <= 255;
}
private Region LoadOrGenerateRegion(Coordinates2D coordinates)
{
if (Regions.ContainsKey(coordinates))
return Regions[coordinates];
Region region;
if (BaseDirectory != null)
{
var file = Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates));
if (File.Exists(file))
region = new Region(coordinates, this, file);
else
region = new Region(coordinates, this);
}
else
region = new Region(coordinates, this);
lock (Regions)
Regions[coordinates] = region;
return region;
}
public void Dispose()
{
foreach (var region in Regions)
region.Value.Dispose();
}
public void OnSpawnEntityRequested(object entity)
{
if (SpawnEntityRequested != null) SpawnEntityRequested(this, new SpawnEntityEventArgs(entity));
}
protected internal virtual void OnBlockChange(Coordinates3D coordinates)
{
if (BlockChange != null) BlockChange(this, new BlockChangeEventArgs(coordinates));
}
}
}
| |
// 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.Data;
using System.Data.Common;
using System.Data.ProviderBase;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Runtime.Versioning;
using System.Diagnostics.CodeAnalysis;
// This class is the process wide dependency dispatcher. It contains all connection listeners for the entire process and
// receives notifications on those connections to dispatch to the corresponding AppDomain dispatcher to notify the
// appropriate dependencies.
internal class SqlDependencyProcessDispatcher : MarshalByRefObject
{
// Class to contain/store all relevant information about a connection that waits on the SSB queue.
private class SqlConnectionContainer
{
private SqlConnection _con;
private SqlCommand _com;
private SqlParameter _conversationGuidParam;
private SqlParameter _timeoutParam;
private SqlConnectionContainerHashHelper _hashHelper;
private string _queue;
private string _receiveQuery;
private string _beginConversationQuery;
private string _endConversationQuery;
private string _concatQuery;
private readonly int _defaultWaitforTimeout = 60000; // Waitfor(Receive) timeout (milleseconds)
private string _escapedQueueName;
private string _sprocName;
private string _dialogHandle;
private string _cachedServer;
private string _cachedDatabase;
private volatile bool _errorState = false;
private volatile bool _stop = false; // Can probably simplify this slightly - one bool instead of two.
private volatile bool _stopped = false;
private volatile bool _serviceQueueCreated = false;
private int _startCount = 0; // Each container class is called once per Start() - we refCount
// to track when we can dispose.
private Timer _retryTimer = null;
private Dictionary<string, int> _appDomainKeyHash = null; // AppDomainKey->Open RefCount
// Constructor
internal SqlConnectionContainer(SqlConnectionContainerHashHelper hashHelper, string appDomainKey, bool useDefaults)
{
bool setupCompleted = false;
try
{
_hashHelper = hashHelper;
string guid = null;
// If default, queue name is not present on hashHelper at this point - so we need to
// generate one and complete initialization.
if (useDefaults)
{
guid = Guid.NewGuid().ToString();
_queue = SQL.SqlNotificationServiceDefault + "-" + guid;
_hashHelper.ConnectionStringBuilder.ApplicationName = _queue; // Used by cleanup sproc.
}
else
{
_queue = _hashHelper.Queue;
}
// Always use ConnectionStringBuilder since in default case it is different from the
// connection string used in the hashHelper.
_con = new SqlConnection(_hashHelper.ConnectionStringBuilder.ConnectionString); // Create connection and open.
// Assert permission for this particular connection string since it differs from the user passed string
// which we have already demanded upon.
SqlConnectionString connStringObj = (SqlConnectionString)_con.ConnectionOptions;
_con.Open();
_cachedServer = _con.DataSource;
_escapedQueueName = SqlConnection.FixupDatabaseTransactionName(_queue); // Properly escape to prevent SQL Injection.
_appDomainKeyHash = new Dictionary<string, int>(); // Dictionary stores the Start/Stop refcount per AppDomain for this container.
_com = new SqlCommand()
{
Connection = _con,
// Determine if broker is enabled on current database.
CommandText = "select is_broker_enabled from sys.databases where database_id=db_id()"
};
if (!(bool)_com.ExecuteScalar())
{
throw SQL.SqlDependencyDatabaseBrokerDisabled();
}
_conversationGuidParam = new SqlParameter("@p1", SqlDbType.UniqueIdentifier);
_timeoutParam = new SqlParameter("@p2", SqlDbType.Int)
{
Value = 0 // Timeout set to 0 for initial sync query.
};
_com.Parameters.Add(_timeoutParam);
setupCompleted = true;
// connection with the server has been setup - from this point use TearDownAndDispose() in case of error
// Create standard query.
_receiveQuery = "WAITFOR(RECEIVE TOP (1) message_type_name, conversation_handle, cast(message_body AS XML) as message_body from " + _escapedQueueName + "), TIMEOUT @p2;";
// Create queue, service, sync query, and async query on user thread to ensure proper
// init prior to return.
if (useDefaults)
{ // Only create if user did not specify service & database.
_sprocName = SqlConnection.FixupDatabaseTransactionName(SQL.SqlNotificationStoredProcedureDefault + "-" + guid);
CreateQueueAndService(false); // Fail if we cannot create service, queue, etc.
}
else
{
// Continue query setup.
_com.CommandText = _receiveQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _receiveQuery;
}
IncrementStartCount(appDomainKey, out bool ignored);
// Query synchronously once to ensure everything is working correctly.
// We want the exception to occur on start to immediately inform caller.
SynchronouslyQueryServiceBrokerQueue();
_timeoutParam.Value = _defaultWaitforTimeout; // Sync successful, extend timeout to 60 seconds.
AsynchronouslyQueryServiceBrokerQueue();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
if (setupCompleted)
{
// Be sure to drop service & queue. This may fail if create service & queue failed.
// This method will not drop unless we created or service & queue ref-count is 0.
TearDownAndDispose();
}
else
{
// connection has not been fully setup yet - cannot use TearDownAndDispose();
// we have to dispose the command and the connection to avoid connection leaks (until GC collects them).
if (_com != null)
{
_com.Dispose();
_com = null;
}
if (_con != null)
{
_con.Dispose();
_con = null;
}
}
throw;
}
}
// Properties
internal string Database
{
get
{
if (_cachedDatabase == null)
{
_cachedDatabase = _con.Database;
}
return _cachedDatabase;
}
}
internal SqlConnectionContainerHashHelper HashHelper => _hashHelper;
internal bool InErrorState => _errorState;
internal string Queue => _queue;
internal string Server => _cachedServer;
// Methods
// This function is called by a ThreadPool thread as a result of an AppDomain calling
// SqlDependencyProcessDispatcher.QueueAppDomainUnload on AppDomain.Unload.
internal bool AppDomainUnload(string appDomainKey)
{
Debug.Assert(!string.IsNullOrEmpty(appDomainKey), "Unexpected empty appDomainKey!");
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Why is value 0 or less?");
bool ignored = false;
while (value > 0)
{
Debug.Assert(!_stopped, "We should not yet be stopped!");
Stop(appDomainKey, out ignored); // Stop will decrement value and remove if necessary from _appDomainKeyHash.
value--;
}
// Stop will remove key when decremented to 0 for this AppDomain, which should now be the case.
Debug.Assert(0 == value, "We did not reach 0 at end of loop in AppDomainUnload!");
Debug.Assert(!_appDomainKeyHash.ContainsKey(appDomainKey), "Key not removed after AppDomainUnload!");
}
}
return _stopped;
}
private void AsynchronouslyQueryServiceBrokerQueue()
{
AsyncCallback callback = new AsyncCallback(AsyncResultCallback);
_com.BeginExecuteReader(CommandBehavior.Default, callback, null); // NO LOCK NEEDED
}
private void AsyncResultCallback(IAsyncResult asyncResult)
{
try
{
using (SqlDataReader reader = _com.EndExecuteReader(asyncResult))
{
ProcessNotificationResults(reader);
}
// Successfull completion of query - no errors.
if (!_stop)
{
AsynchronouslyQueryServiceBrokerQueue(); // Requeue...
}
else
{
TearDownAndDispose();
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
// Let the waiting thread detect the error and exit (otherwise, the Stop call loops forever)
_errorState = true;
throw;
}
if (!_stop)
{ // Only assert if not in cancel path.
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
// Failure - likely due to cancelled command. Check _stop state.
if (_stop)
{
TearDownAndDispose();
}
else
{
_errorState = true;
Restart(null); // Error code path. Will Invalidate based on server if 1st retry fails.
}
}
}
private void CreateQueueAndService(bool restart)
{
SqlCommand com = new SqlCommand()
{
Connection = _con
};
SqlTransaction trans = null;
try
{
trans = _con.BeginTransaction(); // Since we cannot batch proc creation, start transaction.
com.Transaction = trans;
string nameLiteral = SqlServerEscapeHelper.MakeStringLiteral(_queue);
com.CommandText =
"CREATE PROCEDURE " + _sprocName + " AS"
+ " BEGIN"
+ " BEGIN TRANSACTION;"
+ " RECEIVE TOP(0) conversation_handle FROM " + _escapedQueueName + ";"
+ " IF (SELECT COUNT(*) FROM " + _escapedQueueName + " WHERE message_type_name = 'http://schemas.microsoft.com/SQL/ServiceBroker/DialogTimer') > 0"
+ " BEGIN"
+ " if ((SELECT COUNT(*) FROM sys.services WHERE name = " + nameLiteral + ") > 0)"
+ " DROP SERVICE " + _escapedQueueName + ";"
+ " if (OBJECT_ID(" + nameLiteral + ", 'SQ') IS NOT NULL)"
+ " DROP QUEUE " + _escapedQueueName + ";"
+ " DROP PROCEDURE " + _sprocName + ";" // Don't need conditional because this is self
+ " END"
+ " COMMIT TRANSACTION;"
+ " END";
if (!restart)
{
com.ExecuteNonQuery();
}
else
{ // Upon restart, be resilient to the user dropping queue, service, or procedure.
try
{
com.ExecuteNonQuery(); // Cannot add 'IF OBJECT_ID' to create procedure query - wrap and discard failure.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{ // Since the failure will result in a rollback, rollback our object.
if (null != trans)
{
trans.Rollback();
trans = null;
}
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace for now.
}
}
if (null == trans)
{ // Create a new transaction for next operations.
trans = _con.BeginTransaction();
com.Transaction = trans;
}
}
com.CommandText =
"IF OBJECT_ID(" + nameLiteral + ", 'SQ') IS NULL"
+ " BEGIN"
+ " CREATE QUEUE " + _escapedQueueName + " WITH ACTIVATION (PROCEDURE_NAME=" + _sprocName + ", MAX_QUEUE_READERS=1, EXECUTE AS OWNER);"
+ " END;"
+ " IF (SELECT COUNT(*) FROM sys.services WHERE NAME=" + nameLiteral + ") = 0"
+ " BEGIN"
+ " CREATE SERVICE " + _escapedQueueName + " ON QUEUE " + _escapedQueueName + " ([http://schemas.microsoft.com/SQL/Notifications/PostQueryNotification]);"
+ " IF (SELECT COUNT(*) FROM sys.database_principals WHERE name='sql_dependency_subscriber' AND type='R') <> 0"
+ " BEGIN"
+ " GRANT SEND ON SERVICE::" + _escapedQueueName + " TO sql_dependency_subscriber;"
+ " END; "
+ " END;"
+ " BEGIN DIALOG @dialog_handle FROM SERVICE " + _escapedQueueName + " TO SERVICE " + nameLiteral;
SqlParameter param = new SqlParameter()
{
ParameterName = "@dialog_handle",
DbType = DbType.Guid,
Direction = ParameterDirection.Output
};
com.Parameters.Add(param);
com.ExecuteNonQuery();
// Finish setting up queries and state. For re-start, we need to ensure we begin a new dialog above and reset
// our queries to use the new dialogHandle.
_dialogHandle = ((Guid)param.Value).ToString();
_beginConversationQuery = "BEGIN CONVERSATION TIMER ('" + _dialogHandle + "') TIMEOUT = 120; " + _receiveQuery;
_com.CommandText = _beginConversationQuery;
_endConversationQuery = "END CONVERSATION @p1; ";
_concatQuery = _endConversationQuery + _com.CommandText;
trans.Commit();
trans = null;
_serviceQueueCreated = true;
}
finally
{
if (null != trans)
{
try
{
trans.Rollback();
trans = null;
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
}
}
}
}
internal void IncrementStartCount(string appDomainKey, out bool appDomainStart)
{
appDomainStart = false; // Reset out param.
int result = Interlocked.Increment(ref _startCount); // Add to refCount.
// Dictionary used to track how many times start has been called per app domain.
// For each increment, add to count, and create entry if not present.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{
_appDomainKeyHash[appDomainKey] = _appDomainKeyHash[appDomainKey] + 1;
}
else
{
_appDomainKeyHash[appDomainKey] = 1;
appDomainStart = true;
}
}
}
private void ProcessNotificationResults(SqlDataReader reader)
{
Guid handle = Guid.Empty; // Conversation_handle. Always close this!
try
{
if (!_stop)
{
while (reader.Read())
{
string msgType = reader.GetString(0);
handle = reader.GetGuid(1);
// Only process QueryNotification messages.
if (string.Equals(msgType, "http://schemas.microsoft.com/SQL/Notifications/QueryNotification", StringComparison.OrdinalIgnoreCase))
{
SqlXml payload = reader.GetSqlXml(2);
if (null != payload)
{
SqlNotification notification = SqlNotificationParser.ProcessMessage(payload);
if (null != notification)
{
string key = notification.Key;
int index = key.IndexOf(';'); // Our format is simple: "AppDomainKey;commandHash"
if (index >= 0)
{ // Ensure ';' present.
string appDomainKey = key.Substring(0, index);
SqlDependencyPerAppDomainDispatcher dispatcher;
lock (s_staticInstance._sqlDependencyPerAppDomainDispatchers)
{
dispatcher = s_staticInstance._sqlDependencyPerAppDomainDispatchers[appDomainKey];
}
if (null != dispatcher)
{
try
{
dispatcher.InvalidateCommandID(notification); // CROSS APP-DOMAIN CALL!
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure. User event could throw exception.
}
}
else
{
Debug.Fail("Received notification but do not have an associated PerAppDomainDispatcher!");
}
}
else
{
Debug.Fail("Unexpected ID format received!");
}
}
else
{
Debug.Fail("Null notification returned from ProcessMessage!");
}
}
else
{
Debug.Fail("Null payload for QN notification type!");
}
}
else
{
handle = Guid.Empty;
}
}
}
}
finally
{
// Since we do not want to make a separate round trip just for the end conversation call, we need to
// batch it with the next command.
if (handle == Guid.Empty)
{ // This should only happen if failure occurred, or if non-QN format received.
_com.CommandText = _beginConversationQuery ?? _receiveQuery; // If we're doing the initial query, we won't have a conversation Guid to begin yet.
if (_com.Parameters.Count > 1)
{ // Remove conversation param since next execute is only query.
_com.Parameters.Remove(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 1, "Unexpected number of parameters!");
}
else
{
_com.CommandText = _concatQuery; // END query + WAITFOR RECEIVE query.
_conversationGuidParam.Value = handle; // Set value for conversation handle.
if (_com.Parameters.Count == 1)
{ // Add parameter if previous execute was only query.
_com.Parameters.Add(_conversationGuidParam);
}
Debug.Assert(_com.Parameters.Count == 2, "Unexpected number of parameters!");
}
}
}
private void Restart(object unused)
{ // Unused arg required by TimerCallback.
try
{
lock (this)
{
if (!_stop)
{ // Only execute if we are still in running state.
try
{
_con.Close();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard close failure, if it occurs. Only trace it.
}
}
}
// Rather than one long lock - take lock 3 times for shorter periods.
lock (this)
{
if (!_stop)
{
_con.Open();
}
}
lock (this)
{
if (!_stop)
{
if (_serviceQueueCreated)
{
bool failure = false;
try
{
CreateQueueAndService(true); // Ensure service, queue, etc is present, if we created it.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace for now.
failure = true;
}
if (failure)
{
// If we failed to re-created queue, service, sproc - invalidate!
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
}
}
}
lock (this)
{
if (!_stop)
{
_timeoutParam.Value = 0; // Reset timeout to zero - we do not want to block.
SynchronouslyQueryServiceBrokerQueue();
// If the above succeeds, we are back in success case - requeue for async call.
_timeoutParam.Value = _defaultWaitforTimeout; // If success, reset to default for re-queue.
AsynchronouslyQueryServiceBrokerQueue();
_errorState = false;
Timer retryTimer = _retryTimer;
if (retryTimer != null)
{
_retryTimer = null;
retryTimer.Dispose();
}
}
}
if (_stop)
{
TearDownAndDispose(); // Function will lock(this).
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e);
try
{
// If unexpected query or connection failure, invalidate all dependencies against this server.
// We may over-notify if only some of the connections to a particular database were affected,
// but this should not be frequent enough to be a concern.
// NOTE - we invalidate after failure first occurs and then retry fails. We will then continue
// to invalidate every time the retry fails.
s_staticInstance.Invalidate(Server,
new SqlNotification(SqlNotificationInfo.Error,
SqlNotificationSource.Client,
SqlNotificationType.Change,
null));
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard exception from Invalidate. User events can throw.
}
try
{
_con.Close();
}
catch (Exception f)
{
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard close failure, if it occurs. Only trace it.
}
if (!_stop)
{
// Create a timer to callback in one minute, retrying the call to Restart().
_retryTimer = new Timer(new TimerCallback(Restart), null, _defaultWaitforTimeout, Timeout.Infinite);
// We will retry this indefinitely, until success - or Stop();
}
}
}
internal bool Stop(string appDomainKey, out bool appDomainStop)
{
appDomainStop = false;
// Dictionary used to track how many times start has been called per app domain.
// For each decrement, subtract from count, and delete if we reach 0.
if (null != appDomainKey)
{
// If null, then this was called from SqlDependencyProcessDispatcher, we ignore appDomainKeyHash.
lock (_appDomainKeyHash)
{
if (_appDomainKeyHash.ContainsKey(appDomainKey))
{ // Do nothing if AppDomain did not call Start!
int value = _appDomainKeyHash[appDomainKey];
Debug.Assert(value > 0, "Unexpected count for appDomainKey");
if (value > 0)
{
_appDomainKeyHash[appDomainKey] = value - 1;
}
else
{
Debug.Fail("Unexpected AppDomainKey count in Stop()");
}
if (1 == value)
{ // Remove from dictionary if pre-decrement count was one.
_appDomainKeyHash.Remove(appDomainKey);
appDomainStop = true;
}
}
else
{
Debug.Fail("Unexpected state on Stop() - no AppDomainKey entry in hashtable!");
}
}
}
Debug.Assert(_startCount > 0, "About to decrement _startCount less than 0!");
int result = Interlocked.Decrement(ref _startCount);
if (0 == result)
{ // If we've reached refCount 0, destroy.
// Lock to ensure Cancel() complete prior to other thread calling TearDown.
lock (this)
{
try
{
// Race condition with executing thread - will throw if connection is closed due to failure.
// Rather than fighting the race condition, just call it and discard any potential failure.
_com.Cancel(); // Cancel the pending command. No-op if connection closed.
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
_stop = true;
}
// Wait until stopped and service & queue are dropped.
Stopwatch retryStopwatch = Stopwatch.StartNew();
while (true)
{
lock (this)
{
if (_stopped)
{
break;
}
// If we are in error state (_errorState is true), force a tear down.
// Likewise, if we have exceeded the maximum retry period (30 seconds) waiting for cleanup, force a tear down.
// In rare cases during app domain unload, the async cleanup performed by AsyncResultCallback
// may fail to execute TearDownAndDispose, leaving this method in an infinite loop.
// To avoid the infinite loop, we force the cleanup here after 30 seconds. Since we have reached
// refcount of 0, either this method call or the thread running AsyncResultCallback is responsible for calling
// TearDownAndDispose when transitioning to the _stopped state. Failing to call TearDownAndDispose means we leak
// the service broker objects created by this SqlDependency instance, so we make a best effort here to call
// TearDownAndDispose in the maximum retry period case as well as in the _errorState case.
if (_errorState || retryStopwatch.Elapsed.Seconds >= 30)
{
Timer retryTimer = _retryTimer;
_retryTimer = null;
if (retryTimer != null)
{
retryTimer.Dispose(); // Dispose timer - stop retry loop!
}
TearDownAndDispose(); // Will not hit server unless connection open!
break;
}
}
// Yield the thread since the stop has not yet completed.
// To avoid CPU spikes while waiting, yield and wait for at least one millisecond
Thread.Sleep(1);
}
}
Debug.Assert(0 <= _startCount, "Invalid start count state");
return _stopped;
}
private void SynchronouslyQueryServiceBrokerQueue()
{
using (SqlDataReader reader = _com.ExecuteReader())
{
ProcessNotificationResults(reader);
}
}
[SuppressMessage("Microsoft.Security", "CA2100:ReviewSqlQueriesForSecurityVulnerabilities")]
private void TearDownAndDispose()
{
lock (this)
{ // Lock to ensure Stop() (with Cancel()) complete prior to TearDown.
try
{
// Only execute if connection is still up and open.
if (ConnectionState.Closed != _con.State && ConnectionState.Broken != _con.State)
{
if (_com.Parameters.Count > 1)
{ // Need to close dialog before completing.
// In the normal case, the "End Conversation" query is executed before a
// receive query and upon return we will clear the state. However, unless
// a non notification query result is returned, we will not clear it. That
// means a query is generally always executing with an "end conversation" on
// the wire. Rather than synchronize for success of the other "end conversation",
// simply re-execute.
try
{
_com.CommandText = _endConversationQuery;
_com.Parameters.Remove(_timeoutParam);
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
if (_serviceQueueCreated && !_errorState)
{
/*
BEGIN TRANSACTION;
DROP SERVICE "+_escapedQueueName+";
DROP QUEUE "+_escapedQueueName+";
DROP PROCEDURE "+_sprocName+";
COMMIT TRANSACTION;
*/
_com.CommandText = "BEGIN TRANSACTION; DROP SERVICE " + _escapedQueueName + "; DROP QUEUE " + _escapedQueueName + "; DROP PROCEDURE " + _sprocName + "; COMMIT TRANSACTION;";
try
{
_com.ExecuteNonQuery();
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure.
}
}
}
}
finally
{
_stopped = true;
_con.Dispose(); // Close and dispose connection.
}
}
}
}
// Private class encapsulating the notification payload parsing logic.
private class SqlNotificationParser
{
[Flags]
private enum MessageAttributes
{
None = 0,
Type = 1,
Source = 2,
Info = 4,
All = Type + Source + Info,
}
// node names in the payload
private const string RootNode = "QueryNotification";
private const string MessageNode = "Message";
// attribute names (on the QueryNotification element)
private const string InfoAttribute = "info";
private const string SourceAttribute = "source";
private const string TypeAttribute = "type";
internal static SqlNotification ProcessMessage(SqlXml xmlMessage)
{
using (XmlReader xmlReader = xmlMessage.CreateReader())
{
string keyvalue = string.Empty;
MessageAttributes messageAttributes = MessageAttributes.None;
SqlNotificationType type = SqlNotificationType.Unknown;
SqlNotificationInfo info = SqlNotificationInfo.Unknown;
SqlNotificationSource source = SqlNotificationSource.Unknown;
string key = string.Empty;
// Move to main node, expecting "QueryNotification".
xmlReader.Read();
if ((XmlNodeType.Element == xmlReader.NodeType) &&
(RootNode == xmlReader.LocalName) &&
(3 <= xmlReader.AttributeCount))
{
// Loop until we've processed all the attributes.
while ((MessageAttributes.All != messageAttributes) && (xmlReader.MoveToNextAttribute()))
{
try
{
switch (xmlReader.LocalName)
{
case TypeAttribute:
try
{
SqlNotificationType temp = (SqlNotificationType)Enum.Parse(typeof(SqlNotificationType), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationType), temp))
{
type = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Type;
break;
case SourceAttribute:
try
{
SqlNotificationSource temp = (SqlNotificationSource)Enum.Parse(typeof(SqlNotificationSource), xmlReader.Value, true);
if (Enum.IsDefined(typeof(SqlNotificationSource), temp))
{
source = temp;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Source;
break;
case InfoAttribute:
try
{
string value = xmlReader.Value;
// 3 of the server info values do not match client values - map.
switch (value)
{
case "set options":
info = SqlNotificationInfo.Options;
break;
case "previous invalid":
info = SqlNotificationInfo.PreviousFire;
break;
case "query template limit":
info = SqlNotificationInfo.TemplateLimit;
break;
default:
SqlNotificationInfo temp = (SqlNotificationInfo)Enum.Parse(typeof(SqlNotificationInfo), value, true);
if (Enum.IsDefined(typeof(SqlNotificationInfo), temp))
{
info = temp;
}
break;
}
}
catch (Exception e)
{
if (!ADP.IsCatchableExceptionType(e))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, if it should occur.
}
messageAttributes |= MessageAttributes.Info;
break;
default:
break;
}
}
catch (ArgumentException e)
{
ADP.TraceExceptionWithoutRethrow(e); // Discard failure, but trace.
return null;
}
}
if (MessageAttributes.All != messageAttributes)
{
return null;
}
// Proceed to the "Message" node.
if (!xmlReader.Read())
{
return null;
}
// Verify state after Read().
if ((XmlNodeType.Element != xmlReader.NodeType) || (0 != string.Compare(xmlReader.LocalName, MessageNode, StringComparison.OrdinalIgnoreCase)))
{
return null;
}
// Proceed to the Text Node.
if (!xmlReader.Read())
{
return null;
}
// Verify state after Read().
if (xmlReader.NodeType != XmlNodeType.Text)
{
return null;
}
// Create a new XmlTextReader on the Message node value.
using (XmlTextReader xmlMessageReader = new XmlTextReader(xmlReader.Value, XmlNodeType.Element, null))
{
// Proceed to the Text Node.
if (!xmlMessageReader.Read())
{
return null;
}
if (xmlMessageReader.NodeType == XmlNodeType.Text)
{
key = xmlMessageReader.Value;
xmlMessageReader.Close();
}
else
{
return null;
}
}
return new SqlNotification(info, source, type, key);
}
else
{
return null; // failure
}
}
}
}
// Private class encapsulating the SqlConnectionContainer hash logic.
private class SqlConnectionContainerHashHelper
{
// For default, queue is computed in SqlConnectionContainer constructor, so queue will be empty and
// connection string will not include app name based on queue. As a result, the connection string
// builder will always contain up to date info, but _connectionString and _queue will not.
// As a result, we will not use _connectionStringBuilder as part of Equals or GetHashCode.
private DbConnectionPoolIdentity _identity;
private string _connectionString;
private string _queue;
private SqlConnectionStringBuilder _connectionStringBuilder; // Not to be used for comparison!
internal SqlConnectionContainerHashHelper(DbConnectionPoolIdentity identity, string connectionString,
string queue, SqlConnectionStringBuilder connectionStringBuilder)
{
_identity = identity;
_connectionString = connectionString;
_queue = queue;
_connectionStringBuilder = connectionStringBuilder;
}
// Not to be used for comparison!
internal SqlConnectionStringBuilder ConnectionStringBuilder => _connectionStringBuilder;
internal DbConnectionPoolIdentity Identity => _identity;
internal string Queue => _queue;
public override bool Equals(object value)
{
SqlConnectionContainerHashHelper temp = (SqlConnectionContainerHashHelper)value;
bool result = false;
// Ignore SqlConnectionStringBuilder, since it is present largely for debug purposes.
if (null == temp)
{ // If passed value null - false.
result = false;
}
else if (this == temp)
{ // If instances equal - true.
result = true;
}
else
{
if ((_identity != null && temp._identity == null) || // If XOR of null identities false - false.
(_identity == null && temp._identity != null))
{
result = false;
}
else if (_identity == null && temp._identity == null)
{
if (temp._connectionString == _connectionString &&
string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else
{
result = false;
}
}
else
{
if (temp._identity.Equals(_identity) &&
temp._connectionString == _connectionString &&
string.Equals(temp._queue, _queue, StringComparison.OrdinalIgnoreCase))
{
result = true;
}
else
{
result = false;
}
}
}
return result;
}
public override int GetHashCode()
{
int hashValue = 0;
if (null != _identity)
{
hashValue = _identity.GetHashCode();
}
if (null != _queue)
{
hashValue = unchecked(_connectionString.GetHashCode() + _queue.GetHashCode() + hashValue);
}
else
{
hashValue = unchecked(_connectionString.GetHashCode() + hashValue);
}
return hashValue;
}
}
// SqlDependencyProcessDispatcher static members
private static SqlDependencyProcessDispatcher s_staticInstance = new SqlDependencyProcessDispatcher(null);
// Dictionaries used as maps.
private Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer> _connectionContainers; // NT_ID+ConStr+Service->Container
private Dictionary<string, SqlDependencyPerAppDomainDispatcher> _sqlDependencyPerAppDomainDispatchers; // AppDomainKey->Callback
// Constructors
// Private constructor - only called by public constructor for static initialization.
private SqlDependencyProcessDispatcher(object dummyVariable)
{
Debug.Assert(null == s_staticInstance, "Real constructor called with static instance already created!");
_connectionContainers = new Dictionary<SqlConnectionContainerHashHelper, SqlConnectionContainer>();
_sqlDependencyPerAppDomainDispatchers = new Dictionary<string, SqlDependencyPerAppDomainDispatcher>();
}
// Constructor is only called by remoting.
// Required to be public, even on internal class, for Remoting infrastructure.
public SqlDependencyProcessDispatcher()
{
// Empty constructor and object - dummy to obtain singleton.
}
// Properties
internal static SqlDependencyProcessDispatcher SingletonProcessDispatcher => s_staticInstance;
// Various private methods
private static SqlConnectionContainerHashHelper GetHashHelper(
string connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out DbConnectionPoolIdentity identity,
out string user,
string queue)
{
// Force certain connection string properties to be used by SqlDependencyProcessDispatcher.
// This logic is done here to enable us to have the complete connection string now to be used
// for tracing as we flow through the logic.
connectionStringBuilder = new SqlConnectionStringBuilder(connectionString)
{
Pooling = false,
Enlist = false,
ConnectRetryCount = 0
};
if (null != queue)
{ // User provided!
connectionStringBuilder.ApplicationName = queue; // ApplicationName will be set to queue name.
}
if (connectionStringBuilder.IntegratedSecurity)
{
// Use existing identity infrastructure for error cases and proper hash value.
identity = DbConnectionPoolIdentity.GetCurrent();
user = null;
}
else
{
identity = null;
user = connectionStringBuilder.UserID;
}
return new SqlConnectionContainerHashHelper(identity, connectionStringBuilder.ConnectionString,
queue, connectionStringBuilder);
}
// Needed for remoting to prevent lifetime issues and default GC cleanup.
public override object InitializeLifetimeService()
{
return null;
}
private void Invalidate(string server, SqlNotification sqlNotification)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
lock (_sqlDependencyPerAppDomainDispatchers)
{
foreach (KeyValuePair<string, SqlDependencyPerAppDomainDispatcher> entry in _sqlDependencyPerAppDomainDispatchers)
{
SqlDependencyPerAppDomainDispatcher perAppDomainDispatcher = entry.Value;
try
{
perAppDomainDispatcher.InvalidateServer(server, sqlNotification);
}
catch (Exception f)
{
// Since we are looping over dependency dispatchers, do not allow one Invalidate
// that results in a throw prevent us from invalidating all dependencies
// related to this server.
// NOTE - SqlDependencyPerAppDomainDispatcher already wraps individual dependency invalidates
// with try/catch, but we should be careful and do the same here.
if (!ADP.IsCatchableExceptionType(f))
{
throw;
}
ADP.TraceExceptionWithoutRethrow(f); // Discard failure, but trace.
}
}
}
}
// Clean-up method initiated by other AppDomain.Unloads
// Individual AppDomains upon AppDomain.UnloadEvent will call this method.
internal void QueueAppDomainUnloading(string appDomainKey)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(AppDomainUnloading), appDomainKey);
}
// This method is only called by queued work-items from the method above.
private void AppDomainUnloading(object state)
{
string appDomainKey = (string)state;
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
lock (_connectionContainers)
{
List<SqlConnectionContainerHashHelper> containersToRemove = new List<SqlConnectionContainerHashHelper>();
foreach (KeyValuePair<SqlConnectionContainerHashHelper, SqlConnectionContainer> entry in _connectionContainers)
{
SqlConnectionContainer container = entry.Value;
if (container.AppDomainUnload(appDomainKey))
{ // Perhaps wrap in try catch.
containersToRemove.Add(container.HashHelper);
}
}
foreach (SqlConnectionContainerHashHelper hashHelper in containersToRemove)
{
_connectionContainers.Remove(hashHelper);
}
}
lock (_sqlDependencyPerAppDomainDispatchers)
{ // Remove from global Dictionary.
_sqlDependencyPerAppDomainDispatchers.Remove(appDomainKey);
}
}
// -------------
// Start methods
// -------------
internal bool StartWithDefault(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string service,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher,
out bool errorOccurred,
out bool appDomainStart)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
return Start(
connectionString,
out server,
out identity,
out user,
out database,
ref service,
appDomainKey,
dispatcher,
out errorOccurred,
out appDomainStart,
true);
}
internal bool Start(
string connectionString,
string queue,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
return Start(
connectionString,
out string dummyValue1,
out DbConnectionPoolIdentity dummyValue3,
out dummyValue1,
out dummyValue1,
ref queue,
appDomainKey,
dispatcher,
out bool dummyValue2,
out dummyValue2,
false);
}
private bool Start(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string queueService,
string appDomainKey,
SqlDependencyPerAppDomainDispatcher dispatcher,
out bool errorOccurred,
out bool appDomainStart,
bool useDefaults)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
server = null; // Reset out params.
identity = null;
user = null;
database = null;
errorOccurred = false;
appDomainStart = false;
lock (_sqlDependencyPerAppDomainDispatchers)
{
if (!_sqlDependencyPerAppDomainDispatchers.ContainsKey(appDomainKey))
{
_sqlDependencyPerAppDomainDispatchers[appDomainKey] = dispatcher;
}
}
SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out identity,
out user,
queueService);
bool started = false;
SqlConnectionContainer container = null;
lock (_connectionContainers)
{
if (!_connectionContainers.ContainsKey(hashHelper))
{
container = new SqlConnectionContainer(hashHelper, appDomainKey, useDefaults);
_connectionContainers.Add(hashHelper, container);
started = true;
appDomainStart = true;
}
else
{
container = _connectionContainers[hashHelper];
if (container.InErrorState)
{
errorOccurred = true; // Set outparam errorOccurred true so we invalidate on Start().
}
else
{
container.IncrementStartCount(appDomainKey, out appDomainStart);
}
}
}
if (useDefaults && !errorOccurred)
{ // Return server, database, and queue for use by SqlDependency.
server = container.Server;
database = container.Database;
queueService = container.Queue;
}
return started;
}
// Stop methods
internal bool Stop(
string connectionString,
out string server,
out DbConnectionPoolIdentity identity,
out string user,
out string database,
ref string queueService,
string appDomainKey,
out bool appDomainStop)
{
Debug.Assert(this == s_staticInstance, "Instance method called on non _staticInstance instance!");
server = null; // Reset out param.
identity = null;
user = null;
database = null;
appDomainStop = false;
SqlConnectionContainerHashHelper hashHelper = GetHashHelper(connectionString,
out SqlConnectionStringBuilder connectionStringBuilder,
out identity,
out user,
queueService);
bool stopped = false;
lock (_connectionContainers)
{
if (_connectionContainers.ContainsKey(hashHelper))
{
SqlConnectionContainer container = _connectionContainers[hashHelper];
server = container.Server; // Return server, database, and queue info for use by calling SqlDependency.
database = container.Database;
queueService = container.Queue;
if (container.Stop(appDomainKey, out appDomainStop))
{ // Stop can be blocking if refCount == 0 on container.
stopped = true;
_connectionContainers.Remove(hashHelper); // Remove from collection.
}
}
}
return stopped;
}
}
| |
// <copyright file="MultipleReadersTests.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
using System.Collections.Generic;
using System.Diagnostics.Metrics;
using OpenTelemetry.Tests;
using Xunit;
namespace OpenTelemetry.Metrics.Tests
{
public class MultipleReadersTests
{
[Theory]
[InlineData(AggregationTemporality.Delta, false)]
[InlineData(AggregationTemporality.Delta, true)]
[InlineData(AggregationTemporality.Cumulative, false)]
[InlineData(AggregationTemporality.Cumulative, true)]
public void SdkSupportsMultipleReaders(AggregationTemporality aggregationTemporality, bool hasViews)
{
var exportedItems1 = new List<Metric>();
var exportedItems2 = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{aggregationTemporality}.{hasViews}");
var counter = meter.CreateCounter<long>("counter");
int index = 0;
var values = new long[] { 100, 200, 300, 400 };
long GetValue() => values[index++];
var gauge = meter.CreateObservableGauge("gauge", () => GetValue());
int indexSum = 0;
var valuesSum = new long[] { 1000, 1200, 1300, 1400 };
long GetSum() => valuesSum[indexSum++];
var observableCounter = meter.CreateObservableCounter("obs-counter", () => GetSum());
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems1, metricReaderOptions =>
{
metricReaderOptions.Temporality = AggregationTemporality.Delta;
})
.AddInMemoryExporter(exportedItems2, metricReaderOptions =>
{
metricReaderOptions.Temporality = aggregationTemporality;
});
if (hasViews)
{
meterProviderBuilder.AddView("counter", "renamedCounter");
meterProviderBuilder.AddView("gauge", "renamedGauge");
meterProviderBuilder.AddView("obs-counter", "renamedObservableCounter");
}
using var meterProvider = meterProviderBuilder.Build();
counter.Add(10, new KeyValuePair<string, object>("key", "value"));
meterProvider.ForceFlush();
Assert.Equal(3, exportedItems1.Count);
Assert.Equal(3, exportedItems2.Count);
if (hasViews)
{
Assert.Equal("renamedCounter", exportedItems1[0].Name);
Assert.Equal("renamedCounter", exportedItems2[0].Name);
Assert.Equal("renamedGauge", exportedItems1[1].Name);
Assert.Equal("renamedGauge", exportedItems2[1].Name);
Assert.Equal("renamedObservableCounter", exportedItems1[2].Name);
Assert.Equal("renamedObservableCounter", exportedItems2[2].Name);
}
else
{
Assert.Equal("counter", exportedItems1[0].Name);
Assert.Equal("counter", exportedItems2[0].Name);
Assert.Equal("gauge", exportedItems1[1].Name);
Assert.Equal("gauge", exportedItems2[1].Name);
Assert.Equal("obs-counter", exportedItems1[2].Name);
Assert.Equal("obs-counter", exportedItems2[2].Name);
}
// Check value exported for Counter
this.AssertLongSumValueForMetric(exportedItems1[0], 10);
this.AssertLongSumValueForMetric(exportedItems2[0], 10);
// Check value exported for Gauge
this.AssertLongSumValueForMetric(exportedItems1[1], 100);
this.AssertLongSumValueForMetric(exportedItems2[1], 200);
// Check value exported for ObservableCounter
this.AssertLongSumValueForMetric(exportedItems1[2], 1000);
if (aggregationTemporality == AggregationTemporality.Delta)
{
this.AssertLongSumValueForMetric(exportedItems2[2], 1200);
}
else
{
this.AssertLongSumValueForMetric(exportedItems2[2], 1200);
}
exportedItems1.Clear();
exportedItems2.Clear();
counter.Add(15, new KeyValuePair<string, object>("key", "value"));
meterProvider.ForceFlush();
Assert.Equal(3, exportedItems1.Count);
Assert.Equal(3, exportedItems2.Count);
// Check value exported for Counter
this.AssertLongSumValueForMetric(exportedItems1[0], 15);
if (aggregationTemporality == AggregationTemporality.Delta)
{
this.AssertLongSumValueForMetric(exportedItems2[0], 15);
}
else
{
this.AssertLongSumValueForMetric(exportedItems2[0], 25);
}
// Check value exported for Gauge
this.AssertLongSumValueForMetric(exportedItems1[1], 300);
this.AssertLongSumValueForMetric(exportedItems2[1], 400);
// Check value exported for ObservableCounter
this.AssertLongSumValueForMetric(exportedItems1[2], 300);
if (aggregationTemporality == AggregationTemporality.Delta)
{
this.AssertLongSumValueForMetric(exportedItems2[2], 200);
}
else
{
this.AssertLongSumValueForMetric(exportedItems2[2], 1400);
}
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void ObservableInstrumentCallbacksInvokedForEachReaders(bool hasViews)
{
var exportedItems1 = new List<Metric>();
var exportedItems2 = new List<Metric>();
using var meter = new Meter($"{Utils.GetCurrentMethodName()}.{hasViews}");
int callbackInvocationCount = 0;
var gauge = meter.CreateObservableGauge("gauge", () =>
{
callbackInvocationCount++;
return 10 * callbackInvocationCount;
});
var meterProviderBuilder = Sdk.CreateMeterProviderBuilder()
.AddMeter(meter.Name)
.AddInMemoryExporter(exportedItems1)
.AddInMemoryExporter(exportedItems2);
if (hasViews)
{
meterProviderBuilder.AddView("gauge", "renamedGauge");
}
using var meterProvider = meterProviderBuilder.Build();
meterProvider.ForceFlush();
// VALIDATE
Assert.Equal(2, callbackInvocationCount);
Assert.Single(exportedItems1);
Assert.Single(exportedItems2);
if (hasViews)
{
Assert.Equal("renamedGauge", exportedItems1[0].Name);
Assert.Equal("renamedGauge", exportedItems2[0].Name);
}
else
{
Assert.Equal("gauge", exportedItems1[0].Name);
Assert.Equal("gauge", exportedItems2[0].Name);
}
}
private void AssertLongSumValueForMetric(Metric metric, long value)
{
var metricPoints = metric.GetMetricPoints();
var metricPointsEnumerator = metricPoints.GetEnumerator();
Assert.True(metricPointsEnumerator.MoveNext()); // One MetricPoint is emitted for the Metric
ref readonly var metricPointForFirstExport = ref metricPointsEnumerator.Current;
if (metric.MetricType.IsSum())
{
Assert.Equal(value, metricPointForFirstExport.GetSumLong());
}
else
{
Assert.Equal(value, metricPointForFirstExport.GetGaugeLastValueLong());
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Buffers;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace System.IO.Compression.Tests
{
public class BrotliEncoderTests : CompressionTestBase
{
protected override string CompressedTestFile(string uncompressedPath) => Path.Combine("BrotliTestData", Path.GetFileName(uncompressedPath) + ".br");
[Fact]
public void InvalidQuality()
{
Assert.Throws<ArgumentOutOfRangeException>("quality", () => new BrotliEncoder(-1, 11));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => new BrotliEncoder(12, 11));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, -1, 13));
Assert.Throws<ArgumentOutOfRangeException>("quality", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 12, 13));
}
[Fact]
public void InvalidWindow()
{
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, -1));
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, 9));
Assert.Throws<ArgumentOutOfRangeException>("window", () => new BrotliEncoder(10, 25));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, -1));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, 9));
Assert.Throws<ArgumentOutOfRangeException>("window", () => BrotliEncoder.TryCompress(new ReadOnlySpan<byte>(), new Span<byte>(), out int bytesWritten, 6, 25));
}
[Fact]
public void GetMaxCompressedSize_Basic()
{
Assert.Throws<ArgumentOutOfRangeException>("length", () => BrotliEncoder.GetMaxCompressedLength(-1));
Assert.Throws<ArgumentOutOfRangeException>("length", () => BrotliEncoder.GetMaxCompressedLength(2147483133));
Assert.InRange(BrotliEncoder.GetMaxCompressedLength(2147483132), 0, int.MaxValue);
Assert.Equal(1, BrotliEncoder.GetMaxCompressedLength(0));
}
[Fact]
public void GetMaxCompressedSize()
{
string uncompressedFile = UncompressedTestFile();
string compressedFile = CompressedTestFile(uncompressedFile);
int maxCompressedSize = BrotliEncoder.GetMaxCompressedLength((int)new FileInfo(uncompressedFile).Length);
int actualCompressedSize = (int)new FileInfo(compressedFile).Length;
Assert.True(maxCompressedSize >= actualCompressedSize, $"MaxCompressedSize: {maxCompressedSize}, ActualCompressedSize: {actualCompressedSize}");
}
/// <summary>
/// Test to ensure that when given an empty Destination span, the decoder will consume no input and write no output.
/// </summary>
[Fact]
public void Decompress_WithEmptyDestination()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] destinationBytes = new byte[0];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.False(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress completed successfully but should have failed due to too short of a destination array");
Assert.Equal(0, bytesWritten);
BrotliDecoder decoder;
var result = decoder.Decompress(source, destination, out int bytesConsumed, out bytesWritten);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
}
/// <summary>
/// Test to ensure that when given an empty source span, the decoder will consume no input and write no output
/// </summary>
[Fact]
public void Decompress_WithEmptySource()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = new byte[0];
byte[] destinationBytes = new byte[100000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.False(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress completed successfully but should have failed due to too short of a source array");
Assert.Equal(0, bytesWritten);
BrotliDecoder decoder;
var result = decoder.Decompress(source, destination, out int bytesConsumed, out bytesWritten);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.NeedMoreData, result);
}
/// <summary>
/// Test to ensure that when given an empty Destination span, the encoder consume no input and write no output
/// </summary>
[Fact]
public void Compress_WithEmptyDestination()
{
string testFile = UncompressedTestFile();
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] empty = new byte[0];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(correctUncompressedBytes);
Span<byte> destination = new Span<byte>(empty);
Assert.False(BrotliEncoder.TryCompress(source, destination, out int bytesWritten), "TryCompress completed successfully but should have failed due to too short of a destination array");
Assert.Equal(0, bytesWritten);
BrotliEncoder encoder;
var result = encoder.Compress(source, destination, out int bytesConsumed, out bytesWritten, false);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
result = encoder.Compress(source, destination, out bytesConsumed, out bytesWritten, isFinalBlock: true);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.DestinationTooSmall, result);
}
/// <summary>
/// Test to ensure that when given an empty source span, the decoder will consume no input and write no output (until the finishing block)
/// </summary>
[Fact]
public void Compress_WithEmptySource()
{
string testFile = UncompressedTestFile();
byte[] sourceBytes = new byte[0];
byte[] destinationBytes = new byte[100000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(sourceBytes);
Span<byte> destination = new Span<byte>(destinationBytes);
Assert.True(BrotliEncoder.TryCompress(source, destination, out int bytesWritten));
// The only byte written should be the Brotli end of stream byte which varies based on the window/quality
Assert.Equal(1, bytesWritten);
BrotliEncoder encoder;
var result = encoder.Compress(source, destination, out int bytesConsumed, out bytesWritten, false);
Assert.Equal(0, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.Done, result);
result = encoder.Compress(source, destination, out bytesConsumed, out bytesWritten, isFinalBlock: true);
Assert.Equal(1, bytesWritten);
Assert.Equal(0, bytesConsumed);
Assert.Equal(OperationStatus.Done, result);
}
/// <summary>
/// Test that the decoder can handle partial chunks of flushed encoded data sent from the BrotliEncoder
/// </summary>
[Fact]
public void RoundTrip_Chunks()
{
int chunkSize = 100;
int totalSize = 20000;
BrotliEncoder encoder;
BrotliDecoder decoder;
for (int i = 0; i < totalSize; i += chunkSize)
{
byte[] uncompressed = new byte[chunkSize];
new Random().NextBytes(uncompressed);
byte[] compressed = new byte[BrotliEncoder.GetMaxCompressedLength(chunkSize)];
byte[] decompressed = new byte[chunkSize];
var uncompressedSpan = new ReadOnlySpan<byte>(uncompressed);
var compressedSpan = new Span<byte>(compressed);
var decompressedSpan = new Span<byte>(decompressed);
int totalWrittenThisIteration = 0;
var compress = encoder.Compress(uncompressedSpan, compressedSpan, out int bytesConsumed, out int bytesWritten, isFinalBlock: false);
totalWrittenThisIteration += bytesWritten;
compress = encoder.Flush(compressedSpan.Slice(bytesWritten), out bytesWritten);
totalWrittenThisIteration += bytesWritten;
var res = decoder.Decompress(compressedSpan.Slice(0, totalWrittenThisIteration), decompressedSpan, out int decompressbytesConsumed, out int decompressbytesWritten);
Assert.Equal(totalWrittenThisIteration, decompressbytesConsumed);
Assert.Equal(bytesConsumed, decompressbytesWritten);
Assert.Equal<byte>(uncompressed, decompressedSpan.ToArray());
}
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadFully(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length + 10000];
ReadOnlySpan<byte> source = new ReadOnlySpan<byte>(compressedBytes);
Span<byte> destination = new Span<byte>(actualUncompressedBytes);
Assert.True(BrotliDecoder.TryDecompress(source, destination, out int bytesWritten), "TryDecompress did not complete successfully");
Assert.Equal(correctUncompressedBytes.Length, bytesWritten);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes.AsSpan(0, correctUncompressedBytes.Length).ToArray());
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadWithState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Decompress_WithState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void ReadWithoutState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = File.ReadAllBytes(CompressedTestFile(testFile));
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Decompress_WithoutState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteFully(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
Span<byte> destination = new Span<byte>(compressedBytes);
Assert.True(BrotliEncoder.TryCompress(correctUncompressedBytes, destination, out int bytesWritten));
Assert.True(BrotliDecoder.TryDecompress(destination, actualUncompressedBytes, out bytesWritten));
Assert.Equal(correctUncompressedBytes.Length, bytesWritten);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes.AsSpan(0, correctUncompressedBytes.Length).ToArray());
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteWithState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Compress_WithState(correctUncompressedBytes, compressedBytes);
Decompress_WithState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteWithoutState(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = new byte[BrotliEncoder.GetMaxCompressedLength(correctUncompressedBytes.Length)];
byte[] actualUncompressedBytes = new byte[correctUncompressedBytes.Length];
Compress_WithoutState(correctUncompressedBytes, compressedBytes);
Decompress_WithoutState(compressedBytes, actualUncompressedBytes);
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[Theory]
[OuterLoop("Full set of UncompressedTestFiles takes around 15s to run")]
[MemberData(nameof(UncompressedTestFiles))]
public void WriteStream(string testFile)
{
byte[] correctUncompressedBytes = File.ReadAllBytes(testFile);
byte[] compressedBytes = Compress_Stream(correctUncompressedBytes, CompressionLevel.Optimal).ToArray();
byte[] actualUncompressedBytes = Decompress_Stream(compressedBytes).ToArray();
Assert.Equal<byte>(correctUncompressedBytes, actualUncompressedBytes);
}
[OuterLoop("Full set of tests takes seconds to run")]
[Theory]
[InlineData(1, 0x400001, false)]
[InlineData(1, 0x400001, true)]
[InlineData(4, 0x800000, false)]
[InlineData(4, 0x800000, true)]
[InlineData(53, 12345, false)]
[InlineData(53, 12345, true)]
public static async Task Roundtrip_VaryingSizeReadsAndLengths_Success(int readSize, int totalLength, bool useAsync)
{
byte[] correctUncompressedBytes = Enumerable.Range(0, totalLength).Select(i => (byte)i).ToArray();
byte[] compressedBytes = Compress_Stream(correctUncompressedBytes, CompressionLevel.Fastest).ToArray();
byte[] actualBytes = new byte[correctUncompressedBytes.Length];
using (var s = new BrotliStream(new MemoryStream(compressedBytes), CompressionMode.Decompress))
{
int totalRead = 0;
while (totalRead < actualBytes.Length)
{
int numRead = useAsync ?
await s.ReadAsync(actualBytes, totalRead, Math.Min(readSize, actualBytes.Length - totalRead)) :
s.Read(actualBytes, totalRead, Math.Min(readSize, actualBytes.Length - totalRead));
totalRead += numRead;
}
Assert.Equal<byte>(correctUncompressedBytes, actualBytes);
}
}
[Theory]
[InlineData(1000, CompressionLevel.Fastest)]
[InlineData(1000, CompressionLevel.Optimal)]
[InlineData(1000, CompressionLevel.NoCompression)]
public static void Roundtrip_WriteByte_ReadByte_Success(int totalLength, CompressionLevel level)
{
byte[] correctUncompressedBytes = Enumerable.Range(0, totalLength).Select(i => (byte)i).ToArray();
byte[] compressedBytes;
using (var ms = new MemoryStream())
{
var bs = new BrotliStream(ms, level);
foreach (byte b in correctUncompressedBytes)
{
bs.WriteByte(b);
}
bs.Dispose();
compressedBytes = ms.ToArray();
}
byte[] decompressedBytes = new byte[correctUncompressedBytes.Length];
using (var ms = new MemoryStream(compressedBytes))
using (var bs = new BrotliStream(ms, CompressionMode.Decompress))
{
for (int i = 0; i < decompressedBytes.Length; i++)
{
int b = bs.ReadByte();
Assert.InRange(b, 0, 255);
decompressedBytes[i] = (byte)b;
}
Assert.Equal(-1, bs.ReadByte());
Assert.Equal(-1, bs.ReadByte());
}
Assert.Equal<byte>(correctUncompressedBytes, decompressedBytes);
}
public static void Compress_WithState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliEncoder encoder;
while (!input.IsEmpty && !output.IsEmpty)
{
encoder.Compress(input, output, out int bytesConsumed, out int written, isFinalBlock: false);
input = input.Slice(bytesConsumed);
output = output.Slice(written);
}
encoder.Compress(ReadOnlySpan<byte>.Empty, output, out int bytesConsumed2, out int bytesWritten, isFinalBlock: true);
}
public static void Decompress_WithState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliDecoder decoder;
while (!input.IsEmpty && !output.IsEmpty)
{
decoder.Decompress(input, output, out int bytesConsumed, out int written);
input = input.Slice(bytesConsumed);
output = output.Slice(written);
}
}
public static void Compress_WithoutState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliEncoder.TryCompress(input, output, out int bytesWritten);
}
public static void Decompress_WithoutState(ReadOnlySpan<byte> input, Span<byte> output)
{
BrotliDecoder.TryDecompress(input, output, out int bytesWritten);
}
public static MemoryStream Compress_Stream(ReadOnlySpan<byte> input, CompressionLevel compressionLevel)
{
using (var inputStream = new MemoryStream(input.ToArray()))
{
var outputStream = new MemoryStream();
var compressor = new BrotliStream(outputStream, compressionLevel, true);
inputStream.CopyTo(compressor);
compressor.Dispose();
return outputStream;
}
}
public static MemoryStream Decompress_Stream(ReadOnlySpan<byte> input)
{
using (var inputStream = new MemoryStream(input.ToArray()))
{
var outputStream = new MemoryStream();
var decompressor = new BrotliStream(inputStream, CompressionMode.Decompress, true);
decompressor.CopyTo(outputStream);
decompressor.Dispose();
return outputStream;
}
}
}
}
| |
//
// This file was generated by the BinaryNotes compiler.
// See http://bnotes.sourceforge.net
// Any modifications to this file will be lost upon recompilation of the source ASN.1.
//
using System.Collections.Generic;
using GSF.ASN1;
using GSF.ASN1.Attributes;
using GSF.ASN1.Coders;
namespace GSF.MMS.Model
{
[ASN1PreparedElement]
[ASN1Sequence(Name = "Journal_Entry_instance", IsSet = false)]
public class Journal_Entry_instance : IASN1PreparedElement
{
private static readonly IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(Journal_Entry_instance));
private ApplicationReference clientApplication_;
private byte[] entry_;
private EventTransitionRecordSequenceType eventTransitionRecord_;
private bool eventTransitionRecord_present;
private InformationTypeEnumType informationType_;
private ICollection<JournalVariablesSequenceType> journalVariables_;
private bool journalVariables_present;
private Journal_instance journal_;
private long orderOfReceipt_;
private MMS255String textComment_;
private bool textComment_present;
private TimeOfDay timeStamp_;
[ASN1Element(Name = "journal", IsOptional = false, HasTag = true, Tag = 0, HasDefaultValue = false)]
public Journal_instance Journal
{
get
{
return journal_;
}
set
{
journal_ = value;
}
}
[ASN1OctetString(Name = "")]
[ASN1Element(Name = "entry", IsOptional = false, HasTag = true, Tag = 1, HasDefaultValue = false)]
public byte[] Entry
{
get
{
return entry_;
}
set
{
entry_ = value;
}
}
[ASN1Element(Name = "clientApplication", IsOptional = false, HasTag = true, Tag = 2, HasDefaultValue = false)]
public ApplicationReference ClientApplication
{
get
{
return clientApplication_;
}
set
{
clientApplication_ = value;
}
}
[ASN1Element(Name = "timeStamp", IsOptional = false, HasTag = true, Tag = 3, HasDefaultValue = false)]
public TimeOfDay TimeStamp
{
get
{
return timeStamp_;
}
set
{
timeStamp_ = value;
}
}
[ASN1Integer(Name = "")]
[ASN1Element(Name = "orderOfReceipt", IsOptional = false, HasTag = true, Tag = 4, HasDefaultValue = false)]
public long OrderOfReceipt
{
get
{
return orderOfReceipt_;
}
set
{
orderOfReceipt_ = value;
}
}
[ASN1Element(Name = "informationType", IsOptional = false, HasTag = true, Tag = 5, HasDefaultValue = false)]
public InformationTypeEnumType InformationType
{
get
{
return informationType_;
}
set
{
informationType_ = value;
}
}
[ASN1Element(Name = "textComment", IsOptional = true, HasTag = true, Tag = 6, HasDefaultValue = false)]
public MMS255String TextComment
{
get
{
return textComment_;
}
set
{
textComment_ = value;
textComment_present = true;
}
}
[ASN1Element(Name = "eventTransitionRecord", IsOptional = true, HasTag = true, Tag = 7, HasDefaultValue = false)]
public EventTransitionRecordSequenceType EventTransitionRecord
{
get
{
return eventTransitionRecord_;
}
set
{
eventTransitionRecord_ = value;
eventTransitionRecord_present = true;
}
}
[ASN1SequenceOf(Name = "journalVariables", IsSetOf = false)]
[ASN1Element(Name = "journalVariables", IsOptional = true, HasTag = true, Tag = 10, HasDefaultValue = false)]
public ICollection<JournalVariablesSequenceType> JournalVariables
{
get
{
return journalVariables_;
}
set
{
journalVariables_ = value;
journalVariables_present = true;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
public bool isTextCommentPresent()
{
return textComment_present;
}
public bool isEventTransitionRecordPresent()
{
return eventTransitionRecord_present;
}
public bool isJournalVariablesPresent()
{
return journalVariables_present;
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "eventTransitionRecord", IsSet = false)]
public class EventTransitionRecordSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(EventTransitionRecordSequenceType));
private EC_State currentState_;
private ObjectName name_;
[ASN1Element(Name = "name", IsOptional = false, HasTag = true, Tag = 8, HasDefaultValue = false)]
public ObjectName Name
{
get
{
return name_;
}
set
{
name_ = value;
}
}
[ASN1Element(Name = "currentState", IsOptional = false, HasTag = true, Tag = 9, HasDefaultValue = false)]
public EC_State CurrentState
{
get
{
return currentState_;
}
set
{
currentState_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
[ASN1PreparedElement]
[ASN1Enum(Name = "InformationTypeEnumType")]
public class InformationTypeEnumType : IASN1PreparedElement
{
public enum EnumType
{
[ASN1EnumItem(Name = "annotation", HasTag = true, Tag = 0)]
annotation,
[ASN1EnumItem(Name = "event-data", HasTag = true, Tag = 1)]
event_data,
[ASN1EnumItem(Name = "data", HasTag = true, Tag = 2)]
data,
}
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(InformationTypeEnumType));
private EnumType val;
public EnumType Value
{
get
{
return val;
}
set
{
val = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
[ASN1PreparedElement]
[ASN1Sequence(Name = "journalVariables", IsSet = false)]
public class JournalVariablesSequenceType : IASN1PreparedElement
{
private static IASN1PreparedElementData preparedData = CoderFactory.getInstance().newPreparedElementData(typeof(JournalVariablesSequenceType));
private Data valueSpecification_;
private MMS255String variableTag_;
[ASN1Element(Name = "variableTag", IsOptional = false, HasTag = true, Tag = 11, HasDefaultValue = false)]
public MMS255String VariableTag
{
get
{
return variableTag_;
}
set
{
variableTag_ = value;
}
}
[ASN1Element(Name = "valueSpecification", IsOptional = false, HasTag = true, Tag = 12, HasDefaultValue = false)]
public Data ValueSpecification
{
get
{
return valueSpecification_;
}
set
{
valueSpecification_ = value;
}
}
public void initWithDefaults()
{
}
public IASN1PreparedElementData PreparedData
{
get
{
return preparedData;
}
}
}
}
}
| |
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Threading;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using ModernHttpClient.CoreFoundation;
using ModernHttpClient.Foundation;
#if UNIFIED
using Foundation;
using Security;
#else
using MonoTouch.Foundation;
using MonoTouch.Security;
using System.Globalization;
#endif
namespace ModernHttpClient
{
class InflightOperation
{
public HttpRequestMessage Request { get; set; }
public TaskCompletionSource<HttpResponseMessage> FutureResponse { get; set; }
public ProgressDelegate Progress { get; set; }
public ByteArrayListStream ResponseBody { get; set; }
public CancellationToken CancellationToken { get; set; }
public bool IsCompleted { get; set; }
}
public class NativeMessageHandler : HttpClientHandler
{
readonly NSUrlSession session;
readonly Dictionary<NSUrlSessionTask, InflightOperation> inflightRequests =
new Dictionary<NSUrlSessionTask, InflightOperation>();
readonly Dictionary<HttpRequestMessage, ProgressDelegate> registeredProgressCallbacks =
new Dictionary<HttpRequestMessage, ProgressDelegate>();
readonly Dictionary<string, string> headerSeparators =
new Dictionary<string, string>(){
{"User-Agent", " "}
};
readonly bool throwOnCaptiveNetwork;
readonly bool customSSLVerification;
public bool DisableCaching { get; set; }
public TimeSpan? Timeout { get; set; }
public NativeMessageHandler(): this(false, false) { }
public NativeMessageHandler(bool throwOnCaptiveNetwork, bool customSSLVerification, NativeCookieHandler cookieHandler = null, SslProtocol? minimumSSLProtocol = null)
{
var configuration = NSUrlSessionConfiguration.DefaultSessionConfiguration;
// System.Net.ServicePointManager.SecurityProtocol provides a mechanism for specifying supported protocol types
// for System.Net. Since iOS only provides an API for a minimum and maximum protocol we are not able to port
// this configuration directly and instead use the specified minimum value when one is specified.
if (minimumSSLProtocol.HasValue) {
configuration.TLSMinimumSupportedProtocol = minimumSSLProtocol.Value;
}
session = NSUrlSession.FromConfiguration(
NSUrlSessionConfiguration.DefaultSessionConfiguration,
new DataTaskDelegate(this), null);
this.throwOnCaptiveNetwork = throwOnCaptiveNetwork;
this.customSSLVerification = customSSLVerification;
this.DisableCaching = false;
}
string getHeaderSeparator(string name)
{
if (headerSeparators.ContainsKey(name)) {
return headerSeparators[name];
}
return ",";
}
public void RegisterForProgress(HttpRequestMessage request, ProgressDelegate callback)
{
if (callback == null && registeredProgressCallbacks.ContainsKey(request)) {
registeredProgressCallbacks.Remove(request);
return;
}
registeredProgressCallbacks[request] = callback;
}
ProgressDelegate getAndRemoveCallbackFromRegister(HttpRequestMessage request)
{
ProgressDelegate emptyDelegate = delegate { };
lock (registeredProgressCallbacks) {
if (!registeredProgressCallbacks.ContainsKey(request)) return emptyDelegate;
var callback = registeredProgressCallbacks[request];
registeredProgressCallbacks.Remove(request);
return callback;
}
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var headers = request.Headers as IEnumerable<KeyValuePair<string, IEnumerable<string>>>;
var ms = new MemoryStream();
if (request.Content != null) {
await request.Content.CopyToAsync(ms).ConfigureAwait(false);
headers = headers.Union(request.Content.Headers).ToArray();
}
var rq = new NSMutableUrlRequest() {
AllowsCellularAccess = true,
Body = NSData.FromArray(ms.ToArray()),
CachePolicy = (!this.DisableCaching ? NSUrlRequestCachePolicy.UseProtocolCachePolicy : NSUrlRequestCachePolicy.ReloadIgnoringCacheData),
Headers = headers.Aggregate(new NSMutableDictionary(), (acc, x) => {
acc.Add(new NSString(x.Key), new NSString(String.Join(getHeaderSeparator(x.Key), x.Value)));
return acc;
}),
HttpMethod = request.Method.ToString().ToUpperInvariant(),
Url = NSUrl.FromString(request.RequestUri.AbsoluteUri),
};
if (Timeout != null)
rq.TimeoutInterval = Timeout.Value.TotalSeconds;
var op = session.CreateDataTask(rq);
cancellationToken.ThrowIfCancellationRequested();
var ret = new TaskCompletionSource<HttpResponseMessage>();
cancellationToken.Register(() => ret.TrySetCanceled());
lock (inflightRequests) {
inflightRequests[op] = new InflightOperation() {
FutureResponse = ret,
Request = request,
Progress = getAndRemoveCallbackFromRegister(request),
ResponseBody = new ByteArrayListStream(),
CancellationToken = cancellationToken,
};
}
op.Resume();
return await ret.Task.ConfigureAwait(false);
}
class DataTaskDelegate : NSUrlSessionDataDelegate
{
NativeMessageHandler This { get; set; }
public DataTaskDelegate(NativeMessageHandler that)
{
this.This = that;
}
public override void DidReceiveResponse(NSUrlSession session, NSUrlSessionDataTask dataTask, NSUrlResponse response, Action<NSUrlSessionResponseDisposition> completionHandler)
{
var data = getResponseForTask(dataTask);
try {
if (data.CancellationToken.IsCancellationRequested) {
dataTask.Cancel();
}
var resp = (NSHttpUrlResponse)response;
var req = data.Request;
if (This.throwOnCaptiveNetwork && req.RequestUri.Host != resp.Url.Host) {
throw new CaptiveNetworkException(req.RequestUri, new Uri(resp.Url.ToString()));
}
var content = new CancellableStreamContent(data.ResponseBody, () => {
if (!data.IsCompleted) {
dataTask.Cancel();
}
data.IsCompleted = true;
data.ResponseBody.SetException(new OperationCanceledException());
});
content.Progress = data.Progress;
// NB: The double cast is because of a Xamarin compiler bug
int status = (int)resp.StatusCode;
var ret = new HttpResponseMessage((HttpStatusCode)status) {
Content = content,
RequestMessage = data.Request,
};
ret.RequestMessage.RequestUri = new Uri(resp.Url.AbsoluteString);
foreach(var v in resp.AllHeaderFields) {
// NB: Cocoa trolling us so hard by giving us back dummy
// dictionary entries
if (v.Key == null || v.Value == null) continue;
ret.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString());
ret.Content.Headers.TryAddWithoutValidation(v.Key.ToString(), v.Value.ToString());
}
data.FutureResponse.TrySetResult(ret);
} catch (Exception ex) {
data.FutureResponse.TrySetException(ex);
}
completionHandler(NSUrlSessionResponseDisposition.Allow);
}
public override void WillCacheResponse (NSUrlSession session, NSUrlSessionDataTask dataTask,
NSCachedUrlResponse proposedResponse, Action<NSCachedUrlResponse> completionHandler)
{
completionHandler (This.DisableCaching ? null : proposedResponse);
}
public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
{
var data = getResponseForTask(task);
data.IsCompleted = true;
if (error != null) {
var ex = createExceptionForNSError(error);
// Pass the exception to the response
data.FutureResponse.TrySetException(ex);
data.ResponseBody.SetException(ex);
return;
}
data.ResponseBody.Complete();
lock (This.inflightRequests) {
This.inflightRequests.Remove(task);
}
}
public override void DidReceiveData (NSUrlSession session, NSUrlSessionDataTask dataTask, NSData byteData)
{
var data = getResponseForTask(dataTask);
var bytes = byteData.ToArray();
// NB: If we're cancelled, we still might have one more chunk
// of data that attempts to be delivered
if (data.IsCompleted) return;
data.ResponseBody.AddByteArray(bytes);
}
InflightOperation getResponseForTask(NSUrlSessionTask task)
{
lock (This.inflightRequests) {
return This.inflightRequests[task];
}
}
static readonly Regex cnRegex = new Regex(@"CN\s*=\s*([^,]*)", RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.Singleline);
public override void DidReceiveChallenge(NSUrlSession session, NSUrlSessionTask task, NSUrlAuthenticationChallenge challenge, Action<NSUrlSessionAuthChallengeDisposition, NSUrlCredential> completionHandler)
{
if (challenge.ProtectionSpace.AuthenticationMethod == NSUrlProtectionSpace.AuthenticationMethodNTLM) {
NetworkCredential credentialsToUse;
if (This.Credentials != null) {
if (This.Credentials is NetworkCredential) {
credentialsToUse = (NetworkCredential)This.Credentials;
} else {
var uri = this.getResponseForTask(task).Request.RequestUri;
credentialsToUse = This.Credentials.GetCredential(uri, "NTLM");
}
var credential = new NSUrlCredential(credentialsToUse.UserName, credentialsToUse.Password, NSUrlCredentialPersistence.ForSession);
completionHandler(NSUrlSessionAuthChallengeDisposition.UseCredential, credential);
}
return;
}
if (!This.customSSLVerification) {
goto doDefault;
}
if (challenge.ProtectionSpace.AuthenticationMethod != "NSURLAuthenticationMethodServerTrust") {
goto doDefault;
}
if (ServicePointManager.ServerCertificateValidationCallback == null) {
goto doDefault;
}
// Convert Mono Certificates to .NET certificates and build cert
// chain from root certificate
var serverCertChain = challenge.ProtectionSpace.ServerSecTrust;
var chain = new X509Chain();
X509Certificate2 root = null;
var errors = SslPolicyErrors.None;
if (serverCertChain == null || serverCertChain.Count == 0) {
errors = SslPolicyErrors.RemoteCertificateNotAvailable;
goto sslErrorVerify;
}
if (serverCertChain.Count == 1) {
errors = SslPolicyErrors.RemoteCertificateChainErrors;
goto sslErrorVerify;
}
var netCerts = Enumerable.Range(0, serverCertChain.Count)
.Select(x => serverCertChain[x].ToX509Certificate2())
.ToArray();
for (int i = 1; i < netCerts.Length; i++) {
chain.ChainPolicy.ExtraStore.Add(netCerts[i]);
}
root = netCerts[0];
chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EntireChain;
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
chain.ChainPolicy.UrlRetrievalTimeout = new TimeSpan(0, 1, 0);
chain.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority;
if (!chain.Build(root)) {
errors = SslPolicyErrors.RemoteCertificateChainErrors;
goto sslErrorVerify;
}
var subject = root.Subject;
var subjectCn = cnRegex.Match(subject).Groups[1].Value;
if (String.IsNullOrWhiteSpace(subjectCn) || !Utility.MatchHostnameToPattern(task.CurrentRequest.Url.Host, subjectCn)) {
errors = SslPolicyErrors.RemoteCertificateNameMismatch;
goto sslErrorVerify;
}
sslErrorVerify:
var hostname = task.CurrentRequest.Url.Host;
bool result = ServicePointManager.ServerCertificateValidationCallback(hostname, root, chain, errors);
if (result) {
completionHandler(
NSUrlSessionAuthChallengeDisposition.UseCredential,
NSUrlCredential.FromTrust(challenge.ProtectionSpace.ServerSecTrust));
} else {
completionHandler(NSUrlSessionAuthChallengeDisposition.CancelAuthenticationChallenge, null);
}
return;
doDefault:
completionHandler(NSUrlSessionAuthChallengeDisposition.PerformDefaultHandling, challenge.ProposedCredential);
return;
}
public override void WillPerformHttpRedirection(NSUrlSession session, NSUrlSessionTask task, NSHttpUrlResponse response, NSUrlRequest newRequest, Action<NSUrlRequest> completionHandler)
{
NSUrlRequest nextRequest = (This.AllowAutoRedirect ? newRequest : null);
completionHandler(nextRequest);
}
static Exception createExceptionForNSError(NSError error)
{
var ret = default(Exception);
var webExceptionStatus = WebExceptionStatus.UnknownError;
var innerException = new NSErrorException(error);
if (error.Domain == NSError.NSUrlErrorDomain) {
// Convert the error code into an enumeration (this is future
// proof, rather than just casting integer)
NSUrlErrorExtended urlError;
if (!Enum.TryParse<NSUrlErrorExtended>(error.Code.ToString(), out urlError)) urlError = NSUrlErrorExtended.Unknown;
// Parse the enum into a web exception status or exception. Some
// of these values don't necessarily translate completely to
// what WebExceptionStatus supports, so made some best guesses
// here. For your reading pleasure, compare these:
//
// Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/index.html#//apple_ref/doc/constant_group/URL_Loading_System_Error_Codes
// .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
switch (urlError) {
case NSUrlErrorExtended.Cancelled:
case NSUrlErrorExtended.UserCancelledAuthentication:
// No more processing is required so just return.
return new OperationCanceledException(error.LocalizedDescription, innerException);
case NSUrlErrorExtended.BadURL:
case NSUrlErrorExtended.UnsupportedURL:
case NSUrlErrorExtended.CannotConnectToHost:
case NSUrlErrorExtended.ResourceUnavailable:
case NSUrlErrorExtended.NotConnectedToInternet:
case NSUrlErrorExtended.UserAuthenticationRequired:
case NSUrlErrorExtended.InternationalRoamingOff:
case NSUrlErrorExtended.CallIsActive:
case NSUrlErrorExtended.DataNotAllowed:
webExceptionStatus = WebExceptionStatus.ConnectFailure;
break;
case NSUrlErrorExtended.TimedOut:
webExceptionStatus = WebExceptionStatus.Timeout;
break;
case NSUrlErrorExtended.CannotFindHost:
case NSUrlErrorExtended.DNSLookupFailed:
webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
break;
case NSUrlErrorExtended.DataLengthExceedsMaximum:
webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
break;
case NSUrlErrorExtended.NetworkConnectionLost:
webExceptionStatus = WebExceptionStatus.ConnectionClosed;
break;
case NSUrlErrorExtended.HTTPTooManyRedirects:
case NSUrlErrorExtended.RedirectToNonExistentLocation:
webExceptionStatus = WebExceptionStatus.ProtocolError;
break;
case NSUrlErrorExtended.RequestBodyStreamExhausted:
webExceptionStatus = WebExceptionStatus.SendFailure;
break;
case NSUrlErrorExtended.BadServerResponse:
case NSUrlErrorExtended.ZeroByteResource:
case NSUrlErrorExtended.CannotDecodeRawData:
case NSUrlErrorExtended.CannotDecodeContentData:
case NSUrlErrorExtended.CannotParseResponse:
case NSUrlErrorExtended.FileDoesNotExist:
case NSUrlErrorExtended.FileIsDirectory:
case NSUrlErrorExtended.NoPermissionsToReadFile:
case NSUrlErrorExtended.CannotLoadFromNetwork:
case NSUrlErrorExtended.CannotCreateFile:
case NSUrlErrorExtended.CannotOpenFile:
case NSUrlErrorExtended.CannotCloseFile:
case NSUrlErrorExtended.CannotWriteToFile:
case NSUrlErrorExtended.CannotRemoveFile:
case NSUrlErrorExtended.CannotMoveFile:
case NSUrlErrorExtended.DownloadDecodingFailedMidStream:
case NSUrlErrorExtended.DownloadDecodingFailedToComplete:
webExceptionStatus = WebExceptionStatus.ReceiveFailure;
break;
case NSUrlErrorExtended.SecureConnectionFailed:
webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
break;
case NSUrlErrorExtended.ServerCertificateHasBadDate:
case NSUrlErrorExtended.ServerCertificateHasUnknownRoot:
case NSUrlErrorExtended.ServerCertificateNotYetValid:
case NSUrlErrorExtended.ServerCertificateUntrusted:
case NSUrlErrorExtended.ClientCertificateRejected:
case NSUrlErrorExtended.ClientCertificateRequired:
webExceptionStatus = WebExceptionStatus.TrustFailure;
break;
}
goto done;
}
if (error.Domain == CFNetworkError.ErrorDomain) {
// Convert the error code into an enumeration (this is future
// proof, rather than just casting integer)
CFNetworkErrors networkError;
if (!Enum.TryParse<CFNetworkErrors>(error.Code.ToString(), out networkError)) {
networkError = CFNetworkErrors.CFHostErrorUnknown;
}
// Parse the enum into a web exception status or exception. Some
// of these values don't necessarily translate completely to
// what WebExceptionStatus supports, so made some best guesses
// here. For your reading pleasure, compare these:
//
// Apple docs: https://developer.apple.com/library/ios/documentation/Networking/Reference/CFNetworkErrors/#//apple_ref/c/tdef/CFNetworkErrors
// .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
switch (networkError) {
case CFNetworkErrors.CFURLErrorCancelled:
case CFNetworkErrors.CFURLErrorUserCancelledAuthentication:
case CFNetworkErrors.CFNetServiceErrorCancel:
// No more processing is required so just return.
return new OperationCanceledException(error.LocalizedDescription, innerException);
case CFNetworkErrors.CFSOCKS5ErrorBadCredentials:
case CFNetworkErrors.CFSOCKS5ErrorUnsupportedNegotiationMethod:
case CFNetworkErrors.CFSOCKS5ErrorNoAcceptableMethod:
case CFNetworkErrors.CFErrorHttpAuthenticationTypeUnsupported:
case CFNetworkErrors.CFErrorHttpBadCredentials:
case CFNetworkErrors.CFErrorHttpBadURL:
case CFNetworkErrors.CFURLErrorBadURL:
case CFNetworkErrors.CFURLErrorUnsupportedURL:
case CFNetworkErrors.CFURLErrorCannotConnectToHost:
case CFNetworkErrors.CFURLErrorResourceUnavailable:
case CFNetworkErrors.CFURLErrorNotConnectedToInternet:
case CFNetworkErrors.CFURLErrorUserAuthenticationRequired:
case CFNetworkErrors.CFURLErrorInternationalRoamingOff:
case CFNetworkErrors.CFURLErrorCallIsActive:
case CFNetworkErrors.CFURLErrorDataNotAllowed:
webExceptionStatus = WebExceptionStatus.ConnectFailure;
break;
case CFNetworkErrors.CFURLErrorTimedOut:
case CFNetworkErrors.CFNetServiceErrorTimeout:
webExceptionStatus = WebExceptionStatus.Timeout;
break;
case CFNetworkErrors.CFHostErrorHostNotFound:
case CFNetworkErrors.CFURLErrorCannotFindHost:
case CFNetworkErrors.CFURLErrorDNSLookupFailed:
case CFNetworkErrors.CFNetServiceErrorDNSServiceFailure:
webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
break;
case CFNetworkErrors.CFURLErrorDataLengthExceedsMaximum:
webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
break;
case CFNetworkErrors.CFErrorHttpConnectionLost:
case CFNetworkErrors.CFURLErrorNetworkConnectionLost:
webExceptionStatus = WebExceptionStatus.ConnectionClosed;
break;
case CFNetworkErrors.CFErrorHttpRedirectionLoopDetected:
case CFNetworkErrors.CFURLErrorHTTPTooManyRedirects:
case CFNetworkErrors.CFURLErrorRedirectToNonExistentLocation:
webExceptionStatus = WebExceptionStatus.ProtocolError;
break;
case CFNetworkErrors.CFSOCKSErrorUnknownClientVersion:
case CFNetworkErrors.CFSOCKSErrorUnsupportedServerVersion:
case CFNetworkErrors.CFErrorHttpParseFailure:
case CFNetworkErrors.CFURLErrorRequestBodyStreamExhausted:
webExceptionStatus = WebExceptionStatus.SendFailure;
break;
case CFNetworkErrors.CFSOCKS4ErrorRequestFailed:
case CFNetworkErrors.CFSOCKS4ErrorIdentdFailed:
case CFNetworkErrors.CFSOCKS4ErrorIdConflict:
case CFNetworkErrors.CFSOCKS4ErrorUnknownStatusCode:
case CFNetworkErrors.CFSOCKS5ErrorBadState:
case CFNetworkErrors.CFSOCKS5ErrorBadResponseAddr:
case CFNetworkErrors.CFURLErrorBadServerResponse:
case CFNetworkErrors.CFURLErrorZeroByteResource:
case CFNetworkErrors.CFURLErrorCannotDecodeRawData:
case CFNetworkErrors.CFURLErrorCannotDecodeContentData:
case CFNetworkErrors.CFURLErrorCannotParseResponse:
case CFNetworkErrors.CFURLErrorFileDoesNotExist:
case CFNetworkErrors.CFURLErrorFileIsDirectory:
case CFNetworkErrors.CFURLErrorNoPermissionsToReadFile:
case CFNetworkErrors.CFURLErrorCannotLoadFromNetwork:
case CFNetworkErrors.CFURLErrorCannotCreateFile:
case CFNetworkErrors.CFURLErrorCannotOpenFile:
case CFNetworkErrors.CFURLErrorCannotCloseFile:
case CFNetworkErrors.CFURLErrorCannotWriteToFile:
case CFNetworkErrors.CFURLErrorCannotRemoveFile:
case CFNetworkErrors.CFURLErrorCannotMoveFile:
case CFNetworkErrors.CFURLErrorDownloadDecodingFailedMidStream:
case CFNetworkErrors.CFURLErrorDownloadDecodingFailedToComplete:
case CFNetworkErrors.CFHTTPCookieCannotParseCookieFile:
case CFNetworkErrors.CFNetServiceErrorUnknown:
case CFNetworkErrors.CFNetServiceErrorCollision:
case CFNetworkErrors.CFNetServiceErrorNotFound:
case CFNetworkErrors.CFNetServiceErrorInProgress:
case CFNetworkErrors.CFNetServiceErrorBadArgument:
case CFNetworkErrors.CFNetServiceErrorInvalid:
webExceptionStatus = WebExceptionStatus.ReceiveFailure;
break;
case CFNetworkErrors.CFURLErrorServerCertificateHasBadDate:
case CFNetworkErrors.CFURLErrorServerCertificateUntrusted:
case CFNetworkErrors.CFURLErrorServerCertificateHasUnknownRoot:
case CFNetworkErrors.CFURLErrorServerCertificateNotYetValid:
case CFNetworkErrors.CFURLErrorClientCertificateRejected:
case CFNetworkErrors.CFURLErrorClientCertificateRequired:
webExceptionStatus = WebExceptionStatus.TrustFailure;
break;
case CFNetworkErrors.CFURLErrorSecureConnectionFailed:
webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
break;
case CFNetworkErrors.CFErrorHttpProxyConnectionFailure:
case CFNetworkErrors.CFErrorHttpBadProxyCredentials:
case CFNetworkErrors.CFErrorPACFileError:
case CFNetworkErrors.CFErrorPACFileAuth:
case CFNetworkErrors.CFErrorHttpsProxyConnectionFailure:
case CFNetworkErrors.CFStreamErrorHttpsProxyFailureUnexpectedResponseToConnectMethod:
webExceptionStatus = WebExceptionStatus.RequestProhibitedByProxy;
break;
}
goto done;
}
done:
// Always create a WebException so that it can be handled by the client.
ret = new WebException(error.LocalizedDescription, innerException, webExceptionStatus, response: null);
return ret;
}
}
}
class ByteArrayListStream : Stream
{
Exception exception;
IDisposable lockRelease;
readonly AsyncLock readStreamLock;
readonly List<byte[]> bytes = new List<byte[]>();
bool isCompleted;
long maxLength = 0;
long position = 0;
int offsetInCurrentBuffer = 0;
public ByteArrayListStream()
{
// Initially we have nothing to read so Reads should be parked
readStreamLock = AsyncLock.CreateLocked(out lockRelease);
}
public override bool CanRead { get { return true; } }
public override bool CanWrite { get { return false; } }
public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); }
public override void WriteByte(byte value) { throw new NotSupportedException(); }
public override bool CanSeek { get { return false; } }
public override bool CanTimeout { get { return false; } }
public override void SetLength(long value) { throw new NotSupportedException(); }
public override void Flush() { }
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override long Position {
get { return position; }
set {
throw new NotSupportedException();
}
}
public override long Length {
get {
return maxLength;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.ReadAsync(buffer, offset, count).Result;
}
/* OMG THIS CODE IS COMPLICATED
*
* Here's the core idea. We want to create a ReadAsync function that
* reads from our list of byte arrays **until it gets to the end of
* our current list**.
*
* If we're not there yet, we keep returning data, serializing access
* to the underlying position pointer (i.e. we definitely don't want
* people concurrently moving position along). If we try to read past
* the end, we return the section of data we could read and complete
* it.
*
* Here's where the tricky part comes in. If we're not Completed (i.e.
* the caller still wants to add more byte arrays in the future) and
* we're at the end of the current stream, we want to *block* the read
* (not blocking, but async blocking whatever you know what I mean),
* until somebody adds another byte[] to chew through, or if someone
* rewinds the position.
*
* If we *are* completed, we should return zero to simply complete the
* read, signalling we're at the end of the stream */
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
retry:
int bytesRead = 0;
int buffersToRemove = 0;
if (isCompleted && position == maxLength) {
return 0;
}
if (exception != null) throw exception;
using (await readStreamLock.LockAsync().ConfigureAwait(false)) {
lock (bytes) {
foreach (var buf in bytes) {
cancellationToken.ThrowIfCancellationRequested();
if (exception != null) throw exception;
int toCopy = Math.Min(count, buf.Length - offsetInCurrentBuffer);
Array.ConstrainedCopy(buf, offsetInCurrentBuffer, buffer, offset, toCopy);
count -= toCopy;
offset += toCopy;
bytesRead += toCopy;
offsetInCurrentBuffer += toCopy;
if (offsetInCurrentBuffer >= buf.Length) {
offsetInCurrentBuffer = 0;
buffersToRemove++;
}
if (count <= 0) break;
}
// Remove buffers that we read in this operation
bytes.RemoveRange(0, buffersToRemove);
position += bytesRead;
}
}
// If we're at the end of the stream and it's not done, prepare
// the next read to park itself unless AddByteArray or Complete
// posts
if (position >= maxLength && !isCompleted) {
lockRelease = await readStreamLock.LockAsync().ConfigureAwait(false);
}
if (bytesRead == 0 && !isCompleted) {
// NB: There are certain race conditions where we somehow acquire
// the lock yet are at the end of the stream, and we're not completed
// yet. We should try again so that we can get stuck in the lock.
goto retry;
}
if (cancellationToken.IsCancellationRequested) {
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
cancellationToken.ThrowIfCancellationRequested();
}
if (exception != null) {
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
throw exception;
}
if (isCompleted && position < maxLength) {
// NB: This solves a rare deadlock
//
// 1. ReadAsync called (waiting for lock release)
// 2. AddByteArray called (release lock)
// 3. AddByteArray called (release lock)
// 4. Complete called (release lock the last time)
// 5. ReadAsync called (lock released at this point, the method completed successfully)
// 6. ReadAsync called (deadlock on LockAsync(), because the lock is block, and there is no way to release it)
//
// Current condition forces the lock to be released in the end of 5th point
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
return bytesRead;
}
public void AddByteArray(byte[] arrayToAdd)
{
if (exception != null) throw exception;
if (isCompleted) throw new InvalidOperationException("Can't add byte arrays once Complete() is called");
lock (bytes) {
maxLength += arrayToAdd.Length;
bytes.Add(arrayToAdd);
//Console.WriteLine("Added a new byte array, {0}: max = {1}", arrayToAdd.Length, maxLength);
}
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
public void Complete()
{
isCompleted = true;
Interlocked.Exchange(ref lockRelease, EmptyDisposable.Instance).Dispose();
}
public void SetException(Exception ex)
{
exception = ex;
Complete();
}
}
sealed class CancellableStreamContent : ProgressStreamContent
{
Action onDispose;
public CancellableStreamContent(Stream source, Action onDispose) : base(source, CancellationToken.None)
{
this.onDispose = onDispose;
}
protected override void Dispose(bool disposing)
{
var disp = Interlocked.Exchange(ref onDispose, null);
if (disp != null) disp();
// EVIL HAX: We have to let at least one ReadAsync of the underlying
// stream fail with OperationCancelledException before we can dispose
// the base, or else the exception coming out of the ReadAsync will
// be an ObjectDisposedException from an internal MemoryStream. This isn't
// the Ideal way to fix this, but #yolo.
Task.Run(() => base.Dispose(disposing));
}
}
sealed class EmptyDisposable : IDisposable
{
static readonly IDisposable instance = new EmptyDisposable();
public static IDisposable Instance { get { return instance; } }
EmptyDisposable() { }
public void Dispose() { }
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Threading;
using Mono.Collections.Generic;
namespace Mono.Cecil.Cil {
public sealed class MethodBody : IVariableDefinitionProvider {
readonly internal MethodDefinition method;
internal ParameterDefinition this_parameter;
internal int max_stack_size;
internal int code_size;
internal bool init_locals;
internal MetadataToken local_var_token;
internal Collection<Instruction> instructions;
internal Collection<ExceptionHandler> exceptions;
internal Collection<VariableDefinition> variables;
Scope scope;
public MethodDefinition Method {
get { return method; }
}
public int MaxStackSize {
get { return max_stack_size; }
set { max_stack_size = value; }
}
public int CodeSize {
get { return code_size; }
}
public bool InitLocals {
get { return init_locals; }
set { init_locals = value; }
}
public MetadataToken LocalVarToken {
get { return local_var_token; }
set { local_var_token = value; }
}
public Collection<Instruction> Instructions {
get { return instructions ?? (instructions = new InstructionCollection ()); }
}
public bool HasExceptionHandlers {
get { return !exceptions.IsNullOrEmpty (); }
}
public Collection<ExceptionHandler> ExceptionHandlers {
get { return exceptions ?? (exceptions = new Collection<ExceptionHandler> ()); }
}
public bool HasVariables {
get { return !variables.IsNullOrEmpty (); }
}
public Collection<VariableDefinition> Variables {
get { return variables ?? (variables = new VariableDefinitionCollection ()); }
}
public Scope Scope {
get { return scope; }
set { scope = value; }
}
public ParameterDefinition ThisParameter {
get {
if (method == null || method.DeclaringType == null)
throw new NotSupportedException ();
if (!method.HasThis)
return null;
if (this_parameter == null)
Interlocked.CompareExchange (ref this_parameter, CreateThisParameter (method), null);
return this_parameter;
}
}
static ParameterDefinition CreateThisParameter (MethodDefinition method)
{
var declaring_type = method.DeclaringType;
var type = declaring_type.IsValueType || declaring_type.IsPrimitive
? new PointerType (declaring_type)
: declaring_type as TypeReference;
return new ParameterDefinition (type, method);
}
public MethodBody (MethodDefinition method)
{
this.method = method;
}
public ILProcessor GetILProcessor ()
{
return new ILProcessor (this);
}
}
public interface IVariableDefinitionProvider {
bool HasVariables { get; }
Collection<VariableDefinition> Variables { get; }
}
class VariableDefinitionCollection : Collection<VariableDefinition> {
internal VariableDefinitionCollection ()
{
}
internal VariableDefinitionCollection (int capacity)
: base (capacity)
{
}
protected override void OnAdd (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnInsert (VariableDefinition item, int index)
{
item.index = index;
for (int i = index; i < size; i++)
items [i].index = i + 1;
}
protected override void OnSet (VariableDefinition item, int index)
{
item.index = index;
}
protected override void OnRemove (VariableDefinition item, int index)
{
item.index = -1;
for (int i = index + 1; i < size; i++)
items [i].index = i - 1;
}
}
class InstructionCollection : Collection<Instruction> {
internal InstructionCollection ()
{
}
internal InstructionCollection (int capacity)
: base (capacity)
{
}
protected override void OnAdd (Instruction item, int index)
{
if (index == 0)
return;
var previous = items [index - 1];
previous.next = item;
item.previous = previous;
}
protected override void OnInsert (Instruction item, int index)
{
if (size == 0)
return;
var current = items [index];
if (current == null) {
var last = items [index - 1];
last.next = item;
item.previous = last;
return;
}
var previous = current.previous;
if (previous != null) {
previous.next = item;
item.previous = previous;
}
current.previous = item;
item.next = current;
}
protected override void OnSet (Instruction item, int index)
{
var current = items [index];
item.previous = current.previous;
item.next = current.next;
current.previous = null;
current.next = null;
}
protected override void OnRemove (Instruction item, int index)
{
var previous = item.previous;
if (previous != null)
previous.next = item.next;
var next = item.next;
if (next != null)
next.previous = item.previous;
item.previous = null;
item.next = null;
}
}
}
| |
using System.Collections.Generic;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Security;
namespace Nop.Services.Security
{
/// <summary>
/// Standard permission provider
/// </summary>
public partial class StandardPermissionProvider : IPermissionProvider
{
//admin area permissions
public static readonly PermissionRecord AccessAdminPanel = new PermissionRecord { Name = "Access admin area", SystemName = "AccessAdminPanel", Category = "Standard" };
public static readonly PermissionRecord AllowCustomerImpersonation = new PermissionRecord { Name = "Admin area. Allow Customer Impersonation", SystemName = "AllowCustomerImpersonation", Category = "Customers" };
public static readonly PermissionRecord ManageProducts = new PermissionRecord { Name = "Admin area. Manage Products", SystemName = "ManageProducts", Category = "Catalog" };
public static readonly PermissionRecord ManageCategories = new PermissionRecord { Name = "Admin area. Manage Categories", SystemName = "ManageCategories", Category = "Catalog" };
public static readonly PermissionRecord ManageManufacturers = new PermissionRecord { Name = "Admin area. Manage Manufacturers", SystemName = "ManageManufacturers", Category = "Catalog" };
public static readonly PermissionRecord ManageProductReviews = new PermissionRecord { Name = "Admin area. Manage Product Reviews", SystemName = "ManageProductReviews", Category = "Catalog" };
public static readonly PermissionRecord ManageProductTags = new PermissionRecord { Name = "Admin area. Manage Product Tags", SystemName = "ManageProductTags", Category = "Catalog" };
public static readonly PermissionRecord ManageAttributes = new PermissionRecord { Name = "Admin area. Manage Attributes", SystemName = "ManageAttributes", Category = "Catalog" };
public static readonly PermissionRecord ManageCustomers = new PermissionRecord { Name = "Admin area. Manage Customers", SystemName = "ManageCustomers", Category = "Customers" };
public static readonly PermissionRecord ManageVendors = new PermissionRecord { Name = "Admin area. Manage Vendors", SystemName = "ManageVendors", Category = "Customers" };
public static readonly PermissionRecord ManageCurrentCarts = new PermissionRecord { Name = "Admin area. Manage Current Carts", SystemName = "ManageCurrentCarts", Category = "Orders" };
public static readonly PermissionRecord ManageOrders = new PermissionRecord { Name = "Admin area. Manage Orders", SystemName = "ManageOrders", Category = "Orders" };
public static readonly PermissionRecord ManageRecurringPayments = new PermissionRecord { Name = "Admin area. Manage Recurring Payments", SystemName = "ManageRecurringPayments", Category = "Orders" };
public static readonly PermissionRecord ManageGiftCards = new PermissionRecord { Name = "Admin area. Manage Gift Cards", SystemName = "ManageGiftCards", Category = "Orders" };
public static readonly PermissionRecord ManageReturnRequests = new PermissionRecord { Name = "Admin area. Manage Return Requests", SystemName = "ManageReturnRequests", Category = "Orders" };
public static readonly PermissionRecord OrderCountryReport = new PermissionRecord { Name = "Admin area. Access order country report", SystemName = "OrderCountryReport", Category = "Orders" };
public static readonly PermissionRecord ManageAffiliates = new PermissionRecord { Name = "Admin area. Manage Affiliates", SystemName = "ManageAffiliates", Category = "Promo" };
public static readonly PermissionRecord ManageCampaigns = new PermissionRecord { Name = "Admin area. Manage Campaigns", SystemName = "ManageCampaigns", Category = "Promo" };
public static readonly PermissionRecord ManageDiscounts = new PermissionRecord { Name = "Admin area. Manage Discounts", SystemName = "ManageDiscounts", Category = "Promo" };
public static readonly PermissionRecord ManageNewsletterSubscribers = new PermissionRecord { Name = "Admin area. Manage Newsletter Subscribers", SystemName = "ManageNewsletterSubscribers", Category = "Promo" };
public static readonly PermissionRecord ManagePolls = new PermissionRecord { Name = "Admin area. Manage Polls", SystemName = "ManagePolls", Category = "Content Management" };
public static readonly PermissionRecord ManageNews = new PermissionRecord { Name = "Admin area. Manage News", SystemName = "ManageNews", Category = "Content Management" };
public static readonly PermissionRecord ManageBlog = new PermissionRecord { Name = "Admin area. Manage Blog", SystemName = "ManageBlog", Category = "Content Management" };
public static readonly PermissionRecord ManageWidgets = new PermissionRecord { Name = "Admin area. Manage Widgets", SystemName = "ManageWidgets", Category = "Content Management" };
public static readonly PermissionRecord ManageTopics = new PermissionRecord { Name = "Admin area. Manage Topics", SystemName = "ManageTopics", Category = "Content Management" };
public static readonly PermissionRecord ManageForums = new PermissionRecord { Name = "Admin area. Manage Forums", SystemName = "ManageForums", Category = "Content Management" };
public static readonly PermissionRecord ManageMessageTemplates = new PermissionRecord { Name = "Admin area. Manage Message Templates", SystemName = "ManageMessageTemplates", Category = "Content Management" };
public static readonly PermissionRecord ManageCountries = new PermissionRecord { Name = "Admin area. Manage Countries", SystemName = "ManageCountries", Category = "Configuration" };
public static readonly PermissionRecord ManageLanguages = new PermissionRecord { Name = "Admin area. Manage Languages", SystemName = "ManageLanguages", Category = "Configuration" };
public static readonly PermissionRecord ManageSettings = new PermissionRecord { Name = "Admin area. Manage Settings", SystemName = "ManageSettings", Category = "Configuration" };
public static readonly PermissionRecord ManagePaymentMethods = new PermissionRecord { Name = "Admin area. Manage Payment Methods", SystemName = "ManagePaymentMethods", Category = "Configuration" };
public static readonly PermissionRecord ManageExternalAuthenticationMethods = new PermissionRecord { Name = "Admin area. Manage External Authentication Methods", SystemName = "ManageExternalAuthenticationMethods", Category = "Configuration" };
public static readonly PermissionRecord ManageTaxSettings = new PermissionRecord { Name = "Admin area. Manage Tax Settings", SystemName = "ManageTaxSettings", Category = "Configuration" };
public static readonly PermissionRecord ManageShippingSettings = new PermissionRecord { Name = "Admin area. Manage Shipping Settings", SystemName = "ManageShippingSettings", Category = "Configuration" };
public static readonly PermissionRecord ManageCurrencies = new PermissionRecord { Name = "Admin area. Manage Currencies", SystemName = "ManageCurrencies", Category = "Configuration" };
public static readonly PermissionRecord ManageMeasures = new PermissionRecord { Name = "Admin area. Manage Measures", SystemName = "ManageMeasures", Category = "Configuration" };
public static readonly PermissionRecord ManageActivityLog = new PermissionRecord { Name = "Admin area. Manage Activity Log", SystemName = "ManageActivityLog", Category = "Configuration" };
public static readonly PermissionRecord ManageAcl = new PermissionRecord { Name = "Admin area. Manage ACL", SystemName = "ManageACL", Category = "Configuration" };
public static readonly PermissionRecord ManageEmailAccounts = new PermissionRecord { Name = "Admin area. Manage Email Accounts", SystemName = "ManageEmailAccounts", Category = "Configuration" };
public static readonly PermissionRecord ManageStores = new PermissionRecord { Name = "Admin area. Manage Stores", SystemName = "ManageStores", Category = "Configuration" };
public static readonly PermissionRecord ManagePlugins = new PermissionRecord { Name = "Admin area. Manage Plugins", SystemName = "ManagePlugins", Category = "Configuration" };
public static readonly PermissionRecord ManageSystemLog = new PermissionRecord { Name = "Admin area. Manage System Log", SystemName = "ManageSystemLog", Category = "Configuration" };
public static readonly PermissionRecord ManageMessageQueue = new PermissionRecord { Name = "Admin area. Manage Message Queue", SystemName = "ManageMessageQueue", Category = "Configuration" };
public static readonly PermissionRecord ManageMaintenance = new PermissionRecord { Name = "Admin area. Manage Maintenance", SystemName = "ManageMaintenance", Category = "Configuration" };
public static readonly PermissionRecord HtmlEditorManagePictures = new PermissionRecord { Name = "Admin area. HTML Editor. Manage pictures", SystemName = "HtmlEditor.ManagePictures", Category = "Configuration" };
public static readonly PermissionRecord ManageScheduleTasks = new PermissionRecord { Name = "Admin area. Manage Schedule Tasks", SystemName = "ManageScheduleTasks", Category = "Configuration" };
//public store permissions
public static readonly PermissionRecord DisplayPrices = new PermissionRecord { Name = "Public store. Display Prices", SystemName = "DisplayPrices", Category = "PublicStore" };
public static readonly PermissionRecord EnableShoppingCart = new PermissionRecord { Name = "Public store. Enable shopping cart", SystemName = "EnableShoppingCart", Category = "PublicStore" };
public static readonly PermissionRecord EnableWishlist = new PermissionRecord { Name = "Public store. Enable wishlist", SystemName = "EnableWishlist", Category = "PublicStore" };
public static readonly PermissionRecord PublicStoreAllowNavigation = new PermissionRecord { Name = "Public store. Allow navigation", SystemName = "PublicStoreAllowNavigation", Category = "PublicStore" };
public virtual IEnumerable<PermissionRecord> GetPermissions()
{
return new[]
{
AccessAdminPanel,
AllowCustomerImpersonation,
ManageProducts,
ManageCategories,
ManageManufacturers,
ManageProductReviews,
ManageProductTags,
ManageAttributes,
ManageCustomers,
ManageVendors,
ManageCurrentCarts,
ManageOrders,
ManageRecurringPayments,
ManageGiftCards,
ManageReturnRequests,
OrderCountryReport,
ManageAffiliates,
ManageCampaigns,
ManageDiscounts,
ManageNewsletterSubscribers,
ManagePolls,
ManageNews,
ManageBlog,
ManageWidgets,
ManageTopics,
ManageForums,
ManageMessageTemplates,
ManageCountries,
ManageLanguages,
ManageSettings,
ManagePaymentMethods,
ManageExternalAuthenticationMethods,
ManageTaxSettings,
ManageShippingSettings,
ManageCurrencies,
ManageMeasures,
ManageActivityLog,
ManageAcl,
ManageEmailAccounts,
ManageStores,
ManagePlugins,
ManageSystemLog,
ManageMessageQueue,
ManageMaintenance,
HtmlEditorManagePictures,
ManageScheduleTasks,
DisplayPrices,
EnableShoppingCart,
EnableWishlist,
PublicStoreAllowNavigation,
};
}
public virtual IEnumerable<DefaultPermissionRecord> GetDefaultPermissions()
{
return new[]
{
new DefaultPermissionRecord
{
CustomerRoleSystemName = SystemCustomerRoleNames.Administrators,
PermissionRecords = new[]
{
AccessAdminPanel,
AllowCustomerImpersonation,
ManageProducts,
ManageCategories,
ManageManufacturers,
ManageProductReviews,
ManageProductTags,
ManageAttributes,
ManageCustomers,
ManageVendors,
ManageCurrentCarts,
ManageOrders,
ManageRecurringPayments,
ManageGiftCards,
ManageReturnRequests,
OrderCountryReport,
ManageAffiliates,
ManageCampaigns,
ManageDiscounts,
ManageNewsletterSubscribers,
ManagePolls,
ManageNews,
ManageBlog,
ManageWidgets,
ManageTopics,
ManageForums,
ManageMessageTemplates,
ManageCountries,
ManageLanguages,
ManageSettings,
ManagePaymentMethods,
ManageExternalAuthenticationMethods,
ManageTaxSettings,
ManageShippingSettings,
ManageCurrencies,
ManageMeasures,
ManageActivityLog,
ManageAcl,
ManageEmailAccounts,
ManageStores,
ManagePlugins,
ManageSystemLog,
ManageMessageQueue,
ManageMaintenance,
HtmlEditorManagePictures,
ManageScheduleTasks,
DisplayPrices,
EnableShoppingCart,
EnableWishlist,
PublicStoreAllowNavigation,
}
},
new DefaultPermissionRecord
{
CustomerRoleSystemName = SystemCustomerRoleNames.ForumModerators,
PermissionRecords = new[]
{
DisplayPrices,
EnableShoppingCart,
EnableWishlist,
PublicStoreAllowNavigation,
}
},
new DefaultPermissionRecord
{
CustomerRoleSystemName = SystemCustomerRoleNames.Guests,
PermissionRecords = new[]
{
DisplayPrices,
EnableShoppingCart,
EnableWishlist,
PublicStoreAllowNavigation,
}
},
new DefaultPermissionRecord
{
CustomerRoleSystemName = SystemCustomerRoleNames.Registered,
PermissionRecords = new[]
{
DisplayPrices,
EnableShoppingCart,
EnableWishlist,
PublicStoreAllowNavigation,
}
},
new DefaultPermissionRecord
{
CustomerRoleSystemName = SystemCustomerRoleNames.Vendors,
PermissionRecords = new[]
{
AccessAdminPanel,
ManageProducts,
ManageOrders,
}
}
};
}
}
}
| |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Owin.StaticFiles.ContentTypes
{
/// <summary>
/// Provides a mapping between file extensions and MIME types.
/// </summary>
public class FileExtensionContentTypeProvider : IContentTypeProvider
{
#region Extension mapping table
/// <summary>
/// Creates a new provider with a set of default mappings.
/// </summary>
public FileExtensionContentTypeProvider()
: this(new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
{ ".323", "text/h323" },
{ ".3g2", "video/3gpp2" },
{ ".3gp2", "video/3gpp2" },
{ ".3gp", "video/3gpp" },
{ ".3gpp", "video/3gpp" },
{ ".aac", "audio/aac" },
{ ".aaf", "application/octet-stream" },
{ ".aca", "application/octet-stream" },
{ ".accdb", "application/msaccess" },
{ ".accde", "application/msaccess" },
{ ".accdt", "application/msaccess" },
{ ".acx", "application/internet-property-stream" },
{ ".adt", "audio/vnd.dlna.adts" },
{ ".adts", "audio/vnd.dlna.adts" },
{ ".afm", "application/octet-stream" },
{ ".ai", "application/postscript" },
{ ".aif", "audio/x-aiff" },
{ ".aifc", "audio/aiff" },
{ ".aiff", "audio/aiff" },
{ ".application", "application/x-ms-application" },
{ ".art", "image/x-jg" },
{ ".asd", "application/octet-stream" },
{ ".asf", "video/x-ms-asf" },
{ ".asi", "application/octet-stream" },
{ ".asm", "text/plain" },
{ ".asr", "video/x-ms-asf" },
{ ".asx", "video/x-ms-asf" },
{ ".atom", "application/atom+xml" },
{ ".au", "audio/basic" },
{ ".avi", "video/x-msvideo" },
{ ".axs", "application/olescript" },
{ ".bas", "text/plain" },
{ ".bcpio", "application/x-bcpio" },
{ ".bin", "application/octet-stream" },
{ ".bmp", "image/bmp" },
{ ".c", "text/plain" },
{ ".cab", "application/vnd.ms-cab-compressed" },
{ ".calx", "application/vnd.ms-office.calx" },
{ ".cat", "application/vnd.ms-pki.seccat" },
{ ".cdf", "application/x-cdf" },
{ ".chm", "application/octet-stream" },
{ ".class", "application/x-java-applet" },
{ ".clp", "application/x-msclip" },
{ ".cmx", "image/x-cmx" },
{ ".cnf", "text/plain" },
{ ".cod", "image/cis-cod" },
{ ".cpio", "application/x-cpio" },
{ ".cpp", "text/plain" },
{ ".crd", "application/x-mscardfile" },
{ ".crl", "application/pkix-crl" },
{ ".crt", "application/x-x509-ca-cert" },
{ ".csh", "application/x-csh" },
{ ".css", "text/css" },
{ ".csv", "application/octet-stream" },
{ ".cur", "application/octet-stream" },
{ ".dcr", "application/x-director" },
{ ".deploy", "application/octet-stream" },
{ ".der", "application/x-x509-ca-cert" },
{ ".dib", "image/bmp" },
{ ".dir", "application/x-director" },
{ ".disco", "text/xml" },
{ ".dlm", "text/dlm" },
{ ".doc", "application/msword" },
{ ".docm", "application/vnd.ms-word.document.macroEnabled.12" },
{ ".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" },
{ ".dot", "application/msword" },
{ ".dotm", "application/vnd.ms-word.template.macroEnabled.12" },
{ ".dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template" },
{ ".dsp", "application/octet-stream" },
{ ".dtd", "text/xml" },
{ ".dvi", "application/x-dvi" },
{ ".dvr-ms", "video/x-ms-dvr" },
{ ".dwf", "drawing/x-dwf" },
{ ".dwp", "application/octet-stream" },
{ ".dxr", "application/x-director" },
{ ".eml", "message/rfc822" },
{ ".emz", "application/octet-stream" },
{ ".eot", "application/vnd.ms-fontobject" },
{ ".eps", "application/postscript" },
{ ".etx", "text/x-setext" },
{ ".evy", "application/envoy" },
{ ".fdf", "application/vnd.fdf" },
{ ".fif", "application/fractals" },
{ ".fla", "application/octet-stream" },
{ ".flr", "x-world/x-vrml" },
{ ".flv", "video/x-flv" },
{ ".gif", "image/gif" },
{ ".gtar", "application/x-gtar" },
{ ".gz", "application/x-gzip" },
{ ".h", "text/plain" },
{ ".hdf", "application/x-hdf" },
{ ".hdml", "text/x-hdml" },
{ ".hhc", "application/x-oleobject" },
{ ".hhk", "application/octet-stream" },
{ ".hhp", "application/octet-stream" },
{ ".hlp", "application/winhlp" },
{ ".hqx", "application/mac-binhex40" },
{ ".hta", "application/hta" },
{ ".htc", "text/x-component" },
{ ".htm", "text/html" },
{ ".html", "text/html" },
{ ".htt", "text/webviewhtml" },
{ ".hxt", "text/html" },
{ ".ical", "text/calendar" },
{ ".icalendar", "text/calendar" },
{ ".ico", "image/x-icon" },
{ ".ics", "text/calendar" },
{ ".ief", "image/ief" },
{ ".ifb", "text/calendar" },
{ ".iii", "application/x-iphone" },
{ ".inf", "application/octet-stream" },
{ ".ins", "application/x-internet-signup" },
{ ".isp", "application/x-internet-signup" },
{ ".IVF", "video/x-ivf" },
{ ".jar", "application/java-archive" },
{ ".java", "application/octet-stream" },
{ ".jck", "application/liquidmotion" },
{ ".jcz", "application/liquidmotion" },
{ ".jfif", "image/pjpeg" },
{ ".jpb", "application/octet-stream" },
{ ".jpe", "image/jpeg" },
{ ".jpeg", "image/jpeg" },
{ ".jpg", "image/jpeg" },
{ ".js", "application/javascript" },
{ ".jsx", "text/jscript" },
{ ".latex", "application/x-latex" },
{ ".lit", "application/x-ms-reader" },
{ ".lpk", "application/octet-stream" },
{ ".lsf", "video/x-la-asf" },
{ ".lsx", "video/x-la-asf" },
{ ".lzh", "application/octet-stream" },
{ ".m13", "application/x-msmediaview" },
{ ".m14", "application/x-msmediaview" },
{ ".m1v", "video/mpeg" },
{ ".m2ts", "video/vnd.dlna.mpeg-tts" },
{ ".m3u", "audio/x-mpegurl" },
{ ".m4a", "audio/mp4" },
{ ".m4v", "video/mp4" },
{ ".man", "application/x-troff-man" },
{ ".manifest", "application/x-ms-manifest" },
{ ".map", "text/plain" },
{ ".mdb", "application/x-msaccess" },
{ ".mdp", "application/octet-stream" },
{ ".me", "application/x-troff-me" },
{ ".mht", "message/rfc822" },
{ ".mhtml", "message/rfc822" },
{ ".mid", "audio/mid" },
{ ".midi", "audio/mid" },
{ ".mix", "application/octet-stream" },
{ ".mmf", "application/x-smaf" },
{ ".mno", "text/xml" },
{ ".mny", "application/x-msmoney" },
{ ".mov", "video/quicktime" },
{ ".movie", "video/x-sgi-movie" },
{ ".mp2", "video/mpeg" },
{ ".mp3", "audio/mpeg" },
{ ".mp4", "video/mp4" },
{ ".mp4v", "video/mp4" },
{ ".mpa", "video/mpeg" },
{ ".mpe", "video/mpeg" },
{ ".mpeg", "video/mpeg" },
{ ".mpg", "video/mpeg" },
{ ".mpp", "application/vnd.ms-project" },
{ ".mpv2", "video/mpeg" },
{ ".ms", "application/x-troff-ms" },
{ ".msi", "application/octet-stream" },
{ ".mso", "application/octet-stream" },
{ ".mvb", "application/x-msmediaview" },
{ ".mvc", "application/x-miva-compiled" },
{ ".nc", "application/x-netcdf" },
{ ".nsc", "video/x-ms-asf" },
{ ".nws", "message/rfc822" },
{ ".ocx", "application/octet-stream" },
{ ".oda", "application/oda" },
{ ".odc", "text/x-ms-odc" },
{ ".ods", "application/oleobject" },
{ ".oga", "audio/ogg" },
{ ".ogg", "video/ogg" },
{ ".ogv", "video/ogg" },
{ ".ogx", "application/ogg" },
{ ".one", "application/onenote" },
{ ".onea", "application/onenote" },
{ ".onetoc", "application/onenote" },
{ ".onetoc2", "application/onenote" },
{ ".onetmp", "application/onenote" },
{ ".onepkg", "application/onenote" },
{ ".osdx", "application/opensearchdescription+xml" },
{ ".otf", "font/otf" },
{ ".p10", "application/pkcs10" },
{ ".p12", "application/x-pkcs12" },
{ ".p7b", "application/x-pkcs7-certificates" },
{ ".p7c", "application/pkcs7-mime" },
{ ".p7m", "application/pkcs7-mime" },
{ ".p7r", "application/x-pkcs7-certreqresp" },
{ ".p7s", "application/pkcs7-signature" },
{ ".pbm", "image/x-portable-bitmap" },
{ ".pcx", "application/octet-stream" },
{ ".pcz", "application/octet-stream" },
{ ".pdf", "application/pdf" },
{ ".pfb", "application/octet-stream" },
{ ".pfm", "application/octet-stream" },
{ ".pfx", "application/x-pkcs12" },
{ ".pgm", "image/x-portable-graymap" },
{ ".pko", "application/vnd.ms-pki.pko" },
{ ".pma", "application/x-perfmon" },
{ ".pmc", "application/x-perfmon" },
{ ".pml", "application/x-perfmon" },
{ ".pmr", "application/x-perfmon" },
{ ".pmw", "application/x-perfmon" },
{ ".png", "image/png" },
{ ".pnm", "image/x-portable-anymap" },
{ ".pnz", "image/png" },
{ ".pot", "application/vnd.ms-powerpoint" },
{ ".potm", "application/vnd.ms-powerpoint.template.macroEnabled.12" },
{ ".potx", "application/vnd.openxmlformats-officedocument.presentationml.template" },
{ ".ppam", "application/vnd.ms-powerpoint.addin.macroEnabled.12" },
{ ".ppm", "image/x-portable-pixmap" },
{ ".pps", "application/vnd.ms-powerpoint" },
{ ".ppsm", "application/vnd.ms-powerpoint.slideshow.macroEnabled.12" },
{ ".ppsx", "application/vnd.openxmlformats-officedocument.presentationml.slideshow" },
{ ".ppt", "application/vnd.ms-powerpoint" },
{ ".pptm", "application/vnd.ms-powerpoint.presentation.macroEnabled.12" },
{ ".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation" },
{ ".prf", "application/pics-rules" },
{ ".prm", "application/octet-stream" },
{ ".prx", "application/octet-stream" },
{ ".ps", "application/postscript" },
{ ".psd", "application/octet-stream" },
{ ".psm", "application/octet-stream" },
{ ".psp", "application/octet-stream" },
{ ".pub", "application/x-mspublisher" },
{ ".qt", "video/quicktime" },
{ ".qtl", "application/x-quicktimeplayer" },
{ ".qxd", "application/octet-stream" },
{ ".ra", "audio/x-pn-realaudio" },
{ ".ram", "audio/x-pn-realaudio" },
{ ".rar", "application/octet-stream" },
{ ".ras", "image/x-cmu-raster" },
{ ".rf", "image/vnd.rn-realflash" },
{ ".rgb", "image/x-rgb" },
{ ".rm", "application/vnd.rn-realmedia" },
{ ".rmi", "audio/mid" },
{ ".roff", "application/x-troff" },
{ ".rpm", "audio/x-pn-realaudio-plugin" },
{ ".rtf", "application/rtf" },
{ ".rtx", "text/richtext" },
{ ".scd", "application/x-msschedule" },
{ ".sct", "text/scriptlet" },
{ ".sea", "application/octet-stream" },
{ ".setpay", "application/set-payment-initiation" },
{ ".setreg", "application/set-registration-initiation" },
{ ".sgml", "text/sgml" },
{ ".sh", "application/x-sh" },
{ ".shar", "application/x-shar" },
{ ".sit", "application/x-stuffit" },
{ ".sldm", "application/vnd.ms-powerpoint.slide.macroEnabled.12" },
{ ".sldx", "application/vnd.openxmlformats-officedocument.presentationml.slide" },
{ ".smd", "audio/x-smd" },
{ ".smi", "application/octet-stream" },
{ ".smx", "audio/x-smd" },
{ ".smz", "audio/x-smd" },
{ ".snd", "audio/basic" },
{ ".snp", "application/octet-stream" },
{ ".spc", "application/x-pkcs7-certificates" },
{ ".spl", "application/futuresplash" },
{ ".spx", "audio/ogg" },
{ ".src", "application/x-wais-source" },
{ ".ssm", "application/streamingmedia" },
{ ".sst", "application/vnd.ms-pki.certstore" },
{ ".stl", "application/vnd.ms-pki.stl" },
{ ".sv4cpio", "application/x-sv4cpio" },
{ ".sv4crc", "application/x-sv4crc" },
{ ".svg", "image/svg+xml" },
{ ".svgz", "image/svg+xml" },
{ ".swf", "application/x-shockwave-flash" },
{ ".t", "application/x-troff" },
{ ".tar", "application/x-tar" },
{ ".tcl", "application/x-tcl" },
{ ".tex", "application/x-tex" },
{ ".texi", "application/x-texinfo" },
{ ".texinfo", "application/x-texinfo" },
{ ".tgz", "application/x-compressed" },
{ ".thmx", "application/vnd.ms-officetheme" },
{ ".thn", "application/octet-stream" },
{ ".tif", "image/tiff" },
{ ".tiff", "image/tiff" },
{ ".toc", "application/octet-stream" },
{ ".tr", "application/x-troff" },
{ ".trm", "application/x-msterminal" },
{ ".ts", "video/vnd.dlna.mpeg-tts" },
{ ".tsv", "text/tab-separated-values" },
{ ".ttf", "application/octet-stream" },
{ ".tts", "video/vnd.dlna.mpeg-tts" },
{ ".txt", "text/plain" },
{ ".u32", "application/octet-stream" },
{ ".uls", "text/iuls" },
{ ".ustar", "application/x-ustar" },
{ ".vbs", "text/vbscript" },
{ ".vcf", "text/x-vcard" },
{ ".vcs", "text/plain" },
{ ".vdx", "application/vnd.ms-visio.viewer" },
{ ".vml", "text/xml" },
{ ".vsd", "application/vnd.visio" },
{ ".vss", "application/vnd.visio" },
{ ".vst", "application/vnd.visio" },
{ ".vsto", "application/x-ms-vsto" },
{ ".vsw", "application/vnd.visio" },
{ ".vsx", "application/vnd.visio" },
{ ".vtx", "application/vnd.visio" },
{ ".wav", "audio/wav" },
{ ".wax", "audio/x-ms-wax" },
{ ".wbmp", "image/vnd.wap.wbmp" },
{ ".wcm", "application/vnd.ms-works" },
{ ".wdb", "application/vnd.ms-works" },
{ ".webm", "video/webm" },
{ ".wks", "application/vnd.ms-works" },
{ ".wm", "video/x-ms-wm" },
{ ".wma", "audio/x-ms-wma" },
{ ".wmd", "application/x-ms-wmd" },
{ ".wmf", "application/x-msmetafile" },
{ ".wml", "text/vnd.wap.wml" },
{ ".wmlc", "application/vnd.wap.wmlc" },
{ ".wmls", "text/vnd.wap.wmlscript" },
{ ".wmlsc", "application/vnd.wap.wmlscriptc" },
{ ".wmp", "video/x-ms-wmp" },
{ ".wmv", "video/x-ms-wmv" },
{ ".wmx", "video/x-ms-wmx" },
{ ".wmz", "application/x-ms-wmz" },
{ ".woff", "application/font-woff" },
{ ".woff2", "application/font-woff2" },
{ ".wps", "application/vnd.ms-works" },
{ ".wri", "application/x-mswrite" },
{ ".wrl", "x-world/x-vrml" },
{ ".wrz", "x-world/x-vrml" },
{ ".wsdl", "text/xml" },
{ ".wtv", "video/x-ms-wtv" },
{ ".wvx", "video/x-ms-wvx" },
{ ".x", "application/directx" },
{ ".xaf", "x-world/x-vrml" },
{ ".xaml", "application/xaml+xml" },
{ ".xap", "application/x-silverlight-app" },
{ ".xbap", "application/x-ms-xbap" },
{ ".xbm", "image/x-xbitmap" },
{ ".xdr", "text/plain" },
{ ".xht", "application/xhtml+xml" },
{ ".xhtml", "application/xhtml+xml" },
{ ".xla", "application/vnd.ms-excel" },
{ ".xlam", "application/vnd.ms-excel.addin.macroEnabled.12" },
{ ".xlc", "application/vnd.ms-excel" },
{ ".xlm", "application/vnd.ms-excel" },
{ ".xls", "application/vnd.ms-excel" },
{ ".xlsb", "application/vnd.ms-excel.sheet.binary.macroEnabled.12" },
{ ".xlsm", "application/vnd.ms-excel.sheet.macroEnabled.12" },
{ ".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" },
{ ".xlt", "application/vnd.ms-excel" },
{ ".xltm", "application/vnd.ms-excel.template.macroEnabled.12" },
{ ".xltx", "application/vnd.openxmlformats-officedocument.spreadsheetml.template" },
{ ".xlw", "application/vnd.ms-excel" },
{ ".xml", "text/xml" },
{ ".xof", "x-world/x-vrml" },
{ ".xpm", "image/x-xpixmap" },
{ ".xps", "application/vnd.ms-xpsdocument" },
{ ".xsd", "text/xml" },
{ ".xsf", "text/xml" },
{ ".xsl", "text/xml" },
{ ".xslt", "text/xml" },
{ ".xsn", "application/octet-stream" },
{ ".xtp", "application/octet-stream" },
{ ".xwd", "image/x-xwindowdump" },
{ ".z", "application/x-compress" },
{ ".zip", "application/x-zip-compressed" },
})
{
}
#endregion
/// <summary>
/// Creates a lookup engine using the provided mapping.
/// It is recommended that the IDictionary instance use StringComparer.OrdinalIgnoreCase.
/// </summary>
/// <param name="mapping"></param>
public FileExtensionContentTypeProvider(IDictionary<string, string> mapping)
{
if (mapping == null)
{
throw new ArgumentNullException("mapping");
}
Mappings = mapping;
}
/// <summary>
/// The cross reference table of file extensions and content-types.
/// </summary>
public IDictionary<string, string> Mappings { get; private set; }
/// <summary>
/// Given a file path, determine the MIME type
/// </summary>
/// <param name="subpath">A file path</param>
/// <param name="contentType">The resulting MIME type</param>
/// <returns>True if MIME type could be determined</returns>
public bool TryGetContentType(string subpath, out string contentType)
{
string extension = Path.GetExtension(subpath);
if (extension == null)
{
contentType = null;
return false;
}
return Mappings.TryGetValue(extension, out contentType);
}
}
}
| |
//
// RepositoryRegistry.cs
//
// Author:
// Lluis Sanchez Gual
//
// Copyright (C) 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;
using System.Linq;
using System.IO;
using System.Collections;
using Mono.Addins.Setup.ProgressMonitoring;
using System.Collections.Generic;
namespace Mono.Addins.Setup
{
/// <summary>
/// A registry of on-line repositories
/// </summary>
/// <remarks>
/// This class can be used to manage on-line repository subscriptions.
/// </remarks>
public class RepositoryRegistry
{
ArrayList repoList;
SetupService service;
internal RepositoryRegistry (SetupService service)
{
this.service = service;
}
/// <summary>
/// Subscribes to an on-line repository
/// </summary>
/// <param name="monitor">
/// Progress monitor where to show progress status and log
/// </param>
/// <param name="url">
/// URL of the repository
/// </param>
/// <returns>
/// A repository reference
/// </returns>
/// <remarks>
/// The repository index is not downloaded by default. It can be downloaded
/// by calling UpdateRepository.
/// </remarks>
public AddinRepository RegisterRepository (IProgressStatus monitor, string url)
{
return RegisterRepository (monitor, url, false);
}
/// <summary>
/// Subscribes to an on-line repository
/// </summary>
/// <param name="monitor">
/// Progress monitor where to show progress status and log
/// </param>
/// <param name="url">
/// URL of the repository
/// </param>
/// <param name="updateNow">
/// When set to True, the repository index will be downloaded.
/// </param>
/// <returns>
/// A repository reference
/// </returns>
public AddinRepository RegisterRepository (IProgressStatus monitor, string url, bool updateNow)
{
if (string.IsNullOrEmpty (url))
throw new ArgumentException ("Emtpy url");
if (!url.EndsWith (".mrep")) {
if (url [url.Length - 1] != '/')
url += "/";
url = url + "main.mrep";
}
RepositoryRecord rr = FindRepositoryRecord (url);
if (rr != null)
return rr;
rr = RegisterRepository (url, false);
try {
if (updateNow) {
UpdateRepository (monitor, url);
rr = FindRepositoryRecord (url);
Repository rep = rr.GetCachedRepository ();
if (rep != null)
rr.Name = rep.Name;
}
service.SaveConfiguration ();
return rr;
} catch (Exception ex) {
if (monitor != null)
monitor.ReportError ("The repository could not be registered", ex);
if (ContainsRepository (url))
RemoveRepository (url);
return null;
}
}
internal RepositoryRecord RegisterRepository (string url, bool isReference)
{
RepositoryRecord rr = FindRepositoryRecord (url);
if (rr != null) {
if (rr.IsReference && !isReference) {
rr.IsReference = false;
service.SaveConfiguration ();
}
return rr;
}
rr = new RepositoryRecord ();
rr.Url = url;
rr.IsReference = isReference;
string name = service.RepositoryCachePath;
if (!Directory.Exists (name))
Directory.CreateDirectory (name);
string host = new Uri (url).Host;
if (host.Length == 0)
host = "repo";
name = Path.Combine (name, host);
rr.File = name + "_" + service.Configuration.RepositoryIdCount + ".mrep";
rr.Id = "rep" + service.Configuration.RepositoryIdCount;
service.Configuration.Repositories.Add (rr);
service.Configuration.RepositoryIdCount++;
service.SaveConfiguration ();
repoList = null;
return rr;
}
internal RepositoryRecord FindRepositoryRecord (string url)
{
foreach (RepositoryRecord rr in service.Configuration.Repositories)
if (rr.Url == url) return rr;
return null;
}
/// <summary>
/// Removes an on-line repository subscription.
/// </summary>
/// <param name="url">
/// URL of the repository.
/// </param>
public void RemoveRepository (string url)
{
RepositoryRecord rep = FindRepositoryRecord (url);
if (rep == null)
return; // Nothing to do
foreach (RepositoryRecord rr in service.Configuration.Repositories) {
if (rr == rep) continue;
Repository newRep = rr.GetCachedRepository ();
if (newRep == null) continue;
foreach (ReferenceRepositoryEntry re in newRep.Repositories) {
if (re.Url == url) {
// The repository can't be removed because there is another
// repository depending on it. Just mark it as a reference.
rep.IsReference = true;
return;
}
}
}
// There are no other repositories referencing this one, so we can safely delete
Repository delRep = rep.GetCachedRepository ();
service.Configuration.Repositories.Remove (rep);
rep.ClearCachedRepository ();
if (delRep != null) {
foreach (ReferenceRepositoryEntry re in delRep.Repositories)
RemoveRepository (new Uri (new Uri (url), re.Url).ToString ());
}
service.SaveConfiguration ();
repoList = null;
}
/// <summary>
/// Enables or disables a repository
/// </summary>
/// <param name='url'>
/// URL of the repository
/// </param>
/// <param name='enabled'>
/// 'true' if the repository has to be enabled.
/// </param>
/// <remarks>
/// Disabled repositories are ignored when calling UpdateAllRepositories.
/// </remarks>
public void SetRepositoryEnabled (string url, bool enabled)
{
RepositoryRecord rep = FindRepositoryRecord (url);
if (rep == null)
return; // Nothing to do
rep.Enabled = enabled;
Repository crep = rep.GetCachedRepository ();
if (crep != null) {
foreach (RepositoryEntry re in crep.Repositories)
SetRepositoryEnabled (new Uri (new Uri (url), re.Url).ToString (), enabled);
}
service.SaveConfiguration ();
}
/// <summary>
/// Checks if a repository is already subscribed.
/// </summary>
/// <param name="url">
/// URL of the repository
/// </param>
/// <returns>
/// True if the repository is already subscribed.
/// </returns>
public bool ContainsRepository (string url)
{
return FindRepositoryRecord (url) != null;
}
ArrayList RepositoryList {
get {
if (repoList == null) {
ArrayList list = new ArrayList ();
foreach (RepositoryRecord rep in service.Configuration.Repositories) {
if (!rep.IsReference)
list.Add (rep);
}
repoList = list;
}
return repoList;
}
}
/// <summary>
/// Gets a list of subscribed repositories
/// </summary>
/// <returns>
/// A list of repositories.
/// </returns>
public AddinRepository[] GetRepositories ()
{
return (AddinRepository[]) RepositoryList.ToArray (typeof(AddinRepository));
}
/// <summary>
/// Updates the add-in index of all subscribed repositories.
/// </summary>
/// <param name="monitor">
/// Progress monitor where to show progress status and log
/// </param>
public void UpdateAllRepositories (IProgressStatus monitor)
{
UpdateRepository (monitor, (string)null);
}
/// <summary>
/// Updates the add-in index of the provided repository
/// </summary>
/// <param name="statusMonitor">
/// Progress monitor where to show progress status and log
/// </param>
/// <param name="url">
/// URL of the repository
/// </param>
public void UpdateRepository (IProgressStatus statusMonitor, string url)
{
repoList = null;
IProgressMonitor monitor = ProgressStatusMonitor.GetProgressMonitor (statusMonitor);
monitor.BeginTask ("Updating repositories", service.Configuration.Repositories.Count);
try {
int num = service.Configuration.Repositories.Count;
for (int n=0; n<num; n++) {
RepositoryRecord rr = (RepositoryRecord) service.Configuration.Repositories [n];
if (((url == null && rr.Enabled) || rr.Url == url) && !rr.IsReference)
UpdateRepository (monitor, new Uri (rr.Url), rr);
monitor.Step (1);
}
} catch (Exception ex) {
statusMonitor.ReportError ("Could not get information from repository", ex);
return;
} finally {
monitor.EndTask ();
}
service.SaveConfiguration ();
}
void UpdateRepository (IProgressMonitor monitor, Uri baseUri, RepositoryRecord rr)
{
Uri absUri = new Uri (baseUri, rr.Url);
monitor.BeginTask ("Updating from " + absUri.ToString (), 2);
Repository newRep = null;
Exception error = null;
try {
newRep = (Repository) service.Store.DownloadObject (monitor, absUri.ToString (), typeof(Repository));
} catch (Exception ex) {
error = ex;
}
if (newRep == null) {
monitor.ReportError ("Could not get information from repository" + ": " + absUri.ToString (), error);
return;
}
monitor.Step (1);
foreach (ReferenceRepositoryEntry re in newRep.Repositories) {
Uri refRepUri = new Uri (absUri, re.Url);
string refRepUrl = refRepUri.ToString ();
RepositoryRecord refRep = FindRepositoryRecord (refRepUrl);
if (refRep == null)
refRep = RegisterRepository (refRepUrl, true);
refRep.Enabled = rr.Enabled;
// Update the repo if the modified timestamp changes or if there is no timestamp info
if (refRep.LastModified != re.LastModified || re.LastModified == DateTime.MinValue) {
refRep.LastModified = re.LastModified;
UpdateRepository (monitor, refRepUri, refRep);
}
}
monitor.EndTask ();
rr.UpdateCachedRepository (newRep);
}
/// <summary>
/// Gets a list of available add-in updates.
/// </summary>
/// <returns>
/// A list of add-in references.
/// </returns>
/// <remarks>
/// The list is generated by looking at the add-ins currently installed and checking if there is any
/// add-in with a newer version number in any of the subscribed repositories. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableUpdates ()
{
return GetAvailableAddin (null, null, null, true, RepositorySearchFlags.None);
}
/// <summary>
/// Gets a list of available add-in updates.
/// </summary>
/// <param name="flags">
/// Search flags
/// </param>
/// <returns>
/// A list of add-in references.
/// </returns>
/// <remarks>
/// The list is generated by looking at the add-ins currently installed and checking if there is any
/// add-in with a newer version number in any of the subscribed repositories. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableUpdates (RepositorySearchFlags flags)
{
return GetAvailableAddin (null, null, null, true, flags);
}
/// <summary>
/// Gets a list of available add-in updates in a specific repository.
/// </summary>
/// <param name="repositoryUrl">
/// The repository URL
/// </param>
/// <returns>
/// A list of add-in references.
/// </returns>
/// <remarks>
/// The list is generated by looking at the add-ins currently installed and checking if there is any
/// add-in with a newer version number in the provided repository. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableUpdates (string repositoryUrl)
{
return GetAvailableAddin (repositoryUrl, null, null, true, RepositorySearchFlags.None);
}
#pragma warning disable 1591
[Obsolete ("Use GetAvailableAddinUpdates (id) instead")]
public AddinRepositoryEntry[] GetAvailableUpdates (string id, string version)
{
return GetAvailableAddin (null, id, version, true, RepositorySearchFlags.None);
}
[Obsolete ("Use GetAvailableAddinUpdates (repositoryUrl, id) instead")]
public AddinRepositoryEntry[] GetAvailableUpdates (string repositoryUrl, string id, string version)
{
return GetAvailableAddin (repositoryUrl, id, version, true, RepositorySearchFlags.None);
}
#pragma warning restore 1591
/// <summary>
/// Gets a list of available updates for an add-in.
/// </summary>
/// <param name="id">
/// Identifier of the add-in.
/// </param>
/// <returns>
/// List of updates for the specified add-in.
/// </returns>
/// <remarks>
/// The list is generated by checking if there is any
/// add-in with a newer version number in any of the subscribed repositories. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddinUpdates (string id)
{
return GetAvailableAddin (null, id, null, true, RepositorySearchFlags.None);
}
/// <summary>
/// Gets a list of available updates for an add-in.
/// </summary>
/// <param name="id">
/// Identifier of the add-in.
/// </param>
/// <param name='flags'>
/// Search flags.
/// </param>
/// <returns>
/// List of updates for the specified add-in.
/// </returns>
/// <remarks>
/// The list is generated by checking if there is any
/// add-in with a newer version number in any of the subscribed repositories. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddinUpdates (string id, RepositorySearchFlags flags)
{
return GetAvailableAddin (null, id, null, true, flags);
}
/// <summary>
/// Gets a list of available updates for an add-in in a specific repository
/// </summary>
/// <param name="repositoryUrl">
/// Identifier of the add-in.
/// </param>
/// <param name="id">
/// Identifier of the add-in.
/// </param>
/// <returns>
/// List of updates for the specified add-in.
/// </returns>
/// <remarks>
/// The list is generated by checking if there is any
/// add-in with a newer version number in the provided repository. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddinUpdates (string repositoryUrl, string id)
{
return GetAvailableAddin (repositoryUrl, id, null, true, RepositorySearchFlags.None);
}
/// <summary>
/// Gets a list of available updates for an add-in in a specific repository
/// </summary>
/// <param name="repositoryUrl">
/// Identifier of the add-in.
/// </param>
/// <param name="id">
/// Identifier of the add-in.
/// </param>
/// <param name='flags'>
/// Search flags.
/// </param>
/// <returns>
/// List of updates for the specified add-in.
/// </returns>
/// <remarks>
/// The list is generated by checking if there is any
/// add-in with a newer version number in the provided repository. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddinUpdates (string repositoryUrl, string id, RepositorySearchFlags flags)
{
return GetAvailableAddin (repositoryUrl, id, null, true, flags);
}
/// <summary>
/// Gets a list of all available add-ins
/// </summary>
/// <returns>
/// A list of add-ins
/// </returns>
/// <remarks>
/// This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddins ()
{
return GetAvailableAddin (null, null, null, false, RepositorySearchFlags.None);
}
/// <summary>
/// Gets a list of all available add-ins
/// </summary>
/// <returns>
/// The available addins.
/// </returns>
/// <param name='flags'>
/// Search flags.
/// </param>
/// <remarks>
/// This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddins (RepositorySearchFlags flags)
{
return GetAvailableAddin (null, null, null, false, flags);
}
/// <summary>
/// Gets a list of all available add-ins in a repository
/// </summary>
/// <param name="repositoryUrl">
/// A repository URL
/// </param>
/// <returns>
/// A list of add-ins
/// </returns>
/// <remarks>
/// This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddins (string repositoryUrl)
{
return GetAvailableAddin (repositoryUrl, null, null);
}
/// <summary>
/// Gets a list of all available add-ins in a repository
/// </summary>
/// <param name="repositoryUrl">
/// A repository URL
/// </param>
/// <param name='flags'>
/// Search flags.
/// </param>
/// <returns>
/// A list of add-ins
/// </returns>
/// <remarks>
/// This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddins (string repositoryUrl, RepositorySearchFlags flags)
{
return GetAvailableAddin (repositoryUrl, null, null, false, flags);
}
/// <summary>
/// Checks if an add-in is available to be installed
/// </summary>
/// <param name="id">
/// Identifier of the add-in
/// </param>
/// <param name="version">
/// Version of the add-in (optional, it can be null)
/// </param>
/// <returns>
/// A list of add-ins
/// </returns>
/// <remarks>
/// List of references to add-ins available in on-line repositories. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddin (string id, string version)
{
return GetAvailableAddin (null, id, version);
}
/// <summary>
/// Checks if an add-in is available to be installed from a repository
/// </summary>
/// <param name="repositoryUrl">
/// A repository URL
/// </param>
/// <param name="id">
/// Identifier of the add-in
/// </param>
/// <param name="version">
/// Version of the add-in (optional, it can be null)
/// </param>
/// <returns>
/// A list of add-ins
/// </returns>
/// <remarks>
/// List of references to add-ins available in the repository. This method uses cached
/// information from on-line repositories. Make sure you call UpdateRepository or UpdateAllRepositories
/// before using this method to ensure that the latest information is available.
/// </remarks>
public AddinRepositoryEntry[] GetAvailableAddin (string repositoryUrl, string id, string version)
{
return GetAvailableAddin (repositoryUrl, id, version, false, RepositorySearchFlags.None);
}
PackageRepositoryEntry[] GetAvailableAddin (string repositoryUrl, string id, string version, bool updates, RepositorySearchFlags flags)
{
List<PackageRepositoryEntry> list = new List<PackageRepositoryEntry> ();
IEnumerable ee;
if (repositoryUrl != null) {
ArrayList repos = new ArrayList ();
GetRepositoryTree (repositoryUrl, repos);
ee = repos;
} else
ee = service.Configuration.Repositories;
foreach (RepositoryRecord rr in ee) {
if (!rr.Enabled)
continue;
Repository rep = rr.GetCachedRepository();
if (rep == null) continue;
foreach (PackageRepositoryEntry addin in rep.Addins) {
if ((id == null || Addin.GetIdName (addin.Addin.Id) == id) && (version == null || addin.Addin.Version == version)) {
if (updates) {
Addin ainfo = service.Registry.GetAddin (Addin.GetIdName (addin.Addin.Id));
if (ainfo == null || Addin.CompareVersions (ainfo.Version, addin.Addin.Version) <= 0)
continue;
}
list.Add (addin);
}
}
}
if ((flags & RepositorySearchFlags.LatestVersionsOnly) != 0)
FilterOldVersions (list);
// Old versions are returned first
list.Sort ();
return list.ToArray ();
}
void FilterOldVersions (List<PackageRepositoryEntry> addins)
{
Dictionary<string,string> versions = new Dictionary<string, string> ();
foreach (PackageRepositoryEntry a in addins) {
string last;
string id, version;
Addin.GetIdParts (a.Addin.Id, out id, out version);
if (!versions.TryGetValue (id, out last) || Addin.CompareVersions (last, version) > 0)
versions [id] = version;
}
for (int n=0; n<addins.Count; n++) {
PackageRepositoryEntry a = addins [n];
string id, version;
Addin.GetIdParts (a.Addin.Id, out id, out version);
if (versions [id] != version)
addins.RemoveAt (n--);
}
}
void GetRepositoryTree (string url, ArrayList list)
{
RepositoryRecord rr = FindRepositoryRecord (url);
if (rr == null) return;
if (list.Contains (rr))
return;
list.Add (rr);
Repository rep = rr.GetCachedRepository ();
if (rep == null)
return;
Uri absUri = new Uri (url);
foreach (ReferenceRepositoryEntry re in rep.Repositories) {
Uri refRepUri = new Uri (absUri, re.Url);
GetRepositoryTree (refRepUri.ToString (), list);
}
}
}
public enum RepositorySearchFlags
{
/// <summary>
/// No special search options
/// </summary>
None,
/// <summary>
/// Only the latest version of every add-in is included in the search
/// </summary>
LatestVersionsOnly = 1,
}
}
| |
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// 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.
//
#if !SILVERLIGHT2 && !SILVERLIGHT3 && !WINDOWS_PHONE
namespace NLog.Targets
{
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Text;
using System.Threading;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
using NLog.Internal.FileAppenders;
using NLog.Layouts;
/// <summary>
/// Writes log messages to one or more files.
/// </summary>
/// <seealso href="http://nlog-project.org/wiki/File_target">Documentation on NLog Wiki</seealso>
[Target("File")]
public class FileTarget : TargetWithLayoutHeaderAndFooter, ICreateFileParameters
{
private readonly Dictionary<string, DateTime> initializedFiles = new Dictionary<string, DateTime>();
private LineEndingMode lineEndingMode = LineEndingMode.Default;
private IFileAppenderFactory appenderFactory;
private BaseFileAppender[] recentAppenders;
private Timer autoClosingTimer;
private int initializedFilesCounter;
/// <summary>
/// Initializes a new instance of the <see cref="FileTarget" /> class.
/// </summary>
/// <remarks>
/// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code>
/// </remarks>
public FileTarget()
{
this.ArchiveNumbering = ArchiveNumberingMode.Sequence;
this.MaxArchiveFiles = 9;
this.ConcurrentWriteAttemptDelay = 1;
this.ArchiveEvery = FileArchivePeriod.None;
this.ArchiveAboveSize = -1;
this.ConcurrentWriteAttempts = 10;
this.ConcurrentWrites = true;
#if SILVERLIGHT
this.Encoding = Encoding.UTF8;
#else
this.Encoding = Encoding.Default;
#endif
this.BufferSize = 32768;
this.AutoFlush = true;
#if !SILVERLIGHT && !NET_CF
this.FileAttributes = Win32FileAttributes.Normal;
#endif
this.NewLineChars = EnvironmentHelper.NewLine;
this.EnableFileDelete = true;
this.OpenFileCacheTimeout = -1;
this.OpenFileCacheSize = 5;
this.CreateDirs = true;
}
/// <summary>
/// Gets or sets the name of the file to write to.
/// </summary>
/// <remarks>
/// This FileName string is a layout which may include instances of layout renderers.
/// This lets you use a single target to write to multiple files.
/// </remarks>
/// <example>
/// The following value makes NLog write logging events to files based on the log level in the directory where
/// the application runs.
/// <code>${basedir}/${level}.log</code>
/// All <c>Debug</c> messages will go to <c>Debug.log</c>, all <c>Info</c> messages will go to <c>Info.log</c> and so on.
/// You can combine as many of the layout renderers as you want to produce an arbitrary log file name.
/// </example>
/// <docgen category='Output Options' order='1' />
[RequiredParameter]
public Layout FileName { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to create directories if they don't exist.
/// </summary>
/// <remarks>
/// Setting this to false may improve performance a bit, but you'll receive an error
/// when attempting to write to a directory that's not present.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue(true)]
[Advanced]
public bool CreateDirs { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to delete old log file on startup.
/// </summary>
/// <remarks>
/// This option works only when the "FileName" parameter denotes a single file.
/// </remarks>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
public bool DeleteOldFileOnStartup { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to replace file contents on each write instead of appending log message at the end.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(false)]
[Advanced]
public bool ReplaceFileContentsOnEachWrite { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to keep log file open instead of opening and closing it on each logging event.
/// </summary>
/// <remarks>
/// Setting this property to <c>True</c> helps improve performance.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(false)]
public bool KeepFileOpen { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to enable log file(s) to be deleted.
/// </summary>
/// <docgen category='Output Options' order='10' />
[DefaultValue(true)]
public bool EnableFileDelete { get; set; }
#if !NET_CF && !SILVERLIGHT
/// <summary>
/// Gets or sets the file attributes (Windows only).
/// </summary>
/// <docgen category='Output Options' order='10' />
[Advanced]
public Win32FileAttributes FileAttributes { get; set; }
#endif
/// <summary>
/// Gets or sets the line ending mode.
/// </summary>
/// <docgen category='Layout Options' order='10' />
[Advanced]
public LineEndingMode LineEnding
{
get
{
return this.lineEndingMode;
}
set
{
this.lineEndingMode = value;
switch (value)
{
case LineEndingMode.CR:
this.NewLineChars = "\r";
break;
case LineEndingMode.LF:
this.NewLineChars = "\n";
break;
case LineEndingMode.CRLF:
this.NewLineChars = "\r\n";
break;
case LineEndingMode.Default:
this.NewLineChars = EnvironmentHelper.NewLine;
break;
case LineEndingMode.None:
this.NewLineChars = string.Empty;
break;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether to automatically flush the file buffers after each log message.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(true)]
public bool AutoFlush { get; set; }
/// <summary>
/// Gets or sets the number of files to be kept open. Setting this to a higher value may improve performance
/// in a situation where a single File target is writing to many files
/// (such as splitting by level or by logger).
/// </summary>
/// <remarks>
/// The files are managed on a LRU (least recently used) basis, which flushes
/// the files that have not been used for the longest period of time should the
/// cache become full. As a rule of thumb, you shouldn't set this parameter to
/// a very high value. A number like 10-15 shouldn't be exceeded, because you'd
/// be keeping a large number of files open which consumes system resources.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(5)]
[Advanced]
public int OpenFileCacheSize { get; set; }
/// <summary>
/// Gets or sets the maximum number of seconds that files are kept open. If this number is negative the files are
/// not automatically closed after a period of inactivity.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(-1)]
[Advanced]
public int OpenFileCacheTimeout { get; set; }
/// <summary>
/// Gets or sets the log file buffer size in bytes.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(32768)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the file encoding.
/// </summary>
/// <docgen category='Layout Options' order='10' />
public Encoding Encoding { get; set; }
/// <summary>
/// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on the same host.
/// </summary>
/// <remarks>
/// This makes multi-process logging possible. NLog uses a special technique
/// that lets it keep the files open for writing.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(true)]
public bool ConcurrentWrites { get; set; }
/// <summary>
/// Gets or sets a value indicating whether concurrent writes to the log file by multiple processes on different network hosts.
/// </summary>
/// <remarks>
/// This effectively prevents files from being kept open.
/// </remarks>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(false)]
public bool NetworkWrites { get; set; }
/// <summary>
/// Gets or sets the number of times the write is appended on the file before NLog
/// discards the log message.
/// </summary>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(10)]
[Advanced]
public int ConcurrentWriteAttempts { get; set; }
/// <summary>
/// Gets or sets the delay in milliseconds to wait before attempting to write to the file again.
/// </summary>
/// <remarks>
/// The actual delay is a random value between 0 and the value specified
/// in this parameter. On each failed attempt the delay base is doubled
/// up to <see cref="ConcurrentWriteAttempts" /> times.
/// </remarks>
/// <example>
/// Assuming that ConcurrentWriteAttemptDelay is 10 the time to wait will be:<p/>
/// a random value between 0 and 10 milliseconds - 1st attempt<br/>
/// a random value between 0 and 20 milliseconds - 2nd attempt<br/>
/// a random value between 0 and 40 milliseconds - 3rd attempt<br/>
/// a random value between 0 and 80 milliseconds - 4th attempt<br/>
/// ...<p/>
/// and so on.
/// </example>
/// <docgen category='Performance Tuning Options' order='10' />
[DefaultValue(1)]
[Advanced]
public int ConcurrentWriteAttemptDelay { get; set; }
/// <summary>
/// Gets or sets the size in bytes above which log files will be automatically archived.
/// </summary>
/// <remarks>
/// Caution: Enabling this option can considerably slow down your file
/// logging in multi-process scenarios. If only one process is going to
/// be writing to the file, consider setting <c>ConcurrentWrites</c>
/// to <c>false</c> for maximum performance.
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public long ArchiveAboveSize { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to automatically archive log files every time the specified time passes.
/// </summary>
/// <remarks>
/// Files are moved to the archive as part of the write operation if the current period of time changes. For example
/// if the current <c>hour</c> changes from 10 to 11, the first write that will occur
/// on or after 11:00 will trigger the archiving.
/// <p>
/// Caution: Enabling this option can considerably slow down your file
/// logging in multi-process scenarios. If only one process is going to
/// be writing to the file, consider setting <c>ConcurrentWrites</c>
/// to <c>false</c> for maximum performance.
/// </p>
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public FileArchivePeriod ArchiveEvery { get; set; }
/// <summary>
/// Gets or sets the name of the file to be used for an archive.
/// </summary>
/// <remarks>
/// It may contain a special placeholder {#####}
/// that will be replaced with a sequence of numbers depending on
/// the archiving strategy. The number of hash characters used determines
/// the number of numerical digits to be used for numbering files.
/// </remarks>
/// <docgen category='Archival Options' order='10' />
public Layout ArchiveFileName { get; set; }
/// <summary>
/// Gets or sets the maximum number of archive files that should be kept.
/// </summary>
/// <docgen category='Archival Options' order='10' />
[DefaultValue(9)]
public int MaxArchiveFiles { get; set; }
/// <summary>
/// Gets or sets the way file archives are numbered.
/// </summary>
/// <docgen category='Archival Options' order='10' />
public ArchiveNumberingMode ArchiveNumbering { get; set; }
/// <summary>
/// Gets the characters that are appended after each line.
/// </summary>
protected internal string NewLineChars { get; private set; }
/// <summary>
/// Removes records of initialized files that have not been
/// accessed in the last two days.
/// </summary>
/// <remarks>
/// Files are marked 'initialized' for the purpose of writing footers when the logging finishes.
/// </remarks>
public void CleanupInitializedFiles()
{
this.CleanupInitializedFiles(DateTime.Now.AddDays(-2));
}
/// <summary>
/// Removes records of initialized files that have not been
/// accessed after the specified date.
/// </summary>
/// <param name="cleanupThreshold">The cleanup threshold.</param>
/// <remarks>
/// Files are marked 'initialized' for the purpose of writing footers when the logging finishes.
/// </remarks>
public void CleanupInitializedFiles(DateTime cleanupThreshold)
{
// clean up files that are two days old
var filesToUninitialize = new List<string>();
foreach (var de in this.initializedFiles)
{
string fileName = de.Key;
DateTime lastWriteTime = de.Value;
if (lastWriteTime < cleanupThreshold)
{
filesToUninitialize.Add(fileName);
}
}
foreach (string fileName in filesToUninitialize)
{
this.WriteFooterAndUninitialize(fileName);
}
}
/// <summary>
/// Flushes all pending file operations.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
/// <remarks>
/// The timeout parameter is ignored, because file APIs don't provide
/// the needed functionality.
/// </remarks>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
try
{
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
break;
}
this.recentAppenders[i].Flush();
}
asyncContinuation(null);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
asyncContinuation(exception);
}
}
/// <summary>
/// Initializes file logging by creating data structures that
/// enable efficient multi-file logging.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!this.KeepFileOpen)
{
this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory;
}
else
{
if (this.ArchiveAboveSize != -1 || this.ArchiveEvery != FileArchivePeriod.None)
{
if (this.NetworkWrites)
{
this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory;
}
else if (this.ConcurrentWrites)
{
#if NET_CF || SILVERLIGHT
this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory;
#elif MONO
//
// mono on Windows uses mutexes, on Unix - special appender
//
if (PlatformDetector.IsUnix)
{
this.appenderFactory = UnixMultiProcessFileAppender.TheFactory;
}
else
{
this.appenderFactory = MutexMultiProcessFileAppender.TheFactory;
}
#else
this.appenderFactory = MutexMultiProcessFileAppender.TheFactory;
#endif
}
else
{
this.appenderFactory = CountingSingleProcessFileAppender.TheFactory;
}
}
else
{
if (this.NetworkWrites)
{
this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory;
}
else if (this.ConcurrentWrites)
{
#if NET_CF || SILVERLIGHT
this.appenderFactory = RetryingMultiProcessFileAppender.TheFactory;
#elif MONO
//
// mono on Windows uses mutexes, on Unix - special appender
//
if (PlatformDetector.IsUnix)
{
this.appenderFactory = UnixMultiProcessFileAppender.TheFactory;
}
else
{
this.appenderFactory = MutexMultiProcessFileAppender.TheFactory;
}
#else
this.appenderFactory = MutexMultiProcessFileAppender.TheFactory;
#endif
}
else
{
this.appenderFactory = SingleProcessFileAppender.TheFactory;
}
}
}
this.recentAppenders = new BaseFileAppender[this.OpenFileCacheSize];
if ((this.OpenFileCacheSize > 0 || this.EnableFileDelete) && this.OpenFileCacheTimeout > 0)
{
this.autoClosingTimer = new Timer(
this.AutoClosingTimerCallback,
null,
this.OpenFileCacheTimeout * 1000,
this.OpenFileCacheTimeout * 1000);
}
// Console.Error.WriteLine("Name: {0} Factory: {1}", this.Name, this.appenderFactory.GetType().FullName);
}
/// <summary>
/// Closes the file(s) opened for writing.
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
foreach (string fileName in new List<string>(this.initializedFiles.Keys))
{
this.WriteFooterAndUninitialize(fileName);
}
if (this.autoClosingTimer != null)
{
this.autoClosingTimer.Change(Timeout.Infinite, Timeout.Infinite);
this.autoClosingTimer.Dispose();
this.autoClosingTimer = null;
}
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
break;
}
this.recentAppenders[i].Close();
this.recentAppenders[i] = null;
}
}
/// <summary>
/// Writes the specified logging event to a file specified in the FileName
/// parameter.
/// </summary>
/// <param name="logEvent">The logging event.</param>
protected override void Write(LogEventInfo logEvent)
{
string fileName = this.FileName.Render(logEvent);
byte[] bytes = this.GetBytesToWrite(logEvent);
if (this.ShouldAutoArchive(fileName, logEvent, bytes.Length))
{
this.InvalidateCacheItem(fileName);
this.DoAutoArchive(fileName, logEvent);
}
this.WriteToFile(fileName, bytes, false);
}
/// <summary>
/// Writes the specified array of logging events to a file specified in the FileName
/// parameter.
/// </summary>
/// <param name="logEvents">An array of <see cref="LogEventInfo "/> objects.</param>
/// <remarks>
/// This function makes use of the fact that the events are batched by sorting
/// the requests by filename. This optimizes the number of open/close calls
/// and can help improve performance.
/// </remarks>
protected override void Write(AsyncLogEventInfo[] logEvents)
{
var buckets = logEvents.BucketSort(c => this.FileName.Render(c.LogEvent));
using (var ms = new MemoryStream())
{
var pendingContinuations = new List<AsyncContinuation>();
foreach (var bucket in buckets)
{
string fileName = bucket.Key;
ms.SetLength(0);
ms.Position = 0;
LogEventInfo firstLogEvent = null;
foreach (AsyncLogEventInfo ev in bucket.Value)
{
if (firstLogEvent == null)
{
firstLogEvent = ev.LogEvent;
}
byte[] bytes = this.GetBytesToWrite(ev.LogEvent);
ms.Write(bytes, 0, bytes.Length);
pendingContinuations.Add(ev.Continuation);
}
this.FlushCurrentFileWrites(fileName, firstLogEvent, ms, pendingContinuations);
}
}
}
/// <summary>
/// Formats the log event for write.
/// </summary>
/// <param name="logEvent">The log event to be formatted.</param>
/// <returns>A string representation of the log event.</returns>
protected virtual string GetFormattedMessage(LogEventInfo logEvent)
{
return this.Layout.Render(logEvent);
}
/// <summary>
/// Gets the bytes to be written to the file.
/// </summary>
/// <param name="logEvent">Log event.</param>
/// <returns>Array of bytes that are ready to be written.</returns>
protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent)
{
string renderedText = this.GetFormattedMessage(logEvent) + this.NewLineChars;
return this.TransformBytes(this.Encoding.GetBytes(renderedText));
}
/// <summary>
/// Modifies the specified byte array before it gets sent to a file.
/// </summary>
/// <param name="value">The byte array.</param>
/// <returns>The modified byte array. The function can do the modification in-place.</returns>
protected virtual byte[] TransformBytes(byte[] value)
{
return value;
}
private static string ReplaceNumber(string pattern, int value)
{
int firstPart = pattern.IndexOf("{#", StringComparison.Ordinal);
int lastPart = pattern.IndexOf("#}", StringComparison.Ordinal) + 2;
int numDigits = lastPart - firstPart - 2;
return pattern.Substring(0, firstPart) + Convert.ToString(value, 10).PadLeft(numDigits, '0') + pattern.Substring(lastPart);
}
private void FlushCurrentFileWrites(string currentFileName, LogEventInfo firstLogEvent, MemoryStream ms, List<AsyncContinuation> pendingContinuations)
{
Exception lastException = null;
try
{
if (currentFileName != null)
{
if (this.ShouldAutoArchive(currentFileName, firstLogEvent, (int)ms.Length))
{
this.WriteFooterAndUninitialize(currentFileName);
this.InvalidateCacheItem(currentFileName);
this.DoAutoArchive(currentFileName, firstLogEvent);
}
this.WriteToFile(currentFileName, ms.ToArray(), false);
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
lastException = exception;
}
foreach (AsyncContinuation cont in pendingContinuations)
{
cont(lastException);
}
pendingContinuations.Clear();
}
private void RecursiveRollingRename(string fileName, string pattern, int archiveNumber)
{
if (archiveNumber >= this.MaxArchiveFiles)
{
File.Delete(fileName);
return;
}
if (!File.Exists(fileName))
{
return;
}
string newFileName = ReplaceNumber(pattern, archiveNumber);
if (File.Exists(fileName))
{
this.RecursiveRollingRename(newFileName, pattern, archiveNumber + 1);
}
InternalLogger.Trace("Renaming {0} to {1}", fileName, newFileName);
try
{
File.Move(fileName, newFileName);
}
catch (IOException)
{
string dir = Path.GetDirectoryName(newFileName);
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
File.Move(fileName, newFileName);
}
}
private void SequentialArchive(string fileName, string pattern)
{
string baseNamePattern = Path.GetFileName(pattern);
int firstPart = baseNamePattern.IndexOf("{#", StringComparison.Ordinal);
int lastPart = baseNamePattern.IndexOf("#}", StringComparison.Ordinal) + 2;
int trailerLength = baseNamePattern.Length - lastPart;
string fileNameMask = baseNamePattern.Substring(0, firstPart) + "*" + baseNamePattern.Substring(lastPart);
string dirName = Path.GetDirectoryName(Path.GetFullPath(pattern));
int nextNumber = -1;
int minNumber = -1;
var number2name = new Dictionary<int, string>();
try
{
#if SILVERLIGHT
foreach (string s in Directory.EnumerateFiles(dirName, fileNameMask))
#else
foreach (string s in Directory.GetFiles(dirName, fileNameMask))
#endif
{
string baseName = Path.GetFileName(s);
string number = baseName.Substring(firstPart, baseName.Length - trailerLength - firstPart);
int num;
try
{
num = Convert.ToInt32(number, CultureInfo.InvariantCulture);
}
catch (FormatException)
{
continue;
}
nextNumber = Math.Max(nextNumber, num);
if (minNumber != -1)
{
minNumber = Math.Min(minNumber, num);
}
else
{
minNumber = num;
}
number2name[num] = s;
}
nextNumber++;
}
catch (DirectoryNotFoundException)
{
Directory.CreateDirectory(dirName);
nextNumber = 0;
}
if (minNumber != -1)
{
int minNumberToKeep = nextNumber - this.MaxArchiveFiles + 1;
for (int i = minNumber; i < minNumberToKeep; ++i)
{
string s;
if (number2name.TryGetValue(i, out s))
{
File.Delete(s);
}
}
}
string newFileName = ReplaceNumber(pattern, nextNumber);
File.Move(fileName, newFileName);
}
private void DoAutoArchive(string fileName, LogEventInfo ev)
{
var fi = new FileInfo(fileName);
if (!fi.Exists)
{
return;
}
// Console.WriteLine("DoAutoArchive({0})", fileName);
string fileNamePattern;
if (this.ArchiveFileName == null)
{
string ext = Path.GetExtension(fileName);
fileNamePattern = Path.ChangeExtension(fi.FullName, ".{#}" + ext);
}
else
{
fileNamePattern = this.ArchiveFileName.Render(ev);
}
switch (this.ArchiveNumbering)
{
case ArchiveNumberingMode.Rolling:
this.RecursiveRollingRename(fi.FullName, fileNamePattern, 0);
break;
case ArchiveNumberingMode.Sequence:
this.SequentialArchive(fi.FullName, fileNamePattern);
break;
}
}
private bool ShouldAutoArchive(string fileName, LogEventInfo ev, int upcomingWriteSize)
{
if (this.ArchiveAboveSize == -1 && this.ArchiveEvery == FileArchivePeriod.None)
{
return false;
}
DateTime lastWriteTime;
long fileLength;
if (!this.GetFileInfo(fileName, out lastWriteTime, out fileLength))
{
return false;
}
if (this.ArchiveAboveSize != -1)
{
if (fileLength + upcomingWriteSize > this.ArchiveAboveSize)
{
return true;
}
}
if (this.ArchiveEvery != FileArchivePeriod.None)
{
string formatString;
switch (this.ArchiveEvery)
{
case FileArchivePeriod.Year:
formatString = "yyyy";
break;
case FileArchivePeriod.Month:
formatString = "yyyyMM";
break;
default:
case FileArchivePeriod.Day:
formatString = "yyyyMMdd";
break;
case FileArchivePeriod.Hour:
formatString = "yyyyMMddHH";
break;
case FileArchivePeriod.Minute:
formatString = "yyyyMMddHHmm";
break;
}
string ts = lastWriteTime.ToString(formatString, CultureInfo.InvariantCulture);
string ts2 = ev.TimeStamp.ToString(formatString, CultureInfo.InvariantCulture);
if (ts != ts2)
{
return true;
}
}
return false;
}
private void AutoClosingTimerCallback(object state)
{
lock (this.SyncRoot)
{
if (!this.IsInitialized)
{
return;
}
try
{
DateTime timeToKill = DateTime.Now.AddSeconds(-this.OpenFileCacheTimeout);
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
break;
}
if (this.recentAppenders[i].OpenTime < timeToKill)
{
for (int j = i; j < this.recentAppenders.Length; ++j)
{
if (this.recentAppenders[j] == null)
{
break;
}
this.recentAppenders[j].Close();
this.recentAppenders[j] = null;
}
break;
}
}
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Exception in AutoClosingTimerCallback: {0}", exception);
}
}
}
private void WriteToFile(string fileName, byte[] bytes, bool justData)
{
if (this.ReplaceFileContentsOnEachWrite)
{
using (FileStream fs = File.Create(fileName))
{
byte[] headerBytes = this.GetHeaderBytes();
byte[] footerBytes = this.GetFooterBytes();
if (headerBytes != null)
{
fs.Write(headerBytes, 0, headerBytes.Length);
}
fs.Write(bytes, 0, bytes.Length);
if (footerBytes != null)
{
fs.Write(footerBytes, 0, footerBytes.Length);
}
}
return;
}
bool writeHeader = false;
if (!justData)
{
if (!this.initializedFiles.ContainsKey(fileName))
{
if (this.DeleteOldFileOnStartup)
{
try
{
File.Delete(fileName);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
InternalLogger.Warn("Unable to delete old log file '{0}': {1}", fileName, exception);
}
}
this.initializedFiles[fileName] = DateTime.Now;
this.initializedFilesCounter++;
writeHeader = true;
if (this.initializedFilesCounter >= 100)
{
this.initializedFilesCounter = 0;
this.CleanupInitializedFiles();
}
}
this.initializedFiles[fileName] = DateTime.Now;
}
//
// BaseFileAppender.Write is the most expensive operation here
// so the in-memory data structure doesn't have to be
// very sophisticated. It's a table-based LRU, where we move
// the used element to become the first one.
// The number of items is usually very limited so the
// performance should be equivalent to the one of the hashtable.
//
BaseFileAppender appenderToWrite = null;
int freeSpot = this.recentAppenders.Length - 1;
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
freeSpot = i;
break;
}
if (this.recentAppenders[i].FileName == fileName)
{
// found it, move it to the first place on the list
// (MRU)
// file open has a chance of failure
// if it fails in the constructor, we won't modify any data structures
BaseFileAppender app = this.recentAppenders[i];
for (int j = i; j > 0; --j)
{
this.recentAppenders[j] = this.recentAppenders[j - 1];
}
this.recentAppenders[0] = app;
appenderToWrite = app;
break;
}
}
if (appenderToWrite == null)
{
BaseFileAppender newAppender = this.appenderFactory.Open(fileName, this);
if (this.recentAppenders[freeSpot] != null)
{
this.recentAppenders[freeSpot].Close();
this.recentAppenders[freeSpot] = null;
}
for (int j = freeSpot; j > 0; --j)
{
this.recentAppenders[j] = this.recentAppenders[j - 1];
}
this.recentAppenders[0] = newAppender;
appenderToWrite = newAppender;
}
if (writeHeader && !justData)
{
byte[] headerBytes = this.GetHeaderBytes();
if (headerBytes != null)
{
appenderToWrite.Write(headerBytes);
}
}
appenderToWrite.Write(bytes);
}
private byte[] GetHeaderBytes()
{
if (this.Header == null)
{
return null;
}
string renderedText = this.Header.Render(LogEventInfo.CreateNullEvent()) + this.NewLineChars;
return this.TransformBytes(this.Encoding.GetBytes(renderedText));
}
private byte[] GetFooterBytes()
{
if (this.Footer == null)
{
return null;
}
string renderedText = this.Footer.Render(LogEventInfo.CreateNullEvent()) + this.NewLineChars;
return this.TransformBytes(this.Encoding.GetBytes(renderedText));
}
private void WriteFooterAndUninitialize(string fileName)
{
byte[] footerBytes = this.GetFooterBytes();
if (footerBytes != null)
{
if (File.Exists(fileName))
{
this.WriteToFile(fileName, footerBytes, true);
}
}
this.initializedFiles.Remove(fileName);
}
private bool GetFileInfo(string fileName, out DateTime lastWriteTime, out long fileLength)
{
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
break;
}
if (this.recentAppenders[i].FileName == fileName)
{
this.recentAppenders[i].GetFileInfo(out lastWriteTime, out fileLength);
return true;
}
}
var fi = new FileInfo(fileName);
if (fi.Exists)
{
fileLength = fi.Length;
lastWriteTime = fi.LastWriteTime;
return true;
}
else
{
fileLength = -1;
lastWriteTime = DateTime.MinValue;
return false;
}
}
private void InvalidateCacheItem(string fileName)
{
for (int i = 0; i < this.recentAppenders.Length; ++i)
{
if (this.recentAppenders[i] == null)
{
break;
}
if (this.recentAppenders[i].FileName == fileName)
{
this.recentAppenders[i].Close();
for (int j = i; j < this.recentAppenders.Length - 1; ++j)
{
this.recentAppenders[j] = this.recentAppenders[j + 1];
}
this.recentAppenders[this.recentAppenders.Length - 1] = null;
break;
}
}
}
}
}
#endif
| |
using UnityEngine;
using System.Collections;
using System;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
public class GA {
public static GA_GameObjectManager _GA_controller;
private static GA_Settings _settings;
public static GA_Settings SettingsGA
{
get {
if (_settings == null)
{
InitAPI ();
}
return _settings;
}
private set{ _settings = value; }
}
public static GA_GameObjectManager GA_controller
{
get{
if(_GA_controller == null)
{
var ga = new GameObject("GA_Controller");
_GA_controller = ga.AddComponent<GA_GameObjectManager>();
}
return _GA_controller;
}
private set{ _GA_controller = value; }
}
public class GA_API
{
public GA_Error Error = new GA_Error();
public GA_Design Design = new GA_Design();
public GA_Business Business = new GA_Business();
public GA_GenericInfo GenericInfo = new GA_GenericInfo();
public GA_Debug Debugging = new GA_Debug();
public GA_Archive Archive = new GA_Archive();
#if UNITY_EDITOR || !UNITY_FLASH
public GA_Request Request = new GA_Request();
#endif
public GA_Submit Submit = new GA_Submit();
public GA_User User = new GA_User();
}
private static GA_API api = new GA_API();
public static GA_API API
{
get{
if(GA.SettingsGA == null)
{
InitAPI ();
}
return api;
}
private set{}
}
private static void InitAPI ()
{
try
{
_settings = (GA_Settings)Resources.Load("GameAnalytics/GA_Settings", typeof(GA_Settings));
#if UNITY_EDITOR
if (_settings == null)
{
//If the settings asset doesn't exist, then create it. We require a resources folder
if(!Directory.Exists(Application.dataPath+"/Resources"))
{
Directory.CreateDirectory(Application.dataPath+"/Resources");
}
if(!Directory.Exists(Application.dataPath+"/Resources/GameAnalytics"))
{
Directory.CreateDirectory(Application.dataPath+"/Resources/GameAnalytics");
Debug.LogWarning("GameAnalytics: Resources/GameAnalytics folder is required to store settings. it was created ");
}
var asset = ScriptableObject.CreateInstance<GA_Settings>();
//some hack to mave the asset around
string path = AssetDatabase.GetAssetPath (Selection.activeObject);
if (path == "")
{
path = "Assets";
}
else if (Path.GetExtension (path) != "")
{
path = path.Replace (Path.GetFileName (AssetDatabase.GetAssetPath (Selection.activeObject)), "");
}
string uniquePath = AssetDatabase.GenerateUniqueAssetPath("Assets/Resources/GameAnalytics/GA_Settings.asset");
AssetDatabase.CreateAsset(asset, uniquePath);
if(uniquePath != "Assets/Resources/GameAnalytics/GA_Settings.asset")
GA.Log("GameAnalytics: The path Assets/Resources/GameAnalytics/GA_Settings.asset used to save the settings file is not available.");
AssetDatabase.SaveAssets ();
Debug.LogWarning("GameAnalytics: Settings file didn't exist and was created");
Selection.activeObject = asset;
//save reference
_settings = asset;
}
#endif
GA.InitializeQueue(); //will also start a coroutine sending messages to the server if needed
}
catch (Exception e)
{
Debug.Log("Error getting GA_Settings in InitAPI: " + e.Message);
}
}
/// <summary>
/// Setup involving other components
/// </summary>
private static void InitializeQueue ()
{
SettingsGA.SetKeys(GA.SettingsGA.GameKey, GA.SettingsGA.SecretKey);
if(!Application.isPlaying)
return; // no need to setup anything else, if we are in the editor and not playing
if (GA.API.GenericInfo.UserID == "" && !GA.SettingsGA.CustomUserID)
{
Debug.LogWarning("GA UserID not set. No data will be sent.");
return;
}
#if UNITY_IPHONE || UNITY_ANDROID
GameObject go = new GameObject("GA AdSupport");
go.AddComponent<GA_AdSupport>();
#endif
GA.RunCoroutine(GA.SettingsGA.CheckInternetConnectivity(true));
}
/// <summary>
/// Starts a new coroutine for the specified method, using the StartCoroutine Unity function.
/// This is used to run the submits to the GameAnalytics server in a seperate routine.
/// </summary>
/// <param name="routine">
/// The method to start in the new coroutine <see cref="IEnumerator"/>
/// </param>
/// <returns>
/// The new coroutine <see cref="Coroutine"/>
/// </returns>
public static void RunCoroutine(IEnumerator routine)
{
RunCoroutine(routine,()=>true); //Default coroutine
}
public static void RunCoroutine(IEnumerator routine,Func<bool> done)
{
if(!Application.isPlaying && Application.isEditor)
{
#if UNITY_EDITOR
GA_ContinuationManager.StartCoroutine(routine,done);
#endif
}
else
{
GA_controller.RunCoroutine(routine);
}
}
public static void Log(object msg, bool addEvent)
{
if (GA.SettingsGA.DebugMode || (addEvent && GA.SettingsGA.DebugAddEvent))
Debug.Log(msg);
}
public static void Log(object msg)
{
if (GA.SettingsGA.DebugMode)
Debug.Log(msg);
}
public static void LogWarning(object msg)
{
Debug.LogWarning(msg);
}
public static void LogError(object msg)
{
Debug.LogError(msg);
}
#if UNITY_EDITOR
public static void HierarchyWindowCallback (int instanceID, Rect selectionRect)
{
GameObject go = (GameObject)EditorUtility.InstanceIDToObject(instanceID);
if (go != null && (go.GetComponent<GA_Tracker>() != null || go.GetComponent<GA_SystemTracker>() != null || go.GetComponent<GA_HeatMapDataFilter>() != null || go.GetComponent<GA_AdSupport>() != null))
{
float addX = 0;
if (go.GetComponent("PlayMakerFSM") != null)
addX = selectionRect.height + 2;
if (GA.SettingsGA.Logo == null)
{
GA.SettingsGA.Logo = (Texture2D)Resources.LoadAssetAtPath("Assets/Gizmos/gaLogo.png", typeof(Texture2D));
}
Graphics.DrawTexture(new Rect(GUILayoutUtility.GetLastRect().width - selectionRect.height - 5 - addX, selectionRect.y, selectionRect.height, selectionRect.height), GA.SettingsGA.Logo);
}
}
#endif
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
using System;
using System.Collections;
using System.Collections.Specialized;
using GenStrings;
namespace System.Collections.Specialized.Tests
{
public class GetIntTests
{
public const int MAX_LEN = 50; // max length of random strings
[Fact]
public void Test01()
{
IntlStrings intl;
NameValueCollection nvc;
// simple string values
string[] values =
{
"",
" ",
"a",
"aA",
"text",
" SPaces",
"1",
"$%^#",
"2222222222222222222222222",
System.DateTime.Today.ToString(),
Int32.MaxValue.ToString()
};
// keys for simple string values
string[] keys =
{
"zero",
"oNe",
" ",
"",
"aa",
"1",
System.DateTime.Today.ToString(),
"$%^#",
Int32.MaxValue.ToString(),
" spaces",
"2222222222222222222222222"
};
int cnt = 0; // Count
// initialize IntStrings
intl = new IntlStrings();
// [] NameValueCollection is constructed as expected
//-----------------------------------------------------------------
nvc = new NameValueCollection();
// [] Get(int) on empty collection
//
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); });
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(0); });
// [] Get(int) on collection filled with simple strings
//
cnt = nvc.Count;
int len = values.Length;
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
if (nvc.Count != len)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, values.Length));
}
//
for (int i = 0; i < len; i++)
{
if (String.Compare(nvc.Get(i), values[i]) != 0)
{
Assert.False(true, string.Format("Error, returned: \"{1}\", expected \"{2}\"", i, nvc.Get(i), values[i]));
}
}
//
// Intl strings
// [] Get(int) on collection filled with Intl strings
//
string[] intlValues = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
string val = intl.GetRandomString(MAX_LEN);
while (Array.IndexOf(intlValues, val) != -1)
val = intl.GetRandomString(MAX_LEN);
intlValues[i] = val;
}
Boolean caseInsensitive = false;
for (int i = 0; i < len * 2; i++)
{
if (intlValues[i].Length != 0 && intlValues[i].ToLowerInvariant() == intlValues[i].ToUpperInvariant())
caseInsensitive = true;
}
nvc.Clear();
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]);
}
if (nvc.Count != (len))
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, len));
}
for (int i = 0; i < len; i++)
{
//
if (String.Compare(nvc.Get(i), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i]));
}
}
//
// [] Case sensitivity
//
string[] intlValuesLower = new string[len * 2];
// fill array with unique strings
//
for (int i = 0; i < len * 2; i++)
{
intlValues[i] = intlValues[i].ToUpperInvariant();
}
for (int i = 0; i < len * 2; i++)
{
intlValuesLower[i] = intlValues[i].ToLowerInvariant();
}
nvc.Clear();
//
// will use first half of array as values and second half as keys
//
for (int i = 0; i < len; i++)
{
nvc.Add(intlValues[i + len], intlValues[i]); // adding uppercase strings
}
//
for (int i = 0; i < len; i++)
{
//
if (String.Compare(nvc.Get(i), intlValues[i]) != 0)
{
Assert.False(true, string.Format("Error, returned \"{1}\" instead of \"{2}\"", i, nvc.Get(i), intlValues[i]));
}
if (!caseInsensitive && String.Compare(nvc.Get(i), intlValuesLower[i]) == 0)
{
Assert.False(true, string.Format("Error, returned lowercase when added uppercase", i));
}
}
// [] Get(int) on filled collection with multiple items swith the same key
//
nvc.Clear();
len = values.Length;
string k = "keykey";
string k1 = "hm1";
string exp = "";
string exp1 = "";
for (int i = 0; i < len; i++)
{
nvc.Add(k, "Value" + i);
nvc.Add(k1, "iTem" + i);
if (i < len - 1)
{
exp += "Value" + i + ",";
exp1 += "iTem" + i + ",";
}
else
{
exp += "Value" + i;
exp1 += "iTem" + i;
}
}
if (nvc.Count != 2)
{
Assert.False(true, string.Format("Error, count is {0} instead of {1}", nvc.Count, 2));
}
if (String.Compare(nvc.Get(0), exp) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(0), exp));
}
if (String.Compare(nvc.Get(1), exp1) != 0)
{
Assert.False(true, string.Format("Error, returned \"{0}\" instead of \"{1}\"", nvc.Get(1), exp1));
}
//
// [] Get(-1)
//
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(-1); });
//
// [] Get(count)
//
if (nvc.Count < 1)
{
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt); });
//
// [] Get(count+1)
//
if (nvc.Count < 1)
{
for (int i = 0; i < len; i++)
{
nvc.Add(keys[i], values[i]);
}
}
cnt = nvc.Count;
Assert.Throws<ArgumentOutOfRangeException>(() => { nvc.Get(cnt + 1); });
//
// Get(null) - calls other overloaded version of Get - Get(string) - no exception
// [] Get(null)
//
string res = nvc.Get(null);
if (res != null)
{
Assert.False(true, "Error, returned non-null ");
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
namespace System.ComponentModel.Design
{
/// <summary>
/// This is a simple implementation of IServiceContainer.
/// </summary>
public class ServiceContainer : IServiceContainer, IDisposable
{
private ServiceCollection<object> _services;
private IServiceProvider _parentProvider;
private static readonly Type[] s_defaultServices = new Type[] { typeof(IServiceContainer), typeof(ServiceContainer) };
private static TraceSwitch s_TRACESERVICE = new TraceSwitch("TRACESERVICE", "ServiceProvider: Trace service provider requests.");
/// <summary>
/// Creates a new service object container.
/// </summary>
public ServiceContainer()
{
}
/// <summary>
/// Creates a new service object container.
/// </summary>
public ServiceContainer(IServiceProvider parentProvider)
{
_parentProvider = parentProvider;
}
/// <summary>
/// Retrieves the parent service container, or null
/// if there is no parent container.
/// </summary>
private IServiceContainer Container
{
get
{
IServiceContainer container = null;
if (_parentProvider != null)
{
container = (IServiceContainer)_parentProvider.GetService(typeof(IServiceContainer));
}
return container;
}
}
/// <summary>
/// This property returns the default services that are implemented directly on this IServiceContainer.
/// the default implementation of this property is to return the IServiceContainer and ServiceContainer
/// types. You may override this property and return your own types, modifying the default behavior
/// of GetService.
/// </summary>
protected virtual Type[] DefaultServices => s_defaultServices;
/// <summary>
/// Our collection of services. The service collection is demand
/// created here.
/// </summary>
private ServiceCollection<object> Services => _services ?? (_services = new ServiceCollection<object>());
/// <summary>
/// Adds the given service to the service container.
/// </summary>
public void AddService(Type serviceType, object serviceInstance)
{
AddService(serviceType, serviceInstance, false);
}
/// <summary>
/// Adds the given service to the service container.
/// </summary>
public virtual void AddService(Type serviceType, object serviceInstance, bool promote)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, $"Adding service (instance) {serviceType.Name}. Promoting: {promote.ToString()}");
if (promote)
{
IServiceContainer container = Container;
if (container != null)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "Promoting to container");
container.AddService(serviceType, serviceInstance, promote);
return;
}
}
// We're going to add this locally. Ensure that the service instance
// is correct.
//
if (serviceType == null) throw new ArgumentNullException(nameof(serviceType));
if (serviceInstance == null) throw new ArgumentNullException(nameof(serviceInstance));
if (!(serviceInstance is ServiceCreatorCallback) && !serviceInstance.GetType().IsCOMObject && !serviceType.IsInstanceOfType(serviceInstance))
{
throw new ArgumentException(SR.Format(SR.ErrorInvalidServiceInstance, serviceType.FullName));
}
if (Services.ContainsKey(serviceType))
{
throw new ArgumentException(SR.Format(SR.ErrorServiceExists, serviceType.FullName), nameof(serviceType));
}
Services[serviceType] = serviceInstance;
}
/// <summary>
/// Adds the given service to the service container.
/// </summary>
public void AddService(Type serviceType, ServiceCreatorCallback callback)
{
AddService(serviceType, callback, false);
}
/// <summary>
/// Adds the given service to the service container.
/// </summary>
public virtual void AddService(Type serviceType, ServiceCreatorCallback callback, bool promote)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, $"Adding service (callback) {serviceType.Name}. Promoting: {promote.ToString()}");
if (promote)
{
IServiceContainer container = Container;
if (container != null)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "Promoting to container");
container.AddService(serviceType, callback, promote);
return;
}
}
// We're going to add this locally. Ensure that the service instance
// is correct.
//
if (serviceType == null) throw new ArgumentNullException(nameof(serviceType));
if (callback == null) throw new ArgumentNullException(nameof(callback));
if (Services.ContainsKey(serviceType))
{
throw new ArgumentException(SR.Format(SR.ErrorServiceExists, serviceType.FullName), nameof(serviceType));
}
Services[serviceType] = callback;
}
/// <summary>
/// Disposes this service container. This also walks all instantiated services within the container
/// and disposes any that implement IDisposable, and clears the service list.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Disposes this service container. This also walks all instantiated services within the container
/// and disposes any that implement IDisposable, and clears the service list.
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
ServiceCollection<object> serviceCollection = _services;
_services = null;
if (serviceCollection != null)
{
foreach (object o in serviceCollection.Values)
{
if (o is IDisposable)
{
((IDisposable)o).Dispose();
}
}
}
}
}
/// <summary>
/// Retrieves the requested service.
/// </summary>
public virtual object GetService(Type serviceType)
{
object service = null;
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, $"Searching for service {serviceType.Name}");
// Try locally. We first test for services we
// implement and then look in our service collection.
Type[] defaults = DefaultServices;
for (int idx = 0; idx < defaults.Length; idx++)
{
if (serviceType.IsEquivalentTo(defaults[idx]))
{
service = this;
break;
}
}
if (service == null)
{
Services.TryGetValue(serviceType, out service);
}
// Is the service a creator delegate?
if (service is ServiceCreatorCallback)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "Encountered a callback. Invoking it");
service = ((ServiceCreatorCallback)service)(this, serviceType);
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, $"Callback return object: {(service == null ? "(null)" : service.ToString())}");
if (service != null && !service.GetType().IsCOMObject && !serviceType.IsInstanceOfType(service))
{
// Callback passed us a bad service. NULL it, rather than throwing an exception.
// Callers here do not need to be prepared to handle bad callback implemetations.
Debug.Fail($"Object {service.GetType().Name} was returned from a service creator callback but it does not implement the registered type of {serviceType.Name}");
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "**** Object does not implement service interface");
service = null;
}
// And replace the callback with our new service.
Services[serviceType] = service;
}
if (service == null && _parentProvider != null)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "Service unresolved. Trying parent");
service = _parentProvider.GetService(serviceType);
}
#if DEBUG
if (s_TRACESERVICE.TraceVerbose && service == null)
{
Debug.WriteLine("******************************************");
Debug.WriteLine("FAILED to resolve service " + serviceType.Name);
Debug.WriteLine("AT: " + Environment.StackTrace);
Debug.WriteLine("******************************************");
}
#endif
return service;
}
/// <summary>
/// Removes the given service type from the service container.
/// </summary>
public void RemoveService(Type serviceType)
{
RemoveService(serviceType, false);
}
/// <summary>
/// Removes the given service type from the service container.
/// </summary>
public virtual void RemoveService(Type serviceType, bool promote)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, $"Removing service: {serviceType.Name}, Promote: {promote.ToString()}");
if (promote)
{
IServiceContainer container = Container;
if (container != null)
{
Debug.WriteLineIf(s_TRACESERVICE.TraceVerbose, "Invoking parent container");
container.RemoveService(serviceType, promote);
return;
}
}
// We're going to remove this from our local list.
if (serviceType == null)
{
throw new ArgumentNullException(nameof(serviceType));
}
Services.Remove(serviceType);
}
/// <summary>
/// Use this collection to store mapping from the Type of a service to the object that provides it in a way
/// that is aware of embedded types. The comparer for this collection will call Type.IsEquivalentTo(...)
/// instead of doing a reference comparison which will fail in type embedding scenarios. To speed the lookup
/// performance we will use hash code of Type.FullName.
/// </summary>
/// <typeparam name="T"></typeparam>
private sealed class ServiceCollection<T> : Dictionary<Type, T>
{
private static EmbeddedTypeAwareTypeComparer s_serviceTypeComparer = new EmbeddedTypeAwareTypeComparer();
private sealed class EmbeddedTypeAwareTypeComparer : IEqualityComparer<Type>
{
public bool Equals(Type x, Type y) => x.IsEquivalentTo(y);
public int GetHashCode(Type obj) => obj.FullName.GetHashCode();
}
public ServiceCollection() : base(s_serviceTypeComparer)
{
}
}
}
}
| |
/*
* VsaEngine.cs - front-end interface to the JScript engine.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace Microsoft.JScript.Vsa
{
using System;
using System.IO;
using System.Text;
using System.Reflection;
using Microsoft.JScript;
using Microsoft.Vsa;
public class VsaEngine : BaseVsaEngine, IRedirectOutput
{
// Internal state.
private static VsaEngine primaryEngine;
private bool detached;
internal bool printSupported;
internal EngineInstance engineInstance;
private LenientGlobalObject lenientGlobalObject;
private GlobalScope globalScope;
private Object[] scopeStack;
private int scopeStackSize;
private Object currentScope;
// Constructors.
public VsaEngine() : this(true) {}
public VsaEngine(bool fast)
: base("JScript", "7.0.3300", true)
{
vsaItems = new VsaItems(this);
detached = false;
printSupported = false;
engineInstance = new EngineInstance(this);
engineInstance.Init();
// Set the global context to this engine if we are
// the only engine instance in the system.
Globals.SetContextEngine(this);
// Create the global object that contains all of
// the definitions in the engine's global scope.
lenientGlobalObject = new LenientGlobalObject(this);
// Create the global scope object.
globalScope = new GlobalScope
(null, lenientGlobalObject.globalObject);
// Initialize the scope stack.
scopeStack = new Object [8];
scopeStack[0] = globalScope;
scopeStackSize = 1;
currentScope = globalScope;
}
// Clone an application domain's engine.
public virtual IVsaEngine Clone(AppDomain domain)
{
throw new NotImplementedException();
}
// Run this engine in a specified application domain.
public virtual void Run(AppDomain domain)
{
throw new NotImplementedException();
}
// Compile an "empty" script context.
public virtual bool CompileEmpty()
{
lock(this)
{
return DoCompile();
}
}
// Run an "empty" script context.
public virtual void RunEmpty()
{
// Let the base class do the work.
base.Run();
}
// Connect up the events in use by this engine.
public virtual void ConnectEvents()
{
// Noting to do here.
}
// Disconnect the events in use by this engine.
public virtual void DisconnectEvents()
{
// Noting to do here.
}
// Register an event source with this engine.
public virtual void RegisterEventSource(String name)
{
// Nothing to do here.
}
// Get the assembly or assembly builder in use.
public virtual Assembly GetAssembly()
{
// We don't use assemblies in this implementation.
return null;
}
// Get the module or module builder in use.
public virtual Module GetModule()
{
// We don't use modules in this implementation.
return null;
}
// Get the global script scope for this engine.
public virtual IVsaScriptScope GetGlobalScope()
{
// As far as we can tell, this API is obsolete or it was
// never actually used for anything. Let us know if you
// find something important that depends upon it.
return null;
}
// Get the main scope.
public virtual GlobalScope GetMainScope()
{
return globalScope;
}
// Interrupt the engine if it is running in a separate thread.
public virtual void Interrupt()
{
// We don't support threading yet.
}
// Determine if an identifier is valid for this engine.
public override bool IsValidIdentifier(String identifier)
{
if(identifier == null)
{
return false;
}
JSScanner scanner = new JSScanner(identifier);
if(scanner.FetchIdentifier() == null)
{
return false;
}
return (scanner.Fetch() == -1);
}
// Internal implementation of "Close"
protected override void DoClose()
{
// Close all code items in the engine.
((VsaItems)vsaItems).Close();
vsaItems = null;
// Clear the engine site, which will no longer be required.
engineSite = null;
// Reset global variables that may refer to this instance.
lock(typeof(VsaEngine))
{
if(primaryEngine == this)
{
primaryEngine = null;
}
if(Globals.contextEngine == this)
{
Globals.contextEngine = null;
#if !CONFIG_SMALL_CONSOLE
ScriptStream.Out = Console.Out;
ScriptStream.Error = Console.Error;
#endif
}
}
#if !ECMA_COMPAT
// Force a garbage collection to clean everything up.
GC.Collect();
#endif
}
// Internal implementation of "Compile".
protected override bool DoCompile()
{
failedCompilation = false;
if(vsaItems != null)
{
failedCompilation = !(((VsaItems)vsaItems).Compile());
}
return !failedCompilation;
}
// Load the compiled state into the application domain.
protected override Assembly LoadCompiledState()
{
return base.LoadCompiledState();
}
// Internal implementation of "LoadSourceState".
protected override void DoLoadSourceState(IVsaPersistSite site)
{
// Nothing to do here - source loading is not supported.
}
// Internal implementation of "SaveCompiledState".
protected override void DoSaveCompiledState
(out byte[] pe, out byte[] debugInfo)
{
// Saving scripts to assembly form is not supported.
throw new VsaException(VsaError.SaveCompiledStateFailed);
}
// Internal implementation of "SaveSourceState".
protected override void DoSaveSourceState(IVsaPersistSite site)
{
// Nothing to do here - source saving is not supported.
}
// Run the compiled script.
internal override void DoRun()
{
if(vsaItems != null)
{
((VsaItems)vsaItems).Run();
}
}
// Get a custom option value.
protected override Object GetCustomOption(String name)
{
// Check options that we understand.
if(String.Compare(name, "detach", true) == 0)
{
return detached;
}
else if(String.Compare(name, "print", true) == 0)
{
return printSupported;
}
// The option was not understood.
throw new VsaException(VsaError.OptionNotSupported);
}
// Determine if a namespace name is valid.
protected override bool IsValidNamespaceName(String name)
{
if(name == null)
{
return false;
}
JSScanner scanner = new JSScanner(name);
if(scanner.FetchIdentifier() == null)
{
return false;
}
while(scanner.Peek() == '.')
{
scanner.Fetch();
if(scanner.FetchIdentifier() == null)
{
return false;
}
}
return (scanner.Fetch() == -1);
}
// Internal implementation of "Reset".
protected override void ResetCompiledState()
{
compiledRootNamespace = null;
failedCompilation = true;
haveCompiledState = false;
((VsaItems)vsaItems).Reset();
isEngineCompiled = false;
isEngineRunning = false;
}
// Set a custom option value.
protected override void SetCustomOption(String name, Object value)
{
// Handle the "detach" option, which allows us to support
// more than one engine instance per process.
if(String.Compare(name, "detach", true) == 0)
{
if(value is Boolean && ((bool)value) && !detached)
{
DetachEngine();
}
return;
}
else if(String.Compare(name, "print", true) == 0)
{
printSupported = (value is Boolean && ((bool)value));
return;
}
// The option is not understood.
throw new VsaException(VsaError.OptionNotSupported);
}
// Validate a root moniker.
protected override void ValidateRootMoniker(String rootMoniker)
{
base.ValidateRootMoniker(rootMoniker);
}
// Implement the IRedirectOutput interface.
public virtual void SetOutputStream(IMessageReceiver output)
{
// Wrap up the receiver to turn it into a stream.
COMCharStream stream = new COMCharStream(output);
StreamWriter writer = new StreamWriter
(stream, Encoding.Default);
// Do a flush after every write operation.
writer.AutoFlush = true;
// Set the stdout and stderr streams for the script.
lock(typeof(VsaEngine))
{
if(Globals.contextEngine != this)
{
// This instance has been detached, so set its
// local output streams.
engineInstance.SetOutputStreams(writer, writer);
}
else
{
#if !CONFIG_SMALL_CONSOLE
// Use the global "ScriptStream" class for the
// default engine instance.
ScriptStream.Out = writer;
ScriptStream.Error = writer;
#endif
}
}
}
// Make a new engine instance and set it up for stand-alone operation.
internal static VsaEngine MakeNewEngine()
{
VsaEngine engine = new VsaEngine(true);
engine.InitVsaEngine
("JScript.Vsa.VsaEngine://Microsoft.JScript.VsaEngine.Vsa",
new ThrowOnErrorVsaSite());
return engine;
}
// Create the primary engine instance.
public static VsaEngine CreateEngine()
{
lock(typeof(VsaEngine))
{
if(primaryEngine == null)
{
primaryEngine = MakeNewEngine();
}
return primaryEngine;
}
}
// Detach this engine from the primary position.
private void DetachEngine()
{
lock(typeof(VsaEngine))
{
if(this == primaryEngine)
{
primaryEngine = null;
}
if(this == Globals.contextEngine)
{
Globals.contextEngine = null;
}
engineInstance.DetachOutputStreams();
detached = true;
}
}
// Create the primary engine instance for a given DLL type.
public static VsaEngine CreateEngineWithType
(RuntimeTypeHandle callingTypeHandle)
{
// Use the primary engine in the current process.
return CreateEngine();
}
// Create an engine and get its global scope.
public static GlobalScope CreateEngineAndGetGlobalScope
(bool fast, String[] AssemblyNames)
{
// We don't support assembly-based JScript executions.
throw new NotSupportedException();
}
// Create an engine and get its global scope.
public static GlobalScope CreateEngineAndGetGlobalScopeWithType
(bool fast, String[] AssemblyNames,
RuntimeTypeHandle callingTypeHandle)
{
// We don't support assembly-based JScript executions.
throw new NotSupportedException();
}
// Initialize a VSA engine in a non-VSA mode manually.
// Use "CreateEngine" instead of this.
public void InitVsaEngine(String rootMoniker, IVsaSite site)
{
rootNamespace = "JScript.DefaultNamespace";
engineMoniker = rootMoniker;
engineSite = site;
isEngineDirty = true;
isEngineCompiled = false;
isEngineInitialized = true;
}
// Get the original constructors for various types.
public ObjectConstructor GetOriginalObjectConstructor()
{
return engineInstance.GetObjectConstructor();
}
public ArrayConstructor GetOriginalArrayConstructor()
{
return engineInstance.GetArrayConstructor();
}
#if false
public RegExpConstructor GetOriginalRegExpConstructor()
{
// TODO
return null;
}
#endif
// Get the lenient global object associated with this engine.
public LenientGlobalObject LenientGlobalObject
{
get
{
return lenientGlobalObject;
}
}
// Push an object onto the script object stack.
public void PushScriptObject(ScriptObject obj)
{
if(scopeStackSize >= scopeStack.Length)
{
Object[] stack = new Object [scopeStackSize + 8];
Array.Copy(scopeStack, 0, stack, 0, scopeStackSize);
scopeStack = stack;
}
scopeStack[scopeStackSize++] = obj;
currentScope = obj;
}
// Push an object onto the script object stack, and check for overflow.
internal void PushScriptObjectChecked(ScriptObject obj)
{
if(scopeStackSize > 500)
{
throw new JScriptException(JSError.OutOfStack);
}
else
{
PushScriptObject(obj);
}
}
// Pop an object from the script object stack.
public ScriptObject PopScriptObject()
{
// Never pop the global object.
if(scopeStackSize > 1)
{
--scopeStackSize;
currentScope = scopeStack[scopeStackSize - 1];
}
return (ScriptObject)currentScope;
}
// Get the object at the top of the script object stack.
public ScriptObject ScriptObjectStackTop()
{
return (ScriptObject)currentScope;
}
// Get the current size of the script object stack.
internal int ScriptObjectStackSize()
{
return scopeStackSize;
}
// Reset the script object stack to a particular size.
internal void ScriptObjectStackSetSize(int size)
{
if(size < scopeStackSize)
{
scopeStackSize = size;
}
}
// Reset the engine.
public override void Reset()
{
// Let the base class do the work.
base.Reset();
}
// Debugger entry point: restart the engine for another expression.
public virtual void Restart()
{
// Nothing to do here - debugging not yet supported.
}
}; // class VsaEngine
}; // namespace Microsoft.JScript.Vsa
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Common;
using Microsoft.WindowsAzure.Common.Internals;
using Microsoft.WindowsAzure.Management.WebSites;
using Microsoft.WindowsAzure.Management.WebSites.Models;
namespace Microsoft.WindowsAzure.Management.WebSites
{
/// <summary>
/// The Web Sites Management API provides a RESTful set of web services
/// that interact with the Windows Azure Web Sites service to manage your
/// web sites. The API has entities that capture the relationship between
/// an end user and Windows Azure Web Sites service. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx for
/// more information)
/// </summary>
public partial class WebSiteManagementClient : ServiceClient<WebSiteManagementClient>, Microsoft.WindowsAzure.Management.WebSites.IWebSiteManagementClient
{
private string _apiVersion;
/// <summary>
/// Gets the API version.
/// </summary>
public string ApiVersion
{
get { return this._apiVersion; }
}
private Uri _baseUri;
/// <summary>
/// Gets the URI used as the base for all cloud service requests.
/// </summary>
public Uri BaseUri
{
get { return this._baseUri; }
}
private SubscriptionCloudCredentials _credentials;
/// <summary>
/// Gets subscription credentials which uniquely identify Microsoft
/// Azure subscription. The subscription ID forms part of the URI for
/// every service call.
/// </summary>
public SubscriptionCloudCredentials Credentials
{
get { return this._credentials; }
}
private int _longRunningOperationInitialTimeout;
/// <summary>
/// Gets or sets the initial timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationInitialTimeout
{
get { return this._longRunningOperationInitialTimeout; }
set { this._longRunningOperationInitialTimeout = value; }
}
private int _longRunningOperationRetryTimeout;
/// <summary>
/// Gets or sets the retry timeout for Long Running Operations.
/// </summary>
public int LongRunningOperationRetryTimeout
{
get { return this._longRunningOperationRetryTimeout; }
set { this._longRunningOperationRetryTimeout = value; }
}
private IWebHostingPlanOperations _webHostingPlans;
/// <summary>
/// Operations for managing web hosting plans beneath your subscription.
/// </summary>
public virtual IWebHostingPlanOperations WebHostingPlans
{
get { return this._webHostingPlans; }
}
private IWebSiteOperations _webSites;
/// <summary>
/// Operations for managing the web sites in a web space. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/dn166981.aspx
/// for more information)
/// </summary>
public virtual IWebSiteOperations WebSites
{
get { return this._webSites; }
}
private IWebSpaceOperations _webSpaces;
/// <summary>
/// Operations for managing web spaces beneath your subscription.
/// </summary>
public virtual IWebSpaceOperations WebSpaces
{
get { return this._webSpaces; }
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
private WebSiteManagementClient()
: base()
{
this._webHostingPlans = new WebHostingPlanOperations(this);
this._webSites = new WebSiteOperations(this);
this._webSpaces = new WebSpaceOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
public WebSiteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
public WebSiteManagementClient(SubscriptionCloudCredentials credentials)
: this()
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='httpClient'>
/// The Http client
/// </param>
private WebSiteManagementClient(HttpClient httpClient)
: base(httpClient)
{
this._webHostingPlans = new WebHostingPlanOperations(this);
this._webSites = new WebSiteOperations(this);
this._webSpaces = new WebSpaceOperations(this);
this._apiVersion = "2014-04-01";
this._longRunningOperationInitialTimeout = -1;
this._longRunningOperationRetryTimeout = -1;
this.HttpClient.Timeout = TimeSpan.FromSeconds(300);
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='baseUri'>
/// Optional. Gets the URI used as the base for all cloud service
/// requests.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public WebSiteManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this._credentials = credentials;
this._baseUri = baseUri;
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Initializes a new instance of the WebSiteManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Gets subscription credentials which uniquely identify
/// Microsoft Azure subscription. The subscription ID forms part of
/// the URI for every service call.
/// </param>
/// <param name='httpClient'>
/// The Http client
/// </param>
public WebSiteManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient)
: this(httpClient)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this._credentials = credentials;
this._baseUri = new Uri("https://management.core.windows.net");
this.Credentials.InitializeServiceClient(this);
}
/// <summary>
/// Clones properties from current instance to another
/// WebSiteManagementClient instance
/// </summary>
/// <param name='client'>
/// Instance of WebSiteManagementClient to clone to
/// </param>
protected override void Clone(ServiceClient<WebSiteManagementClient> client)
{
base.Clone(client);
if (client is WebSiteManagementClient)
{
WebSiteManagementClient clonedClient = ((WebSiteManagementClient)client);
clonedClient._credentials = this._credentials;
clonedClient._baseUri = this._baseUri;
clonedClient._apiVersion = this._apiVersion;
clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout;
clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout;
clonedClient.Credentials.InitializeServiceClient(clonedClient);
}
}
/// <summary>
/// Parse enum values for type ConnectionStringType.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static ConnectionStringType ParseConnectionStringType(string value)
{
if ("0".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ConnectionStringType.MySql;
}
if ("1".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ConnectionStringType.SqlServer;
}
if ("2".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ConnectionStringType.SqlAzure;
}
if ("3".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ConnectionStringType.Custom;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type ConnectionStringType to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string ConnectionStringTypeToString(ConnectionStringType value)
{
if (value == ConnectionStringType.MySql)
{
return "0";
}
if (value == ConnectionStringType.SqlServer)
{
return "1";
}
if (value == ConnectionStringType.SqlAzure)
{
return "2";
}
if (value == ConnectionStringType.Custom)
{
return "3";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Parse enum values for type ManagedPipelineMode.
/// </summary>
/// <param name='value'>
/// The value to parse.
/// </param>
/// <returns>
/// The enum value.
/// </returns>
internal static ManagedPipelineMode ParseManagedPipelineMode(string value)
{
if ("0".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ManagedPipelineMode.Integrated;
}
if ("1".Equals(value, StringComparison.OrdinalIgnoreCase))
{
return ManagedPipelineMode.Classic;
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// Convert an enum of type ManagedPipelineMode to a string.
/// </summary>
/// <param name='value'>
/// The value to convert to a string.
/// </param>
/// <returns>
/// The enum value as a string.
/// </returns>
internal static string ManagedPipelineModeToString(ManagedPipelineMode value)
{
if (value == ManagedPipelineMode.Integrated)
{
return "0";
}
if (value == ManagedPipelineMode.Classic)
{
return "1";
}
throw new ArgumentOutOfRangeException("value");
}
/// <summary>
/// The Get Operation Status operation returns the status of the
/// specified operation. After calling a long-running operation, you
/// can call Get Operation Status to determine whether the operation
/// has succeeded, failed, timed out, or is still in progress. (see
/// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx
/// for more information)
/// </summary>
/// <param name='webSpaceName'>
/// Required. The name of the webspace for the website where the
/// operation was targeted.
/// </param>
/// <param name='siteName'>
/// Required. The name of the site where the operation was targeted.
/// </param>
/// <param name='operationId'>
/// Required. The operation ID for the operation you wish to track. The
/// operation ID is returned in the ID field in the body of the
/// response for long-running operations.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response body contains the status of the specified long-running
/// operation, indicating whether it has succeeded, is inprogress, has
/// timed out, or has failed. Note that this status is distinct from
/// the HTTP status code returned for the Get Operation Status
/// operation itself. If the long-running operation failed, the
/// response body includes error information regarding the failure.
/// </returns>
public async System.Threading.Tasks.Task<Microsoft.WindowsAzure.Management.WebSites.Models.WebSiteOperationStatusResponse> GetOperationStatusAsync(string webSpaceName, string siteName, string operationId, CancellationToken cancellationToken)
{
// Validate
if (webSpaceName == null)
{
throw new ArgumentNullException("webSpaceName");
}
if (siteName == null)
{
throw new ArgumentNullException("siteName");
}
if (operationId == null)
{
throw new ArgumentNullException("operationId");
}
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("webSpaceName", webSpaceName);
tracingParameters.Add("siteName", siteName);
tracingParameters.Add("operationId", operationId);
Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services/WebSpaces/" + webSpaceName.Trim() + "/sites/" + siteName.Trim() + "/operations/" + operationId.Trim();
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
WebSiteOperationStatusResponse result = null;
// Deserialize Response
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new WebSiteOperationStatusResponse();
XDocument responseDoc = XDocument.Parse(responseContent);
XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure"));
if (operationElement != null)
{
XElement createdTimeElement = operationElement.Element(XName.Get("CreatedTime", "http://schemas.microsoft.com/windowsazure"));
if (createdTimeElement != null)
{
DateTime createdTimeInstance = DateTime.Parse(createdTimeElement.Value, CultureInfo.InvariantCulture);
result.CreatedTime = createdTimeInstance;
}
XElement errorsSequenceElement = operationElement.Element(XName.Get("Errors", "http://schemas.microsoft.com/windowsazure"));
if (errorsSequenceElement != null)
{
bool isNil = false;
XAttribute nilAttribute = errorsSequenceElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute != null)
{
isNil = nilAttribute.Value == "true";
}
if (isNil == false)
{
foreach (XElement errorsElement in errorsSequenceElement.Elements(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")))
{
WebSiteOperationStatusResponse.Error errorInstance = new WebSiteOperationStatusResponse.Error();
result.Errors.Add(errorInstance);
XElement codeElement = errorsElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure"));
if (codeElement != null)
{
bool isNil2 = false;
XAttribute nilAttribute2 = codeElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute2 != null)
{
isNil2 = nilAttribute2.Value == "true";
}
if (isNil2 == false)
{
string codeInstance = codeElement.Value;
errorInstance.Code = codeInstance;
}
}
XElement messageElement = errorsElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure"));
if (messageElement != null)
{
bool isNil3 = false;
XAttribute nilAttribute3 = messageElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute3 != null)
{
isNil3 = nilAttribute3.Value == "true";
}
if (isNil3 == false)
{
string messageInstance = messageElement.Value;
errorInstance.Message = messageInstance;
}
}
XElement extendedCodeElement = errorsElement.Element(XName.Get("ExtendedCode", "http://schemas.microsoft.com/windowsazure"));
if (extendedCodeElement != null)
{
bool isNil4 = false;
XAttribute nilAttribute4 = extendedCodeElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute4 != null)
{
isNil4 = nilAttribute4.Value == "true";
}
if (isNil4 == false)
{
string extendedCodeInstance = extendedCodeElement.Value;
errorInstance.ExtendedCode = extendedCodeInstance;
}
}
XElement messageTemplateElement = errorsElement.Element(XName.Get("MessageTemplate", "http://schemas.microsoft.com/windowsazure"));
if (messageTemplateElement != null)
{
bool isNil5 = false;
XAttribute nilAttribute5 = messageTemplateElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute5 != null)
{
isNil5 = nilAttribute5.Value == "true";
}
if (isNil5 == false)
{
string messageTemplateInstance = messageTemplateElement.Value;
errorInstance.MessageTemplate = messageTemplateInstance;
}
}
XElement parametersSequenceElement = errorsElement.Element(XName.Get("Parameters", "http://schemas.microsoft.com/windowsazure"));
if (parametersSequenceElement != null)
{
bool isNil6 = false;
XAttribute nilAttribute6 = parametersSequenceElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute6 != null)
{
isNil6 = nilAttribute6.Value == "true";
}
if (isNil6 == false)
{
foreach (XElement parametersElement in parametersSequenceElement.Elements(XName.Get("string", "http://schemas.microsoft.com/2003/10/Serialization/Arrays")))
{
errorInstance.Parameters.Add(parametersElement.Value);
}
}
else
{
errorInstance.Parameters = null;
}
}
XElement innerErrorsElement = errorsElement.Element(XName.Get("InnerErrors", "http://schemas.microsoft.com/windowsazure"));
if (innerErrorsElement != null)
{
bool isNil7 = false;
XAttribute nilAttribute7 = innerErrorsElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute7 != null)
{
isNil7 = nilAttribute7.Value == "true";
}
if (isNil7 == false)
{
string innerErrorsInstance = innerErrorsElement.Value;
errorInstance.InnerErrors = innerErrorsInstance;
}
}
}
}
else
{
result.Errors = null;
}
}
XElement expirationTimeElement = operationElement.Element(XName.Get("ExpirationTime", "http://schemas.microsoft.com/windowsazure"));
if (expirationTimeElement != null)
{
DateTime expirationTimeInstance = DateTime.Parse(expirationTimeElement.Value, CultureInfo.InvariantCulture);
result.ExpirationTime = expirationTimeInstance;
}
XElement geoMasterOperationIdElement = operationElement.Element(XName.Get("GeoMasterOperationId", "http://schemas.microsoft.com/windowsazure"));
if (geoMasterOperationIdElement != null)
{
bool isNil8 = false;
XAttribute nilAttribute8 = geoMasterOperationIdElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute8 != null)
{
isNil8 = nilAttribute8.Value == "true";
}
if (isNil8 == false)
{
string geoMasterOperationIdInstance = geoMasterOperationIdElement.Value;
result.GeoMasterOperationId = geoMasterOperationIdInstance;
}
}
XElement idElement = operationElement.Element(XName.Get("Id", "http://schemas.microsoft.com/windowsazure"));
if (idElement != null)
{
bool isNil9 = false;
XAttribute nilAttribute9 = idElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute9 != null)
{
isNil9 = nilAttribute9.Value == "true";
}
if (isNil9 == false)
{
string idInstance = idElement.Value;
result.OperationId = idInstance;
}
}
XElement modifiedTimeElement = operationElement.Element(XName.Get("ModifiedTime", "http://schemas.microsoft.com/windowsazure"));
if (modifiedTimeElement != null)
{
DateTime modifiedTimeInstance = DateTime.Parse(modifiedTimeElement.Value, CultureInfo.InvariantCulture);
result.ModifiedTime = modifiedTimeInstance;
}
XElement nameElement = operationElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure"));
if (nameElement != null)
{
bool isNil10 = false;
XAttribute nilAttribute10 = nameElement.Attribute(XName.Get("nil", "http://www.w3.org/2001/XMLSchema-instance"));
if (nilAttribute10 != null)
{
isNil10 = nilAttribute10.Value == "true";
}
if (isNil10 == false)
{
string nameInstance = nameElement.Value;
result.Name = nameInstance;
}
}
XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure"));
if (statusElement != null)
{
WebSiteOperationStatus statusInstance = ((WebSiteOperationStatus)Enum.Parse(typeof(WebSiteOperationStatus), statusElement.Value, true));
result.Status = statusInstance;
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Register your subscription to use Azure Web Sites.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> RegisterSubscriptionAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "RegisterSubscriptionAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services?";
url = url + "service=website";
url = url + "&action=register";
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Unregister your subscription to use Azure Web Sites.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// A standard service response including an HTTP status code and
/// request ID.
/// </returns>
public async System.Threading.Tasks.Task<OperationResponse> UnregisterSubscriptionAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = Tracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
Tracing.Enter(invocationId, this, "UnregisterSubscriptionAsync", tracingParameters);
}
// Construct URL
string url = "/" + (this.Credentials.SubscriptionId != null ? this.Credentials.SubscriptionId.Trim() : "") + "/services?";
url = url + "service=website";
url = url + "&action=unregister";
string baseUrl = this.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Put;
httpRequest.RequestUri = new Uri(url);
// Set Headers
httpRequest.Headers.Add("x-ms-version", "2014-04-01");
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
Tracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
Tracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.Accepted)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
Tracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
OperationResponse result = null;
result = new OperationResponse();
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
Tracing.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
namespace UIWidgets {
/// <summary>
/// Color picker input mode.
/// None - Don't display sliders
/// RGB - Display RGB sliders
/// HSV - Display HSV sliders
/// </summary>
public enum ColorPickerInputMode {
None = -1,
RGB = 0,
HSV = 1,
}
/// <summary>
/// Color picker palette mode.
/// Specified value used in vertical slider, others used in palette.
/// None - None.
/// Red - Red.
/// Green - Green.
/// Blue - Blue.
/// Hue - Hue.
/// Saturation - Saturation.
/// Value - Value.
/// </summary>
public enum ColorPickerPaletteMode {
None = -1,
Red = 0,
Green = 1,
Blue = 2,
Hue = 3,
Saturation = 4,
Value = 5,
}
/// <summary>
/// Color RGB changed event.
/// </summary>
[System.Serializable]
public class ColorRGBChangedEvent : UnityEvent<Color32> {
}
/// <summary>
/// Color HSV changed event.
/// </summary>
[System.Serializable]
public class ColorHSVChangedEvent : UnityEvent<ColorHSV> {
}
/// <summary>
/// Color alpha changed event.
/// </summary>
[System.Serializable]
public class ColorAlphaChangedEvent : UnityEvent<byte> {
}
/// <summary>
/// ColorPicker.
/// </summary>
[AddComponentMenu("UI/UIWidgets/ColorPicker")]
public class ColorPicker : MonoBehaviour {
/// <summary>
/// Value limit in HSV gradients.
/// </summary>
public const int ValueLimit = 80;
[SerializeField]
ColorPickerRGBPalette rgbPalette;
/// <summary>
/// Gets or sets the RGB palette.
/// </summary>
/// <value>The RGB palette.</value>
public ColorPickerRGBPalette RGBPalette {
get {
return rgbPalette;
}
set {
if (rgbPalette!=null)
{
rgbPalette.OnChangeRGB.RemoveListener(ColorRGBChanged);
}
rgbPalette = value;
if (rgbPalette!=null)
{
rgbPalette.OnChangeRGB.AddListener(ColorRGBChanged);
}
}
}
[SerializeField]
ColorPickerRGBBlock rgbBlock;
/// <summary>
/// Gets or sets the RGB sliders block.
/// </summary>
/// <value>The RGB sliders block.</value>
public ColorPickerRGBBlock RGBBlock {
get {
return rgbBlock;
}
set {
if (rgbBlock!=null)
{
rgbBlock.OnChangeRGB.RemoveListener(ColorRGBChanged);
}
rgbBlock = value;
if (rgbBlock!=null)
{
rgbBlock.OnChangeRGB.AddListener(ColorRGBChanged);
}
}
}
[SerializeField]
ColorPickerHSVPalette hsvPalette;
/// <summary>
/// Gets or sets the HSV palette.
/// </summary>
/// <value>The HSV palette.</value>
public ColorPickerHSVPalette HSVPalette {
get {
return hsvPalette;
}
set {
if (hsvPalette!=null)
{
hsvPalette.OnChangeHSV.RemoveListener(ColorHSVChanged);
}
hsvPalette = value;
if (hsvPalette!=null)
{
hsvPalette.OnChangeHSV.AddListener(ColorHSVChanged);
}
}
}
[SerializeField]
ColorPickerHSVBlock hsvBlock;
/// <summary>
/// Gets or sets the HSV sliders block.
/// </summary>
/// <value>The HSV sliders block.</value>
public ColorPickerHSVBlock HSVBlock {
get {
return hsvBlock;
}
set {
if (hsvBlock!=null)
{
hsvBlock.OnChangeHSV.RemoveListener(ColorHSVChanged);
}
hsvBlock = value;
if (hsvBlock!=null)
{
hsvBlock.OnChangeHSV.AddListener(ColorHSVChanged);
}
}
}
[SerializeField]
ColorPickerABlock aBlock;
/// <summary>
/// Gets or sets Alpha slider block.
/// </summary>
/// <value>Alpha slider block.</value>
public ColorPickerABlock ABlock {
get {
return aBlock;
}
set {
if (aBlock!=null)
{
aBlock.OnChangeAlpha.RemoveListener(ColorAlphaChanged);
}
aBlock = value;
if (aBlock!=null)
{
aBlock.OnChangeAlpha.AddListener(ColorAlphaChanged);
}
}
}
[SerializeField]
ColorPickerColorBlock colorView;
/// <summary>
/// Gets or sets the color view.
/// </summary>
/// <value>The color view.</value>
public ColorPickerColorBlock ColorView {
get {
return colorView;
}
set {
colorView = value;
if (colorView!=null)
{
colorView.SetColor(color);
}
}
}
[SerializeField]
ColorPickerInputMode inputMode;
/// <summary>
/// Gets or sets the input mode.
/// </summary>
/// <value>The input mode.</value>
public ColorPickerInputMode InputMode {
get {
return inputMode;
}
set {
inputMode = value;
if (rgbPalette!=null)
{
rgbPalette.InputMode = inputMode;
}
if (hsvPalette!=null)
{
hsvPalette.InputMode = inputMode;
}
if (rgbBlock!=null)
{
rgbBlock.InputMode = inputMode;
}
if (hsvBlock!=null)
{
hsvBlock.InputMode = inputMode;
}
if (aBlock!=null)
{
aBlock.InputMode = inputMode;
}
}
}
[SerializeField]
ColorPickerPaletteMode paletteMode;
/// <summary>
/// Gets or sets the palette mode.
/// </summary>
/// <value>The palette mode.</value>
public ColorPickerPaletteMode PaletteMode {
get {
return paletteMode;
}
set {
paletteMode = value;
if (rgbPalette!=null)
{
rgbPalette.PaletteMode = paletteMode;
}
if (hsvPalette!=null)
{
hsvPalette.PaletteMode = paletteMode;
}
if (rgbBlock!=null)
{
rgbBlock.PaletteMode = paletteMode;
}
if (hsvBlock!=null)
{
hsvBlock.PaletteMode = paletteMode;
}
if (aBlock!=null)
{
aBlock.PaletteMode = paletteMode;
}
}
}
[SerializeField]
Color32 color = new Color32(255, 255, 255, 255);
/// <summary>
/// Gets or sets the color32.
/// </summary>
/// <value>The color32.</value>
public Color32 Color32 {
get {
return color;
}
set {
color = value;
UpdateBlocks(color);
OnChange.Invoke(color);
}
}
/// <summary>
/// Gets or sets the color.
/// </summary>
/// <value>The color.</value>
public Color Color {
get {
return Color32;
}
set {
Color32 = value;
}
}
/// <summary>
/// OnChange color event.
/// </summary>
public ColorRGBChangedEvent OnChange = new ColorRGBChangedEvent();
/// <summary>
/// Start this instance.
/// </summary>
public void Start()
{
if (rgbPalette!=null)
{
RGBPalette = rgbPalette;
rgbPalette.Start();
}
if (hsvPalette!=null)
{
HSVPalette = hsvPalette;
hsvPalette.Start();
}
if (rgbBlock!=null)
{
RGBBlock = rgbBlock;
rgbBlock.Start();
}
if (hsvBlock!=null)
{
HSVBlock = hsvBlock;
hsvBlock.Start();
}
if (aBlock!=null)
{
ABlock = aBlock;
aBlock.Start();
}
InputMode = inputMode;
PaletteMode = paletteMode;
UpdateBlocks(color);
}
void OnEnable()
{
UpdateBlocks(color);
}
void ColorRGBChanged(Color32 newColor)
{
color = newColor;
UpdateBlocks(color);
OnChange.Invoke(color);
}
void ColorHSVChanged(ColorHSV newColor)
{
color = newColor;
UpdateBlocks(newColor);
OnChange.Invoke(color);
}
void ColorAlphaChanged(byte alpha)
{
color.a = alpha;
if (aBlock!=null)
{
aBlock.SetColor(color);
}
if (colorView!=null)
{
colorView.SetColor(color);
}
OnChange.Invoke(color);
}
void UpdateBlocks(Color32 newColor)
{
if (colorView!=null)
{
colorView.SetColor(newColor);
}
if (rgbPalette!=null)
{
rgbPalette.SetColor(newColor);
}
if (hsvPalette!=null)
{
hsvPalette.SetColor(newColor);
}
if (rgbBlock!=null)
{
rgbBlock.SetColor(newColor);
}
if (hsvBlock!=null)
{
hsvBlock.SetColor(newColor);
}
if (aBlock!=null)
{
aBlock.SetColor(newColor);
}
}
void UpdateBlocks(ColorHSV newColor)
{
if (colorView!=null)
{
colorView.SetColor(newColor);
}
if (rgbPalette!=null)
{
rgbPalette.SetColor(newColor);
}
if (hsvPalette!=null)
{
hsvPalette.SetColor(newColor);
}
if (hsvBlock!=null)
{
hsvBlock.SetColor(newColor);
}
if (rgbBlock!=null)
{
rgbBlock.SetColor(newColor);
}
if (aBlock!=null)
{
aBlock.SetColor(newColor);
}
}
/// <summary>
/// Toggles the input mode.
/// </summary>
public void ToggleInputMode()
{
InputMode = (InputMode==ColorPickerInputMode.RGB)
? ColorPickerInputMode.HSV
: ColorPickerInputMode.RGB;
}
static List<ColorPickerPaletteMode> rgbPaletteModes = new List<ColorPickerPaletteMode>() {
ColorPickerPaletteMode.Red,
ColorPickerPaletteMode.Green,
ColorPickerPaletteMode.Blue,
};
static List<ColorPickerPaletteMode> hsvPaletteModes = new List<ColorPickerPaletteMode>() {
ColorPickerPaletteMode.Hue,
ColorPickerPaletteMode.Saturation,
ColorPickerPaletteMode.Value,
};
/// <summary>
/// Toggles the palette mode.
/// </summary>
public void TogglePaletteMode()
{
var paletteModes = new List<ColorPickerPaletteMode>();
if (rgbPalette!=null)
{
paletteModes.AddRange(rgbPaletteModes);
}
if (hsvPalette!=null)
{
paletteModes.AddRange(hsvPaletteModes);
}
if (paletteModes.Count==0)
{
return ;
}
var next_index = paletteModes.IndexOf(PaletteMode) + 1;
if (next_index==paletteModes.Count)
{
next_index = 0;
}
PaletteMode = paletteModes[next_index];
}
void OnDestroy()
{
RGBPalette = null;
HSVPalette = null;
RGBBlock = null;
HSVBlock = null;
ABlock = null;
ColorView = null;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.Rest.Generator.ClientModel;
using Microsoft.Rest.Generator.Logging;
using Microsoft.Rest.Generator.Utilities;
using Microsoft.Rest.Modeler.Swagger.Model;
using Microsoft.Rest.Modeler.Swagger.Properties;
using ParameterLocation = Microsoft.Rest.Modeler.Swagger.Model.ParameterLocation;
namespace Microsoft.Rest.Modeler.Swagger
{
/// <summary>
/// The builder for building swagger operations into client model methods.
/// </summary>
public class OperationBuilder
{
private IList<string> _effectiveProduces;
private IList<string> _effectiveConsumes;
private SwaggerModeler _swaggerModeler;
private Operation _operation;
private const string APP_JSON_MIME = "application/json";
public OperationBuilder(Operation operation, SwaggerModeler swaggerModeler)
{
if (operation == null)
{
throw new ArgumentNullException("operation");
}
if (swaggerModeler == null)
{
throw new ArgumentNullException("swaggerModeler");
}
this._operation = operation;
this._swaggerModeler = swaggerModeler;
this._effectiveProduces = operation.Produces.Any() ? operation.Produces : swaggerModeler.ServiceDefinition.Produces;
this._effectiveConsumes = operation.Consumes.Any() ? operation.Consumes : swaggerModeler.ServiceDefinition.Consumes;
}
public Method BuildMethod(HttpMethod httpMethod, string url, string methodName, string methodGroup)
{
EnsureUniqueMethodName(methodName, methodGroup);
var method = new Method
{
HttpMethod = httpMethod,
Url = url,
Name = methodName,
SerializedName = _operation.OperationId
};
method.RequestContentType = _effectiveConsumes.FirstOrDefault() ?? APP_JSON_MIME;
string produce = _effectiveConsumes.FirstOrDefault(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(produce))
{
method.RequestContentType = produce;
}
if (method.RequestContentType.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase) &&
method.RequestContentType.IndexOf("charset=", StringComparison.OrdinalIgnoreCase) == -1)
{
// Enable UTF-8 charset
method.RequestContentType += "; charset=utf-8";
}
method.Description = _operation.Description;
method.Summary = _operation.Summary;
method.ExternalDocsUrl = _operation.ExternalDocs?.Url;
// Service parameters
if (_operation.Parameters != null)
{
BuildMethodParameters(method);
}
// Build header object
var responseHeaders = new Dictionary<string, Header>();
foreach (var response in _operation.Responses.Values)
{
if (response.Headers != null)
{
response.Headers.ForEach(h => responseHeaders[h.Key] = h.Value);
}
}
var headerTypeName = string.Format(CultureInfo.InvariantCulture,
"{0}-{1}-Headers", methodGroup, methodName).Trim('-');
var headerType = new CompositeType
{
Name = headerTypeName,
SerializedName = headerTypeName,
Documentation = string.Format(CultureInfo.InvariantCulture, "Defines headers for {0} operation.", methodName)
};
responseHeaders.ForEach(h =>
{
var property = new Property
{
Name = h.Key,
SerializedName = h.Key,
Type = h.Value.GetBuilder(this._swaggerModeler).BuildServiceType(h.Key),
Documentation = h.Value.Description
};
headerType.Properties.Add(property);
});
if (!headerType.Properties.Any())
{
headerType = null;
}
// Response format
List<Stack<IType>> typesList = BuildResponses(method, headerType);
method.ReturnType = BuildMethodReturnType(typesList, headerType);
if (method.Responses.Count == 0)
{
method.ReturnType = method.DefaultResponse;
}
if (method.ReturnType.Headers != null)
{
_swaggerModeler.ServiceClient.HeaderTypes.Add(method.ReturnType.Headers as CompositeType);
}
// Copy extensions
_operation.Extensions.ForEach(extention => method.Extensions.Add(extention.Key, extention.Value));
return method;
}
private static IEnumerable<SwaggerParameter> DeduplicateParameters(IEnumerable<SwaggerParameter> parameters)
{
return parameters
.Select(s =>
{
// if parameter with the same name exists in Body and Path/Query then we need to give it a unique name
if (s.In == ParameterLocation.Body)
{
string newName = s.Name;
while (parameters.Any(t => t.In != ParameterLocation.Body &&
string.Equals(t.Name, newName,
StringComparison.OrdinalIgnoreCase)))
{
newName += "Body";
}
s.Name = newName;
}
// if parameter with same name exists in Query and Path, make Query one required
if (s.In == ParameterLocation.Query &&
parameters.Any(t => t.In == ParameterLocation.Path &&
string.Equals(t.Name, s.Name, StringComparison.OrdinalIgnoreCase)))
{
s.IsRequired = true;
}
return s;
});
}
private static void BuildMethodReturnTypeStack(IType type, List<Stack<IType>> types)
{
var typeStack = new Stack<IType>();
typeStack.Push(type);
types.Add(typeStack);
}
private void BuildMethodParameters(Method method)
{
foreach (var swaggerParameter in DeduplicateParameters(_operation.Parameters))
{
var parameter = ((ParameterBuilder)swaggerParameter.GetBuilder(_swaggerModeler)).Build();
method.Parameters.Add(parameter);
StringBuilder parameterName = new StringBuilder(parameter.Name);
parameterName = CollectionFormatBuilder.OnBuildMethodParameter(method, swaggerParameter,
parameterName);
if (swaggerParameter.In == ParameterLocation.Header)
{
method.RequestHeaders[swaggerParameter.Name] =
string.Format(CultureInfo.InvariantCulture, "{{{0}}}", parameterName);
}
}
}
private List<Stack<IType>> BuildResponses(Method method, CompositeType headerType)
{
string methodName = method.Name;
var typesList = new List<Stack<IType>>();
foreach (var response in _operation.Responses)
{
if (string.Equals(response.Key, "default", StringComparison.OrdinalIgnoreCase))
{
TryBuildDefaultResponse(methodName, response.Value, method, headerType);
}
else
{
if (
!(TryBuildResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType) ||
TryBuildStreamResponse(response.Key.ToHttpStatusCode(), response.Value, method, typesList, headerType) ||
TryBuildEmptyResponse(methodName, response.Key.ToHttpStatusCode(), response.Value, method,
typesList, headerType)))
{
throw new InvalidOperationException(
string.Format(CultureInfo.InvariantCulture,
Resources.UnsupportedMimeTypeForResponseBody,
methodName,
response.Key));
}
}
}
return typesList;
}
private Response BuildMethodReturnType(List<Stack<IType>> types, IType headerType)
{
IType baseType = new PrimaryType(KnownPrimaryType.Object);
// Return null if no response is specified
if (types.Count == 0)
{
return new Response(null, headerType);
}
// Return first if only one return type
if (types.Count == 1)
{
return new Response(types.First().Pop(), headerType);
}
// BuildParameter up type inheritance tree
types.ForEach(typeStack =>
{
IType type = typeStack.Peek();
while (!Equals(type, baseType))
{
if (type is CompositeType && _swaggerModeler.ExtendedTypes.ContainsKey(type.Name))
{
type = _swaggerModeler.GeneratedTypes[_swaggerModeler.ExtendedTypes[type.Name]];
}
else
{
type = baseType;
}
typeStack.Push(type);
}
});
// Eliminate commonly shared base classes
while (!types.First().IsNullOrEmpty())
{
IType currentType = types.First().Peek();
foreach (var typeStack in types)
{
IType t = typeStack.Pop();
if (!Equals(t, currentType))
{
return new Response(baseType, headerType);
}
}
baseType = currentType;
}
return new Response(baseType, headerType);
}
private bool TryBuildStreamResponse(HttpStatusCode responseStatusCode, OperationResponse response,
Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (SwaggerOperationProducesNotEmpty())
{
if (response.Schema != null)
{
IType serviceType = response.Schema.GetBuilder(_swaggerModeler)
.BuildServiceType(response.Schema.Reference.StripDefinitionPath());
Debug.Assert(serviceType != null);
BuildMethodReturnTypeStack(serviceType, types);
var compositeType = serviceType as CompositeType;
if (compositeType != null)
{
VerifyFirstPropertyIsByteArray(compositeType);
}
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
handled = true;
}
}
return handled;
}
private void VerifyFirstPropertyIsByteArray(CompositeType serviceType)
{
var referenceKey = serviceType.Name;
var responseType = _swaggerModeler.GeneratedTypes[referenceKey];
var property = responseType.Properties.FirstOrDefault(p => p.Type is PrimaryType && ((PrimaryType)p.Type).Type == KnownPrimaryType.ByteArray);
if (property == null)
{
throw new KeyNotFoundException(
"Please specify a field with type of System.Byte[] to deserialize the file contents to");
}
}
private bool TryBuildResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
IType serviceType;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response,
s => GenerateResponseObjectName(s, responseStatusCode), out serviceType))
{
method.Responses[responseStatusCode] = new Response(serviceType, headerType);
BuildMethodReturnTypeStack(serviceType, types);
handled = true;
}
}
return handled;
}
private bool TryBuildEmptyResponse(string methodName, HttpStatusCode responseStatusCode,
OperationResponse response, Method method, List<Stack<IType>> types, IType headerType)
{
bool handled = false;
if (response.Schema == null)
{
method.Responses[responseStatusCode] = new Response(null, headerType);
handled = true;
}
else
{
if (_operation.Produces.IsNullOrEmpty())
{
method.Responses[responseStatusCode] = new Response(new PrimaryType(KnownPrimaryType.Object), headerType);
BuildMethodReturnTypeStack(new PrimaryType(KnownPrimaryType.Object), types);
handled = true;
}
var unwrapedSchemaProperties =
_swaggerModeler.Resolver.Unwrap(response.Schema).Properties;
if (unwrapedSchemaProperties != null && unwrapedSchemaProperties.Any())
{
Logger.LogWarning(Resources.NoProduceOperationWithBody,
methodName);
}
}
return handled;
}
private void TryBuildDefaultResponse(string methodName, OperationResponse response, Method method, IType headerType)
{
IType errorModel = null;
if (SwaggerOperationProducesJson())
{
if (TryBuildResponseBody(methodName, response, s => GenerateErrorModelName(s), out errorModel))
{
method.DefaultResponse = new Response(errorModel, headerType);
}
}
}
private bool TryBuildResponseBody(string methodName, OperationResponse response,
Func<string, string> typeNamer, out IType responseType)
{
bool handled = false;
responseType = null;
if (SwaggerOperationProducesJson())
{
if (response.Schema != null)
{
string referenceKey;
if (response.Schema.Reference != null)
{
referenceKey = response.Schema.Reference.StripDefinitionPath();
response.Schema.Reference = referenceKey;
}
else
{
referenceKey = typeNamer(methodName);
}
responseType = response.Schema.GetBuilder(_swaggerModeler).BuildServiceType(referenceKey);
handled = true;
}
}
return handled;
}
private bool SwaggerOperationProducesJson()
{
return _effectiveProduces != null &&
_effectiveProduces.Any(s => s.StartsWith(APP_JSON_MIME, StringComparison.OrdinalIgnoreCase));
}
private bool SwaggerOperationProducesNotEmpty()
{
return _effectiveProduces != null
&& _effectiveProduces.Any();
}
private void EnsureUniqueMethodName(string methodName, string methodGroup)
{
string serviceOperationPrefix = "";
if (methodGroup != null)
{
serviceOperationPrefix = methodGroup + "_";
}
if (_swaggerModeler.ServiceClient.Methods.Any(m => m.Group == methodGroup && m.Name == methodName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture,
Resources.DuplicateOperationIdException,
serviceOperationPrefix + methodName));
}
}
private static string GenerateResponseObjectName(string methodName, HttpStatusCode responseStatusCode)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}{1}Response", methodName, responseStatusCode);
}
private static string GenerateErrorModelName(string methodName)
{
return string.Format(CultureInfo.InvariantCulture,
"{0}ErrorModel", methodName);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2015 Charlie Poole, Rob Prouse
//
// 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 NUnit.Framework.Interfaces;
using NUnit.Framework.Internal;
using NUnit.TestData.TestCaseAttributeFixture;
using NUnit.TestUtilities;
#if ASYNC
using System.Threading.Tasks;
#endif
#if NET_4_0
using Task = System.Threading.Tasks.TaskEx;
#endif
namespace NUnit.Framework.Attributes
{
[TestFixture]
public class TestCaseAttributeTests
{
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void IntegerDivisionWithResultPassedToTest(int n, int d, int q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int IntegerDivisionWithResultCheckedByNUnit(int n, int d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult=4)]
public double CanConvertIntToDouble(double x, double y)
{
return x + y;
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal CanConvertStringToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal CanConvertDoubleToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal CanConvertIntToDecimal(decimal x, decimal y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short CanConvertSmallIntsToShort(short x, short y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte CanConvertSmallIntsToByte(byte x, byte y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte CanConvertSmallIntsToSByte(sbyte x, sbyte y)
{
return (sbyte)(x + y);
}
[TestCase("MethodCausesConversionOverflow", RunState.NotRunnable)]
[TestCase("VoidTestCaseWithExpectedResult", RunState.NotRunnable)]
[TestCase("TestCaseWithNullableReturnValueAndNullExpectedResult", RunState.Runnable)]
public void TestCaseRunnableState(string methodName, RunState expectedState)
{
var test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), methodName).Tests[0];
Assert.AreEqual(expectedState, test.RunState);
}
[TestCase("12-October-1942")]
public void CanConvertStringToDateTime(DateTime dt)
{
Assert.AreEqual(1942, dt.Year);
}
[TestCase("4:44:15")]
public void CanConvertStringToTimeSpan(TimeSpan ts)
{
Assert.AreEqual(4, ts.Hours);
Assert.AreEqual(44, ts.Minutes);
Assert.AreEqual(15, ts.Seconds);
}
[TestCase(null)]
public void CanPassNullAsFirstArgument(object a)
{
Assert.IsNull(a);
}
[TestCase(new object[] { 1, "two", 3.0 })]
[TestCase(new object[] { "zip" })]
public void CanPassObjectArrayAsFirstArgument(object[] a)
{
}
[TestCase(new object[] { "a", "b" })]
public void CanPassArrayAsArgument(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a", "b")]
public void ArgumentsAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(1, "b")]
public void ArgumentsOfDifferentTypeAreCoalescedInObjectArray(object[] array)
{
Assert.AreEqual(1, array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase(ExpectedResult = null)]
public object ResultCanBeNull()
{
return null;
}
[TestCase("a", "b")]
public void HandlesParamsArrayAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
Assert.AreEqual("b", array[1]);
}
[TestCase("a")]
public void HandlesParamsArrayWithOneItemAsSoleArgument(params string[] array)
{
Assert.AreEqual("a", array[0]);
}
[TestCase("a", "b", "c", "d")]
public void HandlesParamsArrayAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
Assert.AreEqual("d", array[1]);
}
[TestCase("a", "b")]
public void HandlesParamsArrayWithNoItemsAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual(0, array.Length);
}
[TestCase("a", "b", "c")]
public void HandlesParamsArrayWithOneItemAsLastArgument(string s1, string s2, params object[] array)
{
Assert.AreEqual("a", s1);
Assert.AreEqual("b", s2);
Assert.AreEqual("c", array[0]);
}
[TestCase("x", ExpectedResult = new []{"x", "b", "c"})]
[TestCase("x", "y", ExpectedResult = new[] { "x", "y", "c" })]
[TestCase("x", "y", "z", ExpectedResult = new[] { "x", "y", "z" })]
public string[] HandlesOptionalArguments(string s1, string s2 = "b", string s3 = "c")
{
return new[] {s1, s2, s3};
}
[TestCase(ExpectedResult = new []{"a", "b"})]
[TestCase("x", ExpectedResult = new[] { "x", "b" })]
[TestCase("x", "y", ExpectedResult = new[] { "x", "y" })]
public string[] HandlesAllOptionalArguments(string s1 = "a", string s2 = "b")
{
return new[] {s1, s2};
}
[TestCase("a", "b", Explicit = true)]
public void ShouldNotRunAndShouldNotFailInConsoleRunner()
{
Assert.Fail();
}
[Test]
public void CanSpecifyDescription()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasDescriptionSpecified").Tests[0];
Assert.AreEqual("My Description", test.Properties.Get(PropertyNames.Description));
}
[Test]
public void CanSpecifyTestName_FixedText()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_FixedText").Tests[0];
Assert.AreEqual("XYZ", test.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture.XYZ", test.FullName);
}
[Test]
public void CanSpecifyTestName_WithMethodName()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasTestNameSpecified_WithMethodName").Tests[0];
var expectedName = "MethodHasTestNameSpecified_WithMethodName+XYZ";
Assert.AreEqual(expectedName, test.Name);
Assert.AreEqual("NUnit.TestData.TestCaseAttributeFixture.TestCaseAttributeFixture." + expectedName, test.FullName);
}
[Test]
public void CanSpecifyCategory()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasSingleCategory").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "XYZ" }, categories);
}
[Test]
public void CanSpecifyMultipleCategories()
{
Test test = (Test)TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodHasMultipleCategories").Tests[0];
IList categories = test.Properties["Category"];
Assert.AreEqual(new string[] { "X", "Y", "Z" }, categories);
}
[Test]
public void CanIgnoreIndividualTestCases()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithIgnoredTestCases");
Test testCase = TestFinder.Find("MethodWithIgnoredTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
testCase = TestFinder.Find("MethodWithIgnoredTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Ignored));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Don't Run Me!"));
}
[Test]
public void CanMarkIndividualTestCasesExplicit()
{
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithExplicitTestCases");
Test testCase = TestFinder.Find("MethodWithExplicitTestCases(1)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Runnable));
testCase = TestFinder.Find("MethodWithExplicitTestCases(2)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
testCase = TestFinder.Find("MethodWithExplicitTestCases(3)", suite, false);
Assert.That(testCase.RunState, Is.EqualTo(RunState.Explicit));
Assert.That(testCase.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Connection failing"));
}
#if !NETSTANDARD1_3 && !NETSTANDARD1_6
[Test]
public void CanIncludePlatform()
{
bool isLinux = OSPlatform.CurrentPlatform.IsUnix;
bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX;
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWithIncludePlatform");
Test testCase1 = TestFinder.Find("MethodWithIncludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWithIncludePlatform(2)", suite, false);
Test testCase3 = TestFinder.Find("MethodWithIncludePlatform(3)", suite, false);
Test testCase4 = TestFinder.Find("MethodWithIncludePlatform(4)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
else if (isMacOSX)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Skipped));
}
}
[Test]
public void CanExcludePlatform()
{
bool isLinux = OSPlatform.CurrentPlatform.IsUnix;
bool isMacOSX = OSPlatform.CurrentPlatform.IsMacOSX;
TestSuite suite = TestBuilder.MakeParameterizedMethodSuite(
typeof(TestCaseAttributeFixture), "MethodWitExcludePlatform");
Test testCase1 = TestFinder.Find("MethodWitExcludePlatform(1)", suite, false);
Test testCase2 = TestFinder.Find("MethodWitExcludePlatform(2)", suite, false);
Test testCase3 = TestFinder.Find("MethodWitExcludePlatform(3)", suite, false);
Test testCase4 = TestFinder.Find("MethodWitExcludePlatform(4)", suite, false);
if (isLinux)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
else if (isMacOSX)
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
else
{
Assert.That(testCase1.RunState, Is.EqualTo(RunState.Skipped));
Assert.That(testCase2.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase3.RunState, Is.EqualTo(RunState.Runnable));
Assert.That(testCase4.RunState, Is.EqualTo(RunState.Runnable));
}
}
#endif
#region Nullable<> tests
[TestCase(12, 3, 4)]
[TestCase(12, 2, 6)]
[TestCase(12, 4, 3)]
public void NullableIntegerDivisionWithResultPassedToTest(int? n, int? d, int? q)
{
Assert.AreEqual(q, n / d);
}
[TestCase(12, 3, ExpectedResult = 4)]
[TestCase(12, 2, ExpectedResult = 6)]
[TestCase(12, 4, ExpectedResult = 3)]
public int? NullableIntegerDivisionWithResultCheckedByNUnit(int? n, int? d)
{
return n / d;
}
[TestCase(2, 2, ExpectedResult = 4)]
public double? CanConvertIntToNullableDouble(double? x, double? y)
{
return x + y;
}
[TestCase(1)]
public void CanConvertIntToNullableShort(short? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableByte(byte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableSByte(sbyte? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase(1)]
public void CanConvertIntToNullableLong(long? x)
{
Assert.That(x.HasValue);
Assert.That(x.Value, Is.EqualTo(1));
}
[TestCase("2.2", "3.3", ExpectedResult = 5.5)]
public decimal? CanConvertStringToNullableDecimal(decimal? x, decimal? y)
{
Assert.That(x.HasValue);
Assert.That(y.HasValue);
return x.Value + y.Value;
}
[TestCase(null)]
public void SupportsNullableDecimal(decimal? x)
{
Assert.That(x.HasValue, Is.False);
}
[TestCase(2.2, 3.3, ExpectedResult = 5.5)]
public decimal? CanConvertDoubleToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public decimal? CanConvertIntToNullableDecimal(decimal? x, decimal? y)
{
return x + y;
}
[TestCase(5, 2, ExpectedResult = 7)]
public short? CanConvertSmallIntsToNullableShort(short? x, short? y)
{
return (short)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public byte? CanConvertSmallIntsToNullableByte(byte? x, byte? y)
{
return (byte)(x + y);
}
[TestCase(5, 2, ExpectedResult = 7)]
public sbyte? CanConvertSmallIntsToNullableSByte(sbyte? x, sbyte? y)
{
return (sbyte)(x + y);
}
[TestCase("12-October-1942")]
public void CanConvertStringToNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue);
Assert.AreEqual(1942, dt.Value.Year);
}
[TestCase(null)]
public void SupportsNullableDateTime(DateTime? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase("4:44:15")]
public void CanConvertStringToNullableTimeSpan(TimeSpan? ts)
{
Assert.That(ts.HasValue);
Assert.AreEqual(4, ts.Value.Hours);
Assert.AreEqual(44, ts.Value.Minutes);
Assert.AreEqual(15, ts.Value.Seconds);
}
[TestCase(null)]
public void SupportsNullableTimeSpan(TimeSpan? dt)
{
Assert.That(dt.HasValue, Is.False);
}
[TestCase(1)]
public void NullableSimpleFormalParametersWithArgument(int? a)
{
Assert.AreEqual(1, a);
}
[TestCase(null)]
public void NullableSimpleFormalParametersWithNullArgument(int? a)
{
Assert.IsNull(a);
}
[TestCase(null, ExpectedResult = null)]
[TestCase(1, ExpectedResult = 1)]
public int? TestCaseWithNullableReturnValue(int? a)
{
return a;
}
[TestCase(1, ExpectedResult = 1)]
public T TestWithGenericReturnType<T>(T arg1)
{
return arg1;
}
#if ASYNC
[TestCase(1, ExpectedResult = 1)]
public async Task<T> TestWithAsyncGenericReturnType<T>(T arg1)
{
return await Task.Run(() => arg1);
}
#endif
#endregion
}
}
| |
// Copyright (c) MOSA Project. Licensed under the New BSD License.
using Mosa.Compiler.Common;
using Mosa.Compiler.Framework;
using Mosa.Compiler.Framework.IR;
using Mosa.Compiler.MosaTypeSystem;
using System;
using System.Diagnostics;
namespace Mosa.Platform.x86.Stages
{
/// <summary>
/// Transforms IR instructions into their appropriate X86.
/// </summary>
/// <remarks>
/// This transformation stage transforms IR instructions into their equivalent X86 sequences.
/// </remarks>
public sealed class IRTransformationStage : BaseTransformationStage
{
private const int LargeAlignment = 16;
protected override void PopulateVisitationDictionary()
{
visitationDictionary[IRInstruction.AddSigned] = AddSigned;
visitationDictionary[IRInstruction.AddUnsigned] = AddUnsigned;
visitationDictionary[IRInstruction.AddFloat] = AddFloat;
visitationDictionary[IRInstruction.DivFloat] = DivFloat;
visitationDictionary[IRInstruction.AddressOf] = AddressOf;
visitationDictionary[IRInstruction.FloatCompare] = FloatCompare;
visitationDictionary[IRInstruction.IntegerCompareBranch] = IntegerCompareBranch;
visitationDictionary[IRInstruction.IntegerCompare] = IntegerCompare;
visitationDictionary[IRInstruction.Jmp] = Jmp;
visitationDictionary[IRInstruction.Load] = Load;
visitationDictionary[IRInstruction.Load2] = Load2;
visitationDictionary[IRInstruction.CompoundLoad] = CompoundLoad;
visitationDictionary[IRInstruction.LoadSignExtended] = LoadSignExtended;
visitationDictionary[IRInstruction.LoadZeroExtended] = LoadZeroExtended;
visitationDictionary[IRInstruction.LogicalAnd] = LogicalAnd;
visitationDictionary[IRInstruction.LogicalOr] = LogicalOr;
visitationDictionary[IRInstruction.LogicalXor] = LogicalXor;
visitationDictionary[IRInstruction.LogicalNot] = LogicalNot;
visitationDictionary[IRInstruction.Move] = Move;
visitationDictionary[IRInstruction.CompoundMove] = CompoundMove;
visitationDictionary[IRInstruction.Return] = Return;
visitationDictionary[IRInstruction.InternalCall] = InternalCall;
visitationDictionary[IRInstruction.InternalReturn] = InternalReturn;
visitationDictionary[IRInstruction.ArithmeticShiftRight] = ArithmeticShiftRight;
visitationDictionary[IRInstruction.ShiftLeft] = ShiftLeft;
visitationDictionary[IRInstruction.ShiftRight] = ShiftRight;
visitationDictionary[IRInstruction.Store] = Store;
visitationDictionary[IRInstruction.CompoundStore] = CompoundStore;
visitationDictionary[IRInstruction.MulFloat] = MulFloat;
visitationDictionary[IRInstruction.SubFloat] = SubFloat;
visitationDictionary[IRInstruction.SubSigned] = SubSigned;
visitationDictionary[IRInstruction.SubUnsigned] = SubUnsigned;
visitationDictionary[IRInstruction.MulSigned] = MulSigned;
visitationDictionary[IRInstruction.MulUnsigned] = MulUnsigned;
visitationDictionary[IRInstruction.DivSigned] = DivSigned;
visitationDictionary[IRInstruction.DivUnsigned] = DivUnsigned;
visitationDictionary[IRInstruction.RemSigned] = RemSigned;
visitationDictionary[IRInstruction.RemUnsigned] = RemUnsigned;
visitationDictionary[IRInstruction.RemFloat] = RemFloat;
visitationDictionary[IRInstruction.Switch] = Switch;
visitationDictionary[IRInstruction.Break] = Break;
visitationDictionary[IRInstruction.Nop] = Nop;
visitationDictionary[IRInstruction.SignExtendedMove] = SignExtendedMove;
visitationDictionary[IRInstruction.Call] = Call;
visitationDictionary[IRInstruction.ZeroExtendedMove] = ZeroExtendedMove;
visitationDictionary[IRInstruction.FloatToIntegerConversion] = FloatToIntegerConversion;
visitationDictionary[IRInstruction.IntegerToFloatConversion] = IntegerToFloatConversion;
}
#region Visitation Methods
/// <summary>
/// Visitation function for AddSigned.
/// </summary>
/// <param name="context">The context.</param>
private void AddSigned(Context context)
{
context.ReplaceInstructionOnly(X86.Add);
}
/// <summary>
/// Visitation function for AddUnsigned.
/// </summary>
/// <param name="context">The context.</param>
private void AddUnsigned(Context context)
{
context.ReplaceInstructionOnly(X86.Add);
}
/// <summary>
/// Visitation function for AddFloat.
/// </summary>
/// <param name="context">The context.</param>
private void AddFloat(Context context)
{
if (context.Result.IsR4)
{
context.ReplaceInstructionOnly(X86.Addss);
context.Size = InstructionSize.Size32;
}
else
{
context.ReplaceInstructionOnly(X86.Addsd);
context.Size = InstructionSize.Size64;
}
}
/// <summary>
/// Visitation function for DivFloat.
/// </summary>
/// <param name="context">The context.</param>
private void DivFloat(Context context)
{
if (context.Result.IsR4)
{
context.ReplaceInstructionOnly(X86.Divss);
context.Size = InstructionSize.Size32;
}
else
{
context.ReplaceInstructionOnly(X86.Divsd);
context.Size = InstructionSize.Size64;
}
}
/// <summary>
/// Addresses the of instruction.
/// </summary>
/// <param name="context">The context.</param>
private void AddressOf(Context context)
{
Operand result = context.Result;
Operand register = AllocateVirtualRegister(result.Type);
context.Result = register;
context.ReplaceInstructionOnly(X86.Lea);
context.AppendInstruction(X86.Mov, NativeInstructionSize, result, register);
}
/// <summary>
/// Floating point compare instruction.
/// </summary>
/// <param name="context">The context.</param>
private void FloatCompare(Context context)
{
Operand result = context.Result;
Operand left = context.Operand1;
Operand right = context.Operand2;
ConditionCode condition = context.ConditionCode;
// normalize condition
switch (condition)
{
case ConditionCode.Equal: break;
case ConditionCode.NotEqual: break;
case ConditionCode.UnsignedGreaterOrEqual: condition = ConditionCode.GreaterOrEqual; break;
case ConditionCode.UnsignedGreaterThan: condition = ConditionCode.GreaterThan; break;
case ConditionCode.UnsignedLessOrEqual: condition = ConditionCode.LessOrEqual; break;
case ConditionCode.UnsignedLessThan: condition = ConditionCode.LessThan; break;
}
// TODO - Move the following to its own pre-IR decomposition stage for this instruction
// Swap, if necessary, the operands to place register operand first than memory operand
// otherwise the memory operand will have to be loaded into a register
if ((condition == ConditionCode.Equal || condition == ConditionCode.NotEqual) && left.IsMemoryAddress && !right.IsMemoryAddress)
{
// swap order of operands to move
var t = left;
left = right;
right = t;
}
Context before = context.InsertBefore();
// Compare using the smallest precision
if (left.IsR4 && right.IsR8)
{
Operand rop = AllocateVirtualRegister(TypeSystem.BuiltIn.R4);
before.SetInstruction(X86.Cvtsd2ss, rop, right);
right = rop;
}
if (left.IsR8 && right.IsR4)
{
Operand rop = AllocateVirtualRegister(TypeSystem.BuiltIn.R4);
before.SetInstruction(X86.Cvtsd2ss, rop, left);
left = rop;
}
X86Instruction instruction = null;
InstructionSize size = InstructionSize.None;
if (left.IsR4)
{
instruction = X86.Ucomiss;
size = InstructionSize.Size32;
}
else
{
instruction = X86.Ucomisd;
size = InstructionSize.Size64;
}
switch (condition)
{
case ConditionCode.Equal:
{
// a==b
// mov eax, 1
// ucomisd xmm0, xmm1
// jp L3
// jne L3
// ret
//L3:
// mov eax, 0
var newBlocks = CreateNewBlockContexts(2);
Context nextBlock = Split(context);
context.SetInstruction(X86.Mov, result, Operand.CreateConstant(TypeSystem, 1));
context.AppendInstruction(instruction, size, null, left, right);
context.AppendInstruction(X86.Branch, ConditionCode.Parity, newBlocks[1].Block);
context.AppendInstruction(X86.Jmp, newBlocks[0].Block);
newBlocks[0].AppendInstruction(X86.Branch, ConditionCode.NotEqual, newBlocks[1].Block);
newBlocks[0].AppendInstruction(X86.Jmp, nextBlock.Block);
newBlocks[1].AppendInstruction(X86.Mov, result, ConstantZero);
newBlocks[1].AppendInstruction(X86.Jmp, nextBlock.Block);
break;
}
case ConditionCode.NotEqual:
{
// a!=b
// mov eax, 1
// ucomisd xmm0, xmm1
// jp L5
// setne al
// movzx eax, al
//L5:
var newBlocks = CreateNewBlockContexts(1);
Context nextBlock = Split(context);
context.SetInstruction(X86.Mov, result, Operand.CreateConstant(TypeSystem, 1));
context.AppendInstruction(instruction, size, null, left, right);
context.AppendInstruction(X86.Branch, ConditionCode.Parity, nextBlock.Block);
context.AppendInstruction(X86.Jmp, newBlocks[0].Block);
newBlocks[0].AppendInstruction(X86.Setcc, ConditionCode.NotEqual, result);
newBlocks[0].AppendInstruction(X86.Movzx, InstructionSize.Size8, result, result);
newBlocks[0].AppendInstruction(X86.Jmp, nextBlock.Block);
break;
}
case ConditionCode.LessThan:
{
// a<b
// mov eax, 0
// ucomisd xmm1, xmm0
// seta al
context.SetInstruction(X86.Mov, result, ConstantZero);
context.AppendInstruction(instruction, size, null, right, left);
context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterThan, result);
break;
}
case ConditionCode.GreaterThan:
{
// a>b
// mov eax, 0
// ucomisd xmm0, xmm1
// seta al
context.SetInstruction(X86.Mov, result, ConstantZero);
context.AppendInstruction(instruction, size, null, left, right);
context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterThan, result);
break;
}
case ConditionCode.LessOrEqual:
{
// a<=b
// mov eax, 0
// ucomisd xmm1, xmm0
// setae al
context.SetInstruction(X86.Mov, result, ConstantZero);
context.AppendInstruction(instruction, size, null, right, left);
context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterOrEqual, result);
break;
}
case ConditionCode.GreaterOrEqual:
{
// a>=b
// mov eax, 0
// ucomisd xmm0, xmm1
// setae al
context.SetInstruction(X86.Mov, result, ConstantZero);
context.AppendInstruction(instruction, size, null, left, right);
context.AppendInstruction(X86.Setcc, ConditionCode.UnsignedGreaterOrEqual, result);
break;
}
}
}
/// <summary>
/// Visitation function for IntegerCompareBranchInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void IntegerCompareBranch(Context context)
{
var target = context.BranchTargets[0];
var condition = context.ConditionCode;
var operand1 = context.Operand1;
var operand2 = context.Operand2;
context.SetInstruction(X86.Cmp, null, operand1, operand2);
context.AppendInstruction(X86.Branch, condition, target);
}
/// <summary>
/// Visitation function for IntegerCompareInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void IntegerCompare(Context context)
{
var condition = context.ConditionCode;
var resultOperand = context.Result;
var operand1 = context.Operand1;
var operand2 = context.Operand2;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
context.SetInstruction(X86.Mov, v1, ConstantZero);
context.AppendInstruction(X86.Cmp, null, operand1, operand2);
if (resultOperand.IsUnsigned || resultOperand.IsChar)
context.AppendInstruction(X86.Setcc, condition.GetUnsigned(), v1);
else
context.AppendInstruction(X86.Setcc, condition, v1);
context.AppendInstruction(X86.Mov, resultOperand, v1);
}
/// <summary>
/// Visitation function for JmpInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Jmp(Context context)
{
context.ReplaceInstructionOnly(X86.Jmp);
}
/// <summary>
/// Visitation function for LoadInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Load(Context context)
{
Operand result = context.Result;
Operand baseOperand = context.Operand1;
Operand offsetOperand = context.Operand2;
var type = context.MosaType;
var size = context.Size;
if (offsetOperand.IsConstant)
{
if (baseOperand.IsField)
{
Debug.Assert(offsetOperand.IsConstantZero);
Debug.Assert(baseOperand.Field.IsStatic);
var mov = GetMove(result, baseOperand);
if (result.IsR8 && type.IsR4) // size == InstructionSize.Size32)
{
mov = X86.Cvtss2sd;
}
context.SetInstruction(GetMove(result, baseOperand), size, result, baseOperand);
}
else
{
Operand mem = Operand.CreateMemoryAddress(baseOperand.Type, baseOperand, offsetOperand.ConstantSignedLongInteger);
var mov = GetMove(result, mem);
if (result.IsR8 && type.IsR4) // size == InstructionSize.Size32)
{
mov = X86.Cvtss2sd;
}
context.SetInstruction(mov, size, result, mem);
}
}
else
{
Operand v1 = AllocateVirtualRegister(baseOperand.Type);
Operand mem = Operand.CreateMemoryAddress(v1.Type, v1, 0);
context.SetInstruction(X86.Mov, v1, baseOperand);
context.AppendInstruction(X86.Add, v1, v1, offsetOperand);
var mov = GetMove(result, mem);
if (result.IsR8 && type.IsR4)
{
mov = X86.Cvtss2sd;
}
context.AppendInstruction(mov, size, result, mem);
}
}
private void Load2(Context context)
{
Operand result = context.Result;
Operand baseOperand = context.Operand1;
Operand offsetOperand = context.Operand2;
var type = context.MosaType;
var size = context.Size;
context.SetInstruction(X86.MovLoad, size, result, baseOperand, offsetOperand);
}
private void CompoundLoad(Context context)
{
var type = context.Result.Type;
int typeSize = TypeLayout.GetTypeSize(type);
int alignedTypeSize = typeSize - (typeSize % NativeAlignment);
int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment);
Debug.Assert(typeSize > 0, context.Operand2.Name);
int offset = 0;
if (context.Operand2.IsConstant)
{
offset = (int)context.Operand2.ConstantSignedLongInteger;
}
var offsetop = context.Operand2;
var src = context.Operand1;
var dest = context.Result;
Debug.Assert(dest.IsMemoryAddress, dest.Name);
var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1);
context.SetInstruction(X86.Nop);
context.AppendInstruction(X86.Mov, srcReg, src);
context.AppendInstruction(X86.Lea, dstReg, dest);
if (!offsetop.IsConstant)
{
context.AppendInstruction(X86.Add, srcReg, srcReg, offsetop);
}
for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment)
{
// Large Aligned moves allow 128bits to be copied at a time
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var offset2 = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovupsLoad, tmpLarge, srcReg, index);
context.AppendInstruction(X86.MovupsStore, null, dstReg, index, tmpLarge);
}
for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var offset2 = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovLoad, InstructionSize.Size32, tmp, srcReg, offset2);
context.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, dstReg, index, tmp);
}
for (int i = alignedTypeSize; i < typeSize; i++)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var offset2 = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovzxLoad, InstructionSize.Size8, tmp, srcReg, offset2);
context.AppendInstruction(X86.MovStore, InstructionSize.Size8, null, dstReg, index, tmp);
}
}
/// <summary>
/// Visitation function for Load Sign Extended.
/// </summary>
/// <param name="context">The context.</param>
private void LoadSignExtended(Context context)
{
//var destination = context.Result;
//var source = context.Operand1;
//var type = context.MosaType;
//var offset = context.Operand2;
//var size = context.Size;
// var v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
Debug.Assert(!(context.Operand1.IsConstant && context.Operand2.IsConstant));
Debug.Assert(context.Size == InstructionSize.Size8 || context.Size == InstructionSize.Size16);
context.SetInstruction(X86.MovsxLoad, context.Size, context.Result, context.Operand1, context.Operand2);
//context.SetInstruction(X86.Mov, v1, source);
//if (offset.IsConstant)
//{
// if (source.IsField)
// {
// Debug.Assert(offset.IsConstantZero);
// Debug.Assert(source.Field.IsStatic);
// context.SetInstruction(X86.Movsx, size, destination, source);
// }
// else
// {
// context.AppendInstruction(X86.Movsx, size, destination, Operand.CreateMemoryAddress(type, v1, offset.ConstantSignedLongInteger));
// }
//}
//else
//{
// context.AppendInstruction(X86.Add, v1, v1, offset);
// context.AppendInstruction(X86.Movsx, size, destination, Operand.CreateMemoryAddress(type, v1, 0));
//}
}
/// <summary>
/// Visitation function for Load Zero Extended.
/// </summary>
/// <param name="context">The context.</param>
private void LoadZeroExtended(Context context)
{
context.SetInstruction(X86.MovzxLoad, context.Size, context.Result, context.Operand1, context.Operand2);
}
/// <summary>
/// Visitation function for LogicalAndInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void LogicalAnd(Context context)
{
context.ReplaceInstructionOnly(X86.And);
}
/// <summary>
/// Visitation function for LogicalOrInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void LogicalOr(Context context)
{
context.ReplaceInstructionOnly(X86.Or);
}
/// <summary>
/// Visitation function for LogicalXorInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void LogicalXor(Context context)
{
context.ReplaceInstructionOnly(X86.Xor);
}
/// <summary>
/// Visitation function for LogicalNotInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void LogicalNot(Context context)
{
Operand dest = context.Result;
context.SetInstruction(X86.Mov, context.Result, context.Operand1);
if (dest.IsByte)
context.AppendInstruction(X86.Xor, dest, dest, Operand.CreateConstant(TypeSystem, 0xFF));
else if (dest.IsU2)
context.AppendInstruction(X86.Xor, dest, dest, Operand.CreateConstant(TypeSystem, 0xFFFF));
else
context.AppendInstruction(X86.Not, dest, dest);
}
/// <summary>
/// Visitation function for MoveInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Move(Context context)
{
Operand result = context.Result;
Operand operand = context.Operand1;
X86Instruction instruction = X86.Mov;
InstructionSize size = InstructionSize.None;
if (result.IsR)
{
//Debug.Assert(operand.IsFloatingPoint, @"Move can't convert to floating point type.");
if (result.Type == operand.Type)
{
if (result.IsR4)
{
instruction = X86.Movss;
size = InstructionSize.Size32;
}
else if (result.IsR8)
{
instruction = X86.Movsd;
size = InstructionSize.Size64;
}
}
else if (result.IsR8)
{
instruction = X86.Cvtss2sd;
}
else if (result.IsR4)
{
instruction = X86.Cvtsd2ss;
}
}
context.ReplaceInstructionOnly(instruction);
context.Size = size;
}
private void CompoundMove(Context context)
{
var type = context.Result.Type;
int typeSize = TypeLayout.GetTypeSize(type);
int alignedTypeSize = typeSize - (typeSize % NativeAlignment);
int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment);
Debug.Assert(typeSize > 0, MethodCompiler.Method.FullName);
var src = context.Operand1;
var dest = context.Result;
Debug.Assert((src.IsMemoryAddress || src.IsSymbol) && dest.IsMemoryAddress, context.ToString());
var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1);
context.SetInstruction(X86.Nop);
if (src.IsSymbol)
{
context.AppendInstruction(X86.Mov, srcReg, src);
}
else
{
context.AppendInstruction(X86.Lea, srcReg, src);
}
context.AppendInstruction(X86.Lea, dstReg, dest);
for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment)
{
// Large Aligned moves allow 128bits to be copied at a time
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
context.AppendInstruction(X86.MovupsLoad, tmpLarge, srcReg, index);
context.AppendInstruction(X86.MovupsStore, null, dstReg, index, tmpLarge);
}
for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
context.AppendInstruction(X86.MovLoad, InstructionSize.Size32, tmp, srcReg, index);
context.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, dstReg, index, tmp);
}
for (int i = alignedTypeSize; i < typeSize; i++)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
context.AppendInstruction(X86.MovzxLoad, InstructionSize.Size8, tmp, srcReg, index);
context.AppendInstruction(X86.MovStore, InstructionSize.Size8, null, dstReg, index, tmp);
}
}
/// <summary>
/// Visitation function for Return.
/// </summary>
/// <param name="context">The context.</param>
private void Return(Context context)
{
//Debug.Assert(context.BranchTargets != null);
if (context.Operand1 != null)
{
var returnOperand = context.Operand1;
context.Empty();
CallingConvention.SetReturnValue(MethodCompiler, TypeLayout, context, returnOperand);
context.AppendInstruction(X86.Jmp, BasicBlocks.EpilogueBlock);
}
else
{
context.SetInstruction(X86.Jmp, BasicBlocks.EpilogueBlock);
}
}
/// <summary>
/// Visitation function for InternalCall.
/// </summary>
/// <param name="context">The context.</param>
private void InternalCall(Context context)
{
context.ReplaceInstructionOnly(X86.Call);
}
/// <summary>
/// Visitation function for InternalReturn.
/// </summary>
/// <param name="context">The context.</param>
private void InternalReturn(Context context)
{
Debug.Assert(context.BranchTargets == null);
// To return from an internal method call (usually from within a finally or exception clause)
context.SetInstruction(X86.Ret);
}
/// <summary>
/// Arithmetic the shift right instruction.
/// </summary>
/// <param name="context">The context.</param>
private void ArithmeticShiftRight(Context context)
{
context.ReplaceInstructionOnly(X86.Sar);
}
/// <summary>
/// Visitation function for ShiftLeftInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void ShiftLeft(Context context)
{
context.ReplaceInstructionOnly(X86.Shl);
}
/// <summary>
/// Visitation function for ShiftRightInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void ShiftRight(Context context)
{
context.ReplaceInstructionOnly(X86.Shr);
}
/// <summary>
/// Visitation function for StoreInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Store(Context context)
{
Operand baseOperand = context.Operand1;
Operand offsetOperand = context.Operand2;
Operand value = context.Operand3;
MosaType storeType = context.MosaType;
var type = baseOperand.Type;
var size = context.Size;
if (value.IsR8 && type.IsR4) //&& size == InstructionSize.Size32)
{
Operand xmm1 = AllocateVirtualRegister(TypeSystem.BuiltIn.R4);
context.InsertBefore().AppendInstruction(X86.Cvtsd2ss, size, xmm1, value);
value = xmm1;
}
else if (value.IsMemoryAddress)
{
Operand v2 = AllocateVirtualRegister(value.Type);
context.InsertBefore().AppendInstruction(X86.Mov, size, v2, value);
value = v2;
}
if (offsetOperand.IsConstant)
{
if (baseOperand.IsField)
{
Debug.Assert(offsetOperand.IsConstantZero);
Debug.Assert(baseOperand.Field.IsStatic);
context.SetInstruction(GetMove(baseOperand, value), size, baseOperand, value);
}
else
{
var mem = Operand.CreateMemoryAddress(storeType, baseOperand, offsetOperand.ConstantSignedLongInteger);
context.SetInstruction(GetMove(mem, value), size, mem, value);
}
}
else
{
if (type.IsUnmanagedPointer)
type = storeType.ToUnmanagedPointer();
else if (type.IsManagedPointer)
type = storeType.ToManagedPointer();
Operand v1 = AllocateVirtualRegister(type);
Operand mem = Operand.CreateMemoryAddress(storeType, v1, 0);
context.SetInstruction(X86.Mov, v1, baseOperand);
context.AppendInstruction(X86.Add, v1, v1, offsetOperand);
context.AppendInstruction(GetMove(mem, value), size, mem, value);
}
}
private void CompoundStore(Context context)
{
var type = context.Operand3.Type;
int typeSize = TypeLayout.GetTypeSize(type);
int alignedTypeSize = typeSize - (typeSize % NativeAlignment);
int largeAlignedTypeSize = typeSize - (typeSize % LargeAlignment);
Debug.Assert(typeSize > 0, MethodCompiler.Method.FullName);
int offset = context.Operand2.IsConstant ? context.Operand2.ConstantSignedInteger : 0;
var offsetop = context.Operand2;
var src = context.Operand3;
var dest = context.Operand1;
Debug.Assert(src.IsMemoryAddress);
var srcReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var dstReg = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmp = MethodCompiler.CreateVirtualRegister(dest.Type.TypeSystem.BuiltIn.I4);
var tmpLarge = Operand.CreateCPURegister(MethodCompiler.TypeSystem.BuiltIn.Void, SSE2Register.XMM1);
context.SetInstruction(X86.Nop);
context.AppendInstruction(X86.Lea, srcReg, src);
context.AppendInstruction(X86.Mov, dstReg, dest);
if (!offsetop.IsConstant)
{
context.AppendInstruction(X86.Add, dstReg, dstReg, offsetop);
}
for (int i = 0; i < largeAlignedTypeSize; i += LargeAlignment)
{
// Large Aligned moves allow 128bits to be copied at a time
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var indexOffset = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovupsLoad, InstructionSize.Size128, tmp, srcReg, index);
context.AppendInstruction(X86.MovupsStore, InstructionSize.Size128, null, dstReg, indexOffset, tmp);
}
for (int i = largeAlignedTypeSize; i < alignedTypeSize; i += NativeAlignment)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var indexOffset = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovLoad, InstructionSize.Size32, tmp, srcReg, index);
context.AppendInstruction(X86.MovStore, InstructionSize.Size32, null, dstReg, indexOffset, tmp);
}
for (int i = alignedTypeSize; i < typeSize; i++)
{
var index = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i);
var indexOffset = Operand.CreateConstant(TypeSystem.BuiltIn.I4, i + offset);
context.AppendInstruction(X86.MovLoad, InstructionSize.Size8, tmp, srcReg, index);
context.AppendInstruction(X86.MovStore, InstructionSize.Size8, null, dstReg, indexOffset, tmp);
}
}
/// <summary>
/// Visitation function for MulFloat.
/// </summary>
/// <param name="context">The context.</param>
private void MulFloat(Context context)
{
if (context.Result.IsR4)
{
context.ReplaceInstructionOnly(X86.Mulss);
context.Size = InstructionSize.Size32;
}
else
{
context.ReplaceInstructionOnly(X86.Mulsd);
context.Size = InstructionSize.Size64;
}
}
/// <summary>
/// Visitation function for SubFloat.
/// </summary>
/// <param name="context">The context.</param>
private void SubFloat(Context context)
{
if (context.Result.IsR4)
{
context.ReplaceInstructionOnly(X86.Subss);
context.Size = InstructionSize.Size32;
}
else
{
context.ReplaceInstructionOnly(X86.Subsd);
context.Size = InstructionSize.Size64;
}
}
/// <summary>
/// Visitation function for SubSigned.
/// </summary>
/// <param name="context">The context.</param>
private void SubSigned(Context context)
{
context.ReplaceInstructionOnly(X86.Sub);
}
/// <summary>
/// Visitation function for SubUnsigned.
/// </summary>
/// <param name="context">The context.</param>
private void SubUnsigned(Context context)
{
context.ReplaceInstructionOnly(X86.Sub);
}
/// <summary>
/// Visitation function for MulSigned.
/// </summary>
/// <param name="context">The context.</param>
private void MulSigned(Context context)
{
Operand result = context.Result;
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
context.SetInstruction2(X86.Mul, v1, result, operand1, operand2);
}
/// <summary>
/// Visitation function for MulUnsigned.
/// </summary>
/// <param name="context">The context.</param>
private void MulUnsigned(Context context)
{
Operand result = context.Result;
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
context.SetInstruction2(X86.Mul, v1, result, operand1, operand2);
}
/// <summary>
/// Visitation function for DivSigned.
/// </summary>
/// <param name="context">The context.</param>
private void DivSigned(Context context)
{
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand result = context.Result;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
Operand v3 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
context.SetInstruction2(X86.Cdq, v1, v2, operand1);
context.AppendInstruction2(X86.IDiv, v3, result, v1, v2, operand2);
}
/// <summary>
/// Visitation function for DivUnsigned.
/// </summary>
/// <param name="context">The context.</param>
private void DivUnsigned(Context context)
{
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand result = context.Result;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
context.SetInstruction(X86.Mov, v1, ConstantZero);
context.AppendInstruction2(X86.Div, v1, v2, v1, operand1, operand2);
context.AppendInstruction(X86.Mov, result, v2);
}
/// <summary>
/// Visitation function for RemSigned.
/// </summary>
/// <param name="context">The context.</param>
private void RemSigned(Context context)
{
Operand result = context.Result;
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
Operand v3 = AllocateVirtualRegister(TypeSystem.BuiltIn.I4);
context.SetInstruction2(X86.Cdq, v1, v2, operand1);
context.AppendInstruction2(X86.IDiv, result, v3, v1, v2, operand2);
}
/// <summary>
/// Visitation function for RemUnsigned.
/// </summary>
/// <param name="context">The context.</param>
private void RemUnsigned(Context context)
{
Operand result = context.Result;
Operand operand1 = context.Operand1;
Operand operand2 = context.Operand2;
Operand v1 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
Operand v2 = AllocateVirtualRegister(TypeSystem.BuiltIn.U4);
context.SetInstruction(X86.Mov, v1, ConstantZero);
context.AppendInstruction2(X86.Div, v1, v2, v1, operand1, operand2);
context.AppendInstruction(X86.Mov, result, v1);
}
/// <summary>
/// Visitation function for RemFloat.
/// </summary>
/// <param name="context">The context.</param>
private void RemFloat(Context context)
{
var result = context.Result;
var dividend = context.Operand1;
var divisor = context.Operand2;
var method = (result.IsR8) ? "RemR8" : "RemR4";
var type = TypeSystem.GetTypeByName("Mosa.Runtime.x86", "Division");
Debug.Assert(type != null, "Cannot find type: Mosa.Runtime.x86.Division type");
var mosaMethod = type.FindMethodByName(method);
Debug.Assert(method != null, "Cannot find method: " + method);
context.ReplaceInstructionOnly(IRInstruction.Call);
context.SetOperand(0, Operand.CreateSymbolFromMethod(TypeSystem, mosaMethod));
context.Result = result;
context.Operand2 = dividend;
context.Operand3 = divisor;
context.OperandCount = 3;
context.ResultCount = 1;
context.InvokeMethod = mosaMethod;
// Since we are already in IR Transformation Stage we gotta call this now
CallingConvention.MakeCall(MethodCompiler, TypeLayout, context);
}
/// <summary>
/// Visitation function for SwitchInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Switch(Context context)
{
var targets = context.BranchTargets;
Operand operand = context.Operand1;
context.Empty();
for (int i = 0; i < targets.Count - 1; ++i)
{
context.AppendInstruction(X86.Cmp, null, operand, Operand.CreateConstant(TypeSystem, i));
context.AppendInstruction(X86.Branch, ConditionCode.Equal, targets[i]);
}
}
/// <summary>
/// Visitation function for BreakInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Break(Context context)
{
context.SetInstruction(X86.Break);
}
/// <summary>
/// Visitation function for NopInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void Nop(Context context)
{
context.SetInstruction(X86.Nop);
}
/// <summary>
/// Visitation function for SignExtendedMoveInstruction instructions.
/// </summary>
/// <param name="context">The context.</param>
private void SignExtendedMove(Context context)
{
context.ReplaceInstructionOnly(X86.Movsx);
}
/// <summary>
/// Visitation function for Call.
/// </summary>
/// <param name="context">The context.</param>
private void Call(Context context)
{
if (context.OperandCount == 0 && context.BranchTargets != null)
{
// inter-method call; usually for exception processing
context.ReplaceInstructionOnly(X86.Call);
}
else
{
CallingConvention.MakeCall(MethodCompiler, TypeLayout, context);
}
}
/// <summary>
/// Visitation function for ZeroExtendedMoveInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void ZeroExtendedMove(Context context)
{
Debug.Assert(context.Size != InstructionSize.None);
context.ReplaceInstructionOnly(X86.Movzx);
}
/// <summary>
/// Visitation function for FloatingPointToIntegerConversionInstruction.
/// </summary>
/// <param name="context">The context.</param>
private void FloatToIntegerConversion(Context context)
{
Operand source = context.Operand1;
Operand destination = context.Result;
if (destination.Type.IsI1 || destination.Type.IsI2 || destination.Type.IsI4)
{
if (source.IsR8)
context.ReplaceInstructionOnly(X86.Cvttsd2si);
else
context.ReplaceInstructionOnly(X86.Cvttss2si);
}
else
{
throw new NotImplementCompilerException();
}
}
/// <summary>
/// Visitation function for IntegerToFloatingPointConversion.
/// </summary>
/// <param name="context">The context.</param>
private void IntegerToFloatConversion(Context context)
{
if (context.Result.IsR4)
context.ReplaceInstructionOnly(X86.Cvtsi2ss);
else if (context.Result.IsR8)
context.ReplaceInstructionOnly(X86.Cvtsi2sd);
else
throw new NotSupportedException();
}
#endregion Visitation Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Braintree.Exceptions;
using Braintree.Test;
namespace Braintree.Tests
{
[TestFixture]
public class CustomerTest
{
private BraintreeGateway gateway;
private BraintreeService service;
private Random random;
[SetUp]
public void Setup()
{
gateway = new BraintreeGateway
{
Environment = Environment.DEVELOPMENT,
MerchantId = "integration_merchant_id",
PublicKey = "integration_public_key",
PrivateKey = "integration_private_key"
};
service = new BraintreeService(gateway.Configuration);
random = new Random();
}
[Test]
[Category("Integration")]
public void Find_FindsCustomerWithGivenId()
{
string id = Guid.NewGuid().ToString();
var createRequest = new CustomerRequest
{
Id = id,
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest
{
Number = "5105105105105100",
ExpirationDate = "05/12",
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddress = new CreditCardAddressRequest()
{
FirstName = "Mike",
LastName = "Smith",
Company = "Smith Co.",
StreetAddress = "1 W Main St",
ExtendedAddress = "Suite 330",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
}
}
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.AreEqual(id, customer.Id);
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("510510", customer.CreditCards[0].Bin);
Assert.AreEqual("5100", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2012", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.IsTrue(Regex.IsMatch(customer.CreditCards[0].UniqueNumberIdentifier, "\\A\\w{32}\\z"));
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
Assert.AreEqual("Mike", customer.Addresses[0].FirstName);
Assert.AreEqual("Smith", customer.Addresses[0].LastName);
Assert.AreEqual("Smith Co.", customer.Addresses[0].Company);
Assert.AreEqual("1 W Main St", customer.Addresses[0].StreetAddress);
Assert.AreEqual("Suite 330", customer.Addresses[0].ExtendedAddress);
Assert.AreEqual("Chicago", customer.Addresses[0].Locality);
Assert.AreEqual("IL", customer.Addresses[0].Region);
Assert.AreEqual("60622", customer.Addresses[0].PostalCode);
Assert.AreEqual("United States of America", customer.Addresses[0].CountryName);
}
[Test]
[Category("Integration")]
public void Find_IncludesApplePayCardsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.ApplePayAmex
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.ApplePayCards);
Assert.IsNotNull(customer.PaymentMethods);
ApplePayCard card = customer.ApplePayCards[0];
Assert.IsNotNull(card.Token);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
[Test]
[Category("Integration")]
public void Find_IncludesAndroidPayProxyCardsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.AndroidPayDiscover
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.AndroidPayCards);
Assert.IsNotNull(customer.PaymentMethods);
AndroidPayCard card = customer.AndroidPayCards[0];
Assert.IsNotNull(card.Token);
Assert.IsNotNull(card.GoogleTransactionId);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
[Test]
[Category("Integration")]
public void Find_IncludesAndroidPayNetworkTokensInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.AndroidPayMasterCard
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.AndroidPayCards);
Assert.IsNotNull(customer.PaymentMethods);
AndroidPayCard card = customer.AndroidPayCards[0];
Assert.IsNotNull(card.Token);
Assert.IsNotNull(card.GoogleTransactionId);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
[Test]
[Category("Integration")]
public void Find_IncludesAmexExpressCheckoutCardsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.AmexExpressCheckout
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.AmexExpressCheckoutCards);
Assert.IsNotNull(customer.PaymentMethods);
AmexExpressCheckoutCard card = customer.AmexExpressCheckoutCards[0];
Assert.IsNotNull(card.Token);
Assert.IsNotNull(card.CardMemberNumber);
Assert.AreEqual(card, customer.PaymentMethods[0]);
}
[Test]
[Category("Integration")]
public void Find_IncludesVenmoAccountsInPaymentMethods()
{
var createRequest = new CustomerRequest
{
PaymentMethodNonce = Nonce.VenmoAccount
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
Customer customer = gateway.Customer.Find(createdCustomer.Id);
Assert.IsNotNull(customer.VenmoAccounts);
Assert.IsNotNull(customer.PaymentMethods);
VenmoAccount account = customer.VenmoAccounts[0];
Assert.IsNotNull(account.Token);
Assert.IsNotNull(account.Username);
Assert.IsNotNull(account.VenmoUserId);
Assert.AreEqual(account, customer.PaymentMethods[0]);
}
[Test]
[Category("Integration")]
[ExpectedException(typeof(NotFoundException))]
public void Find_RaisesIfIdIsInvalid()
{
gateway.Customer.Find("DOES_NOT_EXIST_999");
}
[Test]
[Category("Unit")]
[ExpectedException(typeof(NotFoundException))]
public void Find_RaisesIfIdIsBlank()
{
gateway.Customer.Find(" ");
}
[Test]
[Category("Integration")]
public void Create_CanSetCustomFields()
{
var customFields = new Dictionary<string, string>();
customFields.Add("store_me", "a custom value");
var createRequest = new CustomerRequest()
{
CustomFields = customFields
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("a custom value", customer.CustomFields["store_me"]);
}
[Test]
[Category("Integration")]
public void Create_CreatesCustomerWithSpecifiedValues()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Macau",
CountryCodeAlpha2 = "MO",
CountryCodeAlpha3 = "MAC",
CountryCodeNumeric = "446"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Address billingAddress = customer.CreditCards[0].BillingAddress;
Assert.AreEqual("Macau", billingAddress.CountryName);
Assert.AreEqual("MO", billingAddress.CountryCodeAlpha2);
Assert.AreEqual("MAC", billingAddress.CountryCodeAlpha3);
Assert.AreEqual("446", billingAddress.CountryCodeNumeric);
}
[Test]
[Category("Integration")]
public void Create_withSecurityParams()
{
var createRequest = new CustomerRequest()
{
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
CVV = "123",
DeviceSessionId = "my_dsid"
}
};
Result<Customer> result = gateway.Customer.Create(createRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Create_withErrorsOnCountry()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "zzzzzz",
CountryCodeAlpha2 = "zz",
CountryCodeAlpha3 = "zzz",
CountryCodeNumeric = "000"
}
}
};
Result<Customer> result = gateway.Customer.Create(createRequest);
Assert.IsFalse(result.IsSuccess());
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_NAME_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryName")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA2_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeAlpha2")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_ALPHA3_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeAlpha3")[0].Code
);
Assert.AreEqual(
ValidationErrorCode.ADDRESS_COUNTRY_CODE_NUMERIC_IS_NOT_ACCEPTED,
result.Errors.ForObject("Customer").ForObject("CreditCard").ForObject("BillingAddress").OnField("CountryCodeNumeric")[0].Code
);
}
[Test]
[Category("Integration")]
public void Create_CreateCustomerWithCreditCard()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
CVV = "123",
CardholderName = "Michael Angelo"
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("510510", customer.CreditCards[0].Bin);
Assert.AreEqual("5100", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2012", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
}
[Test]
[Category("Integration")]
public void Create_CreateCustomerWithCreditCardAndVerificationAmount()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "05/12",
CVV = "123",
CardholderName = "Michael Angelo",
Options = new CreditCardOptionsRequest
{
VerifyCard = true,
VerificationAmount = "1.02"
}
}
};
Result<Customer> result = gateway.Customer.Create(createRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Create_CreateCustomerUsingAccessToken()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
};
BraintreeGateway oauthGateway = new BraintreeGateway(
"client_id$development$integration_client_id",
"client_secret$development$integration_client_secret"
);
string code = OAuthTestHelper.CreateGrant(oauthGateway, "integration_merchant_id", "read_write");
ResultImpl<OAuthCredentials> accessTokenResult = oauthGateway.OAuth.CreateTokenFromCode(new OAuthCredentialsRequest {
Code = code,
Scope = "read_write"
});
gateway = new BraintreeGateway(accessTokenResult.Target.AccessToken);
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
}
[Test]
[Category("Integration")]
public void Create_CreateCustomerWithCreditCardAndBillingAddress()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com",
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
CVV = "123",
CardholderName = "Michael Angelo",
BillingAddress = new CreditCardAddressRequest()
{
FirstName = "Michael",
LastName = "Angelo",
Company = "Angelo Co.",
StreetAddress = "1 E Main St",
ExtendedAddress = "Apt 3",
Locality = "Chicago",
Region = "IL",
PostalCode = "60622",
CountryName = "United States of America"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("Some Company", customer.Company);
Assert.AreEqual("hansolo64@example.com", customer.Email);
Assert.AreEqual("312.555.1111", customer.Phone);
Assert.AreEqual("312.555.1112", customer.Fax);
Assert.AreEqual("www.example.com", customer.Website);
Assert.AreEqual(DateTime.Now.Year, customer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.UpdatedAt.Value.Year);
Assert.AreEqual(1, customer.CreditCards.Length);
Assert.AreEqual("510510", customer.CreditCards[0].Bin);
Assert.AreEqual("5100", customer.CreditCards[0].LastFour);
Assert.AreEqual("05", customer.CreditCards[0].ExpirationMonth);
Assert.AreEqual("2012", customer.CreditCards[0].ExpirationYear);
Assert.AreEqual("Michael Angelo", customer.CreditCards[0].CardholderName);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, customer.CreditCards[0].UpdatedAt.Value.Year);
Assert.AreEqual(customer.Addresses[0].Id, customer.CreditCards[0].BillingAddress.Id);
Assert.AreEqual("Michael", customer.Addresses[0].FirstName);
Assert.AreEqual("Angelo", customer.Addresses[0].LastName);
Assert.AreEqual("Angelo Co.", customer.Addresses[0].Company);
Assert.AreEqual("1 E Main St", customer.Addresses[0].StreetAddress);
Assert.AreEqual("Apt 3", customer.Addresses[0].ExtendedAddress);
Assert.AreEqual("Chicago", customer.Addresses[0].Locality);
Assert.AreEqual("IL", customer.Addresses[0].Region);
Assert.AreEqual("60622", customer.Addresses[0].PostalCode);
Assert.AreEqual("United States of America", customer.Addresses[0].CountryName);
}
[Test]
[Category("Integration")]
public void Create_WithVenmoSdkPaymentMethodCode()
{
var createRequest = new CustomerRequest()
{
FirstName = "Michael",
LastName = "Angelo",
CreditCard = new CreditCardRequest()
{
VenmoSdkPaymentMethodCode = SandboxValues.VenmoSdk.VISA_PAYMENT_METHOD_CODE
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.AreEqual("Michael", customer.FirstName);
Assert.AreEqual("Angelo", customer.LastName);
Assert.AreEqual("411111", customer.CreditCards[0].Bin);
Assert.AreEqual("1111", customer.CreditCards[0].LastFour);
}
[Test]
[Category("Integration")]
public void Create_WithVenmoSdkSession()
{
var createRequest = new CustomerRequest()
{
CreditCard = new CreditCardRequest()
{
Number = "5105105105105100",
ExpirationDate = "05/12",
Options = new CreditCardOptionsRequest() {
VenmoSdkSession = SandboxValues.VenmoSdk.SESSION
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
Assert.IsTrue(customer.CreditCards[0].IsVenmoSdk.Value);
}
[Test]
[Category("Integration")]
public void Create_WithPaymentMethodNonce()
{
string nonce = TestHelper.GenerateUnlockedNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest{
CreditCard = new CreditCardRequest{
PaymentMethodNonce = nonce
}
});
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Create_WithPayPalPaymentMethodNonce()
{
string nonce = TestHelper.GenerateFuturePaymentPayPalNonce(gateway);
Result<Customer> result = gateway.Customer.Create(new CustomerRequest{
PaymentMethodNonce = nonce
});
Assert.IsTrue(result.IsSuccess());
var customer = result.Target;
Assert.AreEqual(1, customer.PayPalAccounts.Length);
Assert.AreEqual(customer.PayPalAccounts[0].Token, customer.DefaultPaymentMethod.Token);
}
#pragma warning disable 0618
[Test]
[Category("Integration")]
public void ConfirmTransparentRedirect_CreatesTheCustomer()
{
CustomerRequest trParams = new CustomerRequest();
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForCreate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
[Category("Integration")]
public void ConfirmTransparentRedirect_CreatesNestedElementsAndCustomFields()
{
CustomerRequest trParams = new CustomerRequest();
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe",
CreditCard = new CreditCardRequest
{
Number = SandboxValues.CreditCardNumber.VISA,
CardholderName = "John Doe",
ExpirationDate = "05/10",
BillingAddress = new CreditCardAddressRequest
{
CountryName = "Mexico",
CountryCodeAlpha2 = "MX",
CountryCodeAlpha3 = "MEX",
CountryCodeNumeric = "484"
}
},
CustomFields = new Dictionary<string, string>
{
{ "store_me", "a custom value" }
}
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForCreate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
Assert.AreEqual("John Doe", customer.CreditCards[0].CardholderName);
Assert.AreEqual("a custom value", customer.CustomFields["store_me"]);
Address address = customer.CreditCards[0].BillingAddress;
Assert.AreEqual("Mexico", address.CountryName);
Assert.AreEqual("MX", address.CountryCodeAlpha2);
Assert.AreEqual("MEX", address.CountryCodeAlpha3);
Assert.AreEqual("484", address.CountryCodeNumeric);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
[Category("Integration")]
public void ConfirmTransparentRedirect_UpdatesTheCustomer()
{
CustomerRequest createRequest = new CustomerRequest
{
FirstName = "Jane",
LastName = "Deer"
};
Customer createdCustomer = gateway.Customer.Create(createRequest).Target;
CustomerRequest trParams = new CustomerRequest
{
CustomerId = createdCustomer.Id
};
CustomerRequest request = new CustomerRequest
{
FirstName = "John",
LastName = "Doe"
};
string queryString = TestHelper.QueryStringForTR(trParams, request, gateway.Customer.TransparentRedirectURLForUpdate(), service);
Result<Customer> result = gateway.Customer.ConfirmTransparentRedirect(queryString);
Assert.IsTrue(result.IsSuccess());
Customer customer = result.Target;
Assert.AreEqual("John", customer.FirstName);
Assert.AreEqual("Doe", customer.LastName);
}
#pragma warning restore 0618
#pragma warning disable 0618
[Test]
[Category("Integration")]
public void Update_UpdatesCustomerAndNestedValuesViaTr()
{
var createRequest = new CustomerRequest()
{
FirstName = "Old First",
LastName = "Old Last",
CreditCard = new CreditCardRequest()
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "11111"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
CreditCard creditCard = customer.CreditCards[0];
Address address = creditCard.BillingAddress;
var trParams = new CustomerRequest()
{
CustomerId = customer.Id,
FirstName = "New First",
LastName = "New Last",
CreditCard = new CreditCardRequest()
{
ExpirationDate = "12/12",
Options = new CreditCardOptionsRequest()
{
UpdateExistingToken = creditCard.Token
},
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "44444",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148",
Options = new CreditCardAddressOptionsRequest()
{
UpdateExisting = true
}
}
}
};
string queryString = TestHelper.QueryStringForTR(trParams, new CustomerRequest(), gateway.Customer.TransparentRedirectURLForUpdate(), service);
Customer updatedCustomer = gateway.Customer.ConfirmTransparentRedirect(queryString).Target;
CreditCard updatedCreditCard = gateway.CreditCard.Find(creditCard.Token);
Address updatedAddress = gateway.Address.Find(customer.Id, address.Id);
Assert.AreEqual("New First", updatedCustomer.FirstName);
Assert.AreEqual("New Last", updatedCustomer.LastName);
Assert.AreEqual("12/2012", updatedCreditCard.ExpirationDate);
Assert.AreEqual("44444", updatedAddress.PostalCode);
Assert.AreEqual("Chad", updatedAddress.CountryName);
Assert.AreEqual("TD", updatedAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", updatedAddress.CountryCodeAlpha3);
Assert.AreEqual("148", updatedAddress.CountryCodeNumeric);
}
#pragma warning restore 0618
[Test]
[Category("Integration")]
public void Update_UpdatesCustomerWithNewValues()
{
string oldId = Guid.NewGuid().ToString();
string newId = Guid.NewGuid().ToString();
var createRequest = new CustomerRequest()
{
Id = oldId,
FirstName = "Old First",
LastName = "Old Last",
Company = "Old Company",
Email = "old@example.com",
Phone = "312.555.1111 xOld",
Fax = "312.555.1112 xOld",
Website = "old.example.com"
};
gateway.Customer.Create(createRequest);
var updateRequest = new CustomerRequest()
{
Id = newId,
FirstName = "Michael",
LastName = "Angelo",
Company = "Some Company",
Email = "hansolo64@example.com",
Phone = "312.555.1111",
Fax = "312.555.1112",
Website = "www.example.com"
};
Customer updatedCustomer = gateway.Customer.Update(oldId, updateRequest).Target;
Assert.AreEqual(newId, updatedCustomer.Id);
Assert.AreEqual("Michael", updatedCustomer.FirstName);
Assert.AreEqual("Angelo", updatedCustomer.LastName);
Assert.AreEqual("Some Company", updatedCustomer.Company);
Assert.AreEqual("hansolo64@example.com", updatedCustomer.Email);
Assert.AreEqual("312.555.1111", updatedCustomer.Phone);
Assert.AreEqual("312.555.1112", updatedCustomer.Fax);
Assert.AreEqual("www.example.com", updatedCustomer.Website);
Assert.AreEqual(DateTime.Now.Year, updatedCustomer.CreatedAt.Value.Year);
Assert.AreEqual(DateTime.Now.Year, updatedCustomer.UpdatedAt.Value.Year);
}
[Test]
[Category("Integration")]
public void Update_UpdatesCustomerAndNestedValues()
{
var createRequest = new CustomerRequest()
{
FirstName = "Old First",
LastName = "Old Last",
CreditCard = new CreditCardRequest()
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "11111"
}
}
};
Customer customer = gateway.Customer.Create(createRequest).Target;
CreditCard creditCard = customer.CreditCards[0];
Address address = creditCard.BillingAddress;
var updateRequest = new CustomerRequest()
{
FirstName = "New First",
LastName = "New Last",
CreditCard = new CreditCardRequest()
{
ExpirationDate = "12/12",
Options = new CreditCardOptionsRequest()
{
UpdateExistingToken = creditCard.Token
},
BillingAddress = new CreditCardAddressRequest()
{
PostalCode = "44444",
CountryName = "Chad",
CountryCodeAlpha2 = "TD",
CountryCodeAlpha3 = "TCD",
CountryCodeNumeric = "148",
Options = new CreditCardAddressOptionsRequest()
{
UpdateExisting = true
}
}
}
};
Customer updatedCustomer = gateway.Customer.Update(customer.Id, updateRequest).Target;
CreditCard updatedCreditCard = gateway.CreditCard.Find(creditCard.Token);
Address updatedAddress = gateway.Address.Find(customer.Id, address.Id);
Assert.AreEqual("New First", updatedCustomer.FirstName);
Assert.AreEqual("New Last", updatedCustomer.LastName);
Assert.AreEqual("12/2012", updatedCreditCard.ExpirationDate);
Assert.AreEqual("44444", updatedAddress.PostalCode);
Assert.AreEqual("Chad", updatedAddress.CountryName);
Assert.AreEqual("TD", updatedAddress.CountryCodeAlpha2);
Assert.AreEqual("TCD", updatedAddress.CountryCodeAlpha3);
Assert.AreEqual("148", updatedAddress.CountryCodeNumeric);
}
[Test]
[Category("Integration")]
public void Update_MakeExistingCreditCardPaymentMethodTheDefaultUsingOptions()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var creditCardToken1 = GenerateToken();
var creditCardCreateRequest1 = new PaymentMethodRequest
{
CustomerId = customer.Id,
PaymentMethodNonce = Nonce.TransactableMasterCard,
Token = creditCardToken1
};
PaymentMethod creditCardPaymentMethod1 = gateway.PaymentMethod.Create(creditCardCreateRequest1).Target;
customer = gateway.Customer.Find(customer.Id);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, creditCardToken1);
var creditCardToken2 = GenerateToken();
var creditCardCreateRequest2 = new PaymentMethodRequest(){
CustomerId = customer.Id,
PaymentMethodNonce = Nonce.TransactableVisa,
Token = creditCardToken2
};
PaymentMethod creditCardPaymentMethod2 = gateway.PaymentMethod.Create(creditCardCreateRequest2).Target;
customer = gateway.Customer.Find(customer.Id);
Assert.AreNotEqual(customer.DefaultPaymentMethod.Token, creditCardToken2);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, creditCardToken1);
var updateRequest = new CustomerRequest
{
CreditCard = new CreditCardRequest()
{
Options = new CreditCardOptionsRequest()
{
UpdateExistingToken = creditCardToken2,
MakeDefault = true
}
}
};
gateway.Customer.Update(customer.Id, updateRequest);
customer = gateway.Customer.Find(customer.Id);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, creditCardToken2);
}
[Test]
[Category("Integration")]
public void Update_MakeExistingPaymentMethodTheDefaultUsingDefaultPaymentMethodToken()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
var coinbaseToken = GenerateToken();
var coinbaseCreateRequest = new PaymentMethodRequest
{
CustomerId = customer.Id,
PaymentMethodNonce = Nonce.Coinbase,
Token = coinbaseToken
};
PaymentMethod coinbasePaymentMethod = gateway.PaymentMethod.Create(coinbaseCreateRequest).Target;
customer = gateway.Customer.Find(customer.Id);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, coinbaseToken);
var venmoToken = GenerateToken();
var venmoCreateRequest = new PaymentMethodRequest(){
CustomerId = customer.Id,
PaymentMethodNonce = Nonce.VenmoAccount,
Token = venmoToken
};
PaymentMethod venmoPaymentMethod = gateway.PaymentMethod.Create(venmoCreateRequest).Target;
customer = gateway.Customer.Find(customer.Id);
Assert.AreNotEqual(customer.DefaultPaymentMethod.Token, venmoToken);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, coinbaseToken);
var updateRequest = new CustomerRequest
{
DefaultPaymentMethodToken = venmoToken
};
gateway.Customer.Update(customer.Id, updateRequest);
customer = gateway.Customer.Find(customer.Id);
Assert.AreEqual(customer.DefaultPaymentMethod.Token, venmoToken);
}
private String GenerateToken()
{
return String.Format("token{0}", random.Next());
}
[Test]
[Category("Integration")]
public void Update_UpdatesCustomerWithVerificationAmount()
{
var createRequest = new CustomerRequest()
{
FirstName = "Joe",
LastName = "Shmo",
};
Customer customer = gateway.Customer.Create(createRequest).Target;
var updateRequest = new CustomerRequest()
{
CreditCard = new CreditCardRequest()
{
Number = "5555555555554444",
ExpirationDate = "10/10",
Options = new CreditCardOptionsRequest
{
VerifyCard = true,
VerificationAmount = "1.02"
}
}
};
Result<Customer> result = gateway.Customer.Create(updateRequest);
Assert.IsTrue(result.IsSuccess());
}
[Test]
[Category("Integration")]
public void Update_AcceptsNestedBillingAddressId()
{
Customer customer = gateway.Customer.Create(new CustomerRequest()).Target;
AddressRequest addressRequest = new AddressRequest
{
FirstName = "John",
LastName = "Doe"
};
Address address = gateway.Address.Create(customer.Id, addressRequest).Target;
var updateRequest = new CustomerRequest
{
CreditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "10/10",
BillingAddressId = address.Id
}
};
Customer updatedCustomer = gateway.Customer.Update(customer.Id, updateRequest).Target;
Address billingAddress = updatedCustomer.CreditCards[0].BillingAddress;
Assert.AreEqual(address.Id, billingAddress.Id);
Assert.AreEqual("John", billingAddress.FirstName);
Assert.AreEqual("Doe", billingAddress.LastName);
}
[Test]
[Category("Integration")]
public void Update_AcceptsPaymentMethodNonce()
{
var create = new CustomerRequest
{
CreditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "10/18",
}
};
var customer = gateway.Customer.Create(create).Target;
var update = new CustomerRequest
{
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
var updatedCustomer = gateway.Customer.Update(customer.Id, update).Target;
Assert.AreEqual(1, updatedCustomer.PayPalAccounts.Length);
Assert.AreEqual(1, updatedCustomer.CreditCards.Length);
Assert.AreEqual(2, updatedCustomer.PaymentMethods.Length);
}
[Test]
[Category("Integration")]
[ExpectedException(typeof(NotFoundException))]
public void Delete_DeletesTheCustomer()
{
string id = Guid.NewGuid().ToString();
gateway.Customer.Create(new CustomerRequest() { Id = id });
Assert.AreEqual(id, gateway.Customer.Find(id).Id);
Result<Customer> result = gateway.Customer.Delete(id);
Assert.IsTrue(result.IsSuccess());
gateway.Customer.Find(id);
}
[Test]
[Category("Integration")]
public void All() {
ResourceCollection<Customer> collection = gateway.Customer.All();
Assert.IsTrue(collection.MaximumCount > 100);
List<string> items = new List<string>();
foreach (Customer item in collection) {
items.Add(item.Id);
}
HashSet<string> uniqueItems = new HashSet<string>(items);
Assert.AreEqual(uniqueItems.Count, collection.MaximumCount);
}
[Test]
[Category("Integration")]
public void Search_FindDuplicateCardsGivenPaymentMethodToken()
{
CreditCardRequest creditCard = new CreditCardRequest
{
Number = "4111111111111111",
ExpirationDate = "05/2012"
};
CustomerRequest jimRequest = new CustomerRequest
{
FirstName = "Jim",
CreditCard = creditCard
};
CustomerRequest joeRequest = new CustomerRequest
{
FirstName = "Jim",
CreditCard = creditCard
};
Customer jim = gateway.Customer.Create(jimRequest).Target;
Customer joe = gateway.Customer.Create(joeRequest).Target;
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
PaymentMethodTokenWithDuplicates.Is(jim.CreditCards[0].Token);
ResourceCollection<Customer> collection = gateway.Customer.Search(searchRequest);
List<string> customerIds = new List<string>();
foreach (Customer customer in collection) {
customerIds.Add(customer.Id);
}
Assert.IsTrue(customerIds.Contains(jim.Id));
Assert.IsTrue(customerIds.Contains(joe.Id));
}
[Test]
[Category("Integration")]
public void Search_OnAllTextFields()
{
string creditCardToken = string.Format("cc{0}", new Random().Next(1000000).ToString());
CustomerRequest request = new CustomerRequest
{
Company = "Braintree",
Email = "smith@example.com",
Fax = "5551231234",
FirstName = "Tom",
LastName = "Smith",
Phone = "5551231235",
Website = "http://example.com",
CreditCard = new CreditCardRequest
{
CardholderName = "Tim Toole",
Number = "4111111111111111",
ExpirationDate = "05/2012",
Token = creditCardToken,
BillingAddress = new CreditCardAddressRequest
{
Company = "Braintree",
CountryName = "United States of America",
ExtendedAddress = "Suite 123",
FirstName = "Drew",
LastName = "Michaelson",
Locality = "Chicago",
PostalCode = "12345",
Region = "IL",
StreetAddress = "123 Main St"
}
}
};
Customer customer = gateway.Customer.Create(request).Target;
customer = gateway.Customer.Find(customer.Id);
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
FirstName.Is("Tom").
LastName.Is("Smith").
Company.Is("Braintree").
Email.Is("smith@example.com").
Website.Is("http://example.com").
Fax.Is("5551231234").
Phone.Is("5551231235").
AddressFirstName.Is("Drew").
AddressLastName.Is("Michaelson").
AddressLocality.Is("Chicago").
AddressPostalCode.Is("12345").
AddressRegion.Is("IL").
AddressCountryName.Is("United States of America").
AddressStreetAddress.Is("123 Main St").
AddressExtendedAddress.Is("Suite 123").
PaymentMethodToken.Is(creditCardToken).
CardholderName.Is("Tim Toole").
CreditCardNumber.Is("4111111111111111").
CreditCardExpirationDate.Is("05/2012");
ResourceCollection<Customer> collection = gateway.Customer.Search(searchRequest);
Assert.AreEqual(1, collection.MaximumCount);
Assert.AreEqual(customer.Id, collection.FirstItem.Id);
}
[Test]
[Category("Integration")]
public void Search_OnCreatedAt()
{
CustomerRequest request = new CustomerRequest();
Customer customer = gateway.Customer.Create(request).Target;
DateTime createdAt = customer.CreatedAt.Value;
DateTime threeHoursEarlier = createdAt.AddHours(-3);
DateTime oneHourEarlier = createdAt.AddHours(-1);
DateTime oneHourLater = createdAt.AddHours(1);
CustomerSearchRequest searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.Between(oneHourEarlier, oneHourLater);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.GreaterThanOrEqualTo(oneHourEarlier);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.LessThanOrEqualTo(oneHourLater);
Assert.AreEqual(1, gateway.Customer.Search(searchRequest).MaximumCount);
searchRequest = new CustomerSearchRequest().
Id.Is(customer.Id).
CreatedAt.Between(threeHoursEarlier, oneHourEarlier);
Assert.AreEqual(0, gateway.Customer.Search(searchRequest).MaximumCount);
}
[Test]
[Category("Integration")]
public void Search_OnPayPalAccountEmail()
{
var request = new CustomerRequest
{
PaymentMethodNonce = Nonce.PayPalFuturePayment
};
var customer = gateway.Customer.Create(request).Target;
var search = new CustomerSearchRequest().
Id.Is(customer.Id).
PayPalAccountEmail.Is(customer.PayPalAccounts[0].Email);
Assert.AreEqual(1, gateway.Customer.Search(search).MaximumCount);
}
}
}
| |
//
// Copyright 2014-2015 Amazon.com,
// Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Amazon Software License (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/asl/
//
// or in the "license" file accompanying this file. This file is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, express or implied. See the License
// for the specific language governing permissions and
// limitations under the License.
//
#pragma warning disable 1587,3021
#region Header
///
/// JsonWriter.cs
/// Stream-like facility to output JSON text.
///
/// The authors disclaim copyright to this source code. For more details, see
/// the COPYING file included with this distribution.
///
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
namespace ThirdParty.Json.LitJson
{
internal enum Condition
{
InArray,
InObject,
NotAProperty,
Property,
Value
}
internal class WriterContext
{
public int Count;
public bool InArray;
public bool InObject;
public bool ExpectingValue;
public int Padding;
}
public class JsonWriter
{
#region Fields
private static NumberFormatInfo number_format;
private WriterContext context;
private Stack<WriterContext> ctx_stack;
private bool has_reached_end;
private char[] hex_seq;
private int indentation;
private int indent_value;
private StringBuilder inst_string_builder;
private bool pretty_print;
private bool validate;
private TextWriter writer;
#endregion
#region Properties
public int IndentValue {
get { return indent_value; }
set {
indentation = (indentation / indent_value) * value;
indent_value = value;
}
}
public bool PrettyPrint {
get { return pretty_print; }
set { pretty_print = value; }
}
public TextWriter TextWriter {
get { return writer; }
}
public bool Validate {
get { return validate; }
set { validate = value; }
}
#endregion
#region Constructors
static JsonWriter ()
{
number_format = NumberFormatInfo.InvariantInfo;
}
public JsonWriter ()
{
inst_string_builder = new StringBuilder ();
writer = new StringWriter (inst_string_builder);
Init ();
}
public JsonWriter (StringBuilder sb) :
this (new StringWriter (sb))
{
}
public JsonWriter (TextWriter writer)
{
if (writer == null)
throw new ArgumentNullException ("writer");
this.writer = writer;
Init ();
}
#endregion
#region Private Methods
private void DoValidation (Condition cond)
{
if (! context.ExpectingValue)
context.Count++;
if (! validate)
return;
if (has_reached_end)
throw new JsonException (
"A complete JSON symbol has already been written");
switch (cond) {
case Condition.InArray:
if (! context.InArray)
throw new JsonException (
"Can't close an array here");
break;
case Condition.InObject:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't close an object here");
break;
case Condition.NotAProperty:
if (context.InObject && ! context.ExpectingValue)
throw new JsonException (
"Expected a property");
break;
case Condition.Property:
if (! context.InObject || context.ExpectingValue)
throw new JsonException (
"Can't add a property here");
break;
case Condition.Value:
if (! context.InArray &&
(! context.InObject || ! context.ExpectingValue))
throw new JsonException (
"Can't add a value here");
break;
}
}
private void Init ()
{
has_reached_end = false;
hex_seq = new char[4];
indentation = 0;
indent_value = 4;
pretty_print = false;
validate = true;
ctx_stack = new Stack<WriterContext> ();
context = new WriterContext ();
ctx_stack.Push (context);
}
private static void IntToHex (int n, char[] hex)
{
int num;
for (int i = 0; i < 4; i++) {
num = n % 16;
if (num < 10)
hex[3 - i] = (char) ('0' + num);
else
hex[3 - i] = (char) ('A' + (num - 10));
n >>= 4;
}
}
private void Indent ()
{
if (pretty_print)
indentation += indent_value;
}
private void Put (string str)
{
if (pretty_print && ! context.ExpectingValue)
for (int i = 0; i < indentation; i++)
writer.Write (' ');
writer.Write (str);
}
private void PutNewline ()
{
PutNewline (true);
}
private void PutNewline (bool add_comma)
{
if (add_comma && ! context.ExpectingValue &&
context.Count > 1)
writer.Write (',');
if (pretty_print && ! context.ExpectingValue)
writer.Write ("\r\n");
}
private void PutString (string str)
{
Put (String.Empty);
writer.Write ('"');
int n = str.Length;
for (int i = 0; i < n; i++)
{
char c = str[i];
switch (c) {
case '\n':
writer.Write ("\\n");
continue;
case '\r':
writer.Write ("\\r");
continue;
case '\t':
writer.Write ("\\t");
continue;
case '"':
case '\\':
writer.Write ('\\');
writer.Write (c);
continue;
case '\f':
writer.Write ("\\f");
continue;
case '\b':
writer.Write ("\\b");
continue;
}
if ((int) c >= 32 && (int) c <= 126) {
writer.Write (c);
continue;
}
if (c < ' ' || (c >= '\u0080' && c < '\u00a0'))
{
// Turn into a \uXXXX sequence
IntToHex((int)c, hex_seq);
writer.Write("\\u");
writer.Write(hex_seq);
}
else
{
writer.Write(c);
}
}
writer.Write ('"');
}
private void Unindent ()
{
if (pretty_print)
indentation -= indent_value;
}
#endregion
public override string ToString ()
{
if (inst_string_builder == null)
return String.Empty;
return inst_string_builder.ToString ();
}
public void Reset ()
{
has_reached_end = false;
ctx_stack.Clear ();
context = new WriterContext ();
ctx_stack.Push (context);
if (inst_string_builder != null)
inst_string_builder.Remove (0, inst_string_builder.Length);
}
public void Write (bool boolean)
{
DoValidation (Condition.Value);
PutNewline ();
Put (boolean ? "true" : "false");
context.ExpectingValue = false;
}
public void Write (decimal number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (double number)
{
DoValidation (Condition.Value);
PutNewline ();
// Modified to support roundtripping of double.MaxValue
string str = number.ToString("R", CultureInfo.InvariantCulture);
Put (str);
if (str.IndexOf ('.') == -1 &&
str.IndexOf ('E') == -1)
writer.Write (".0");
context.ExpectingValue = false;
}
public void Write (int number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write (long number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number));
context.ExpectingValue = false;
}
public void Write (string str)
{
DoValidation (Condition.Value);
PutNewline ();
if (str == null)
Put ("null");
else
PutString (str);
context.ExpectingValue = false;
}
public void WriteRaw(string str)
{
DoValidation(Condition.Value);
PutNewline();
if (str == null)
Put("null");
else
Put(str);
context.ExpectingValue = false;
}
[CLSCompliant(false)]
public void Write (ulong number)
{
DoValidation (Condition.Value);
PutNewline ();
Put (Convert.ToString (number, number_format));
context.ExpectingValue = false;
}
public void Write(DateTime date)
{
DoValidation(Condition.Value);
PutNewline();
Put(Amazon.Util.AWSSDKUtils.ConvertToUnixEpochMilliSeconds(date).ToString(CultureInfo.InvariantCulture));
context.ExpectingValue = false;
}
public void WriteArrayEnd ()
{
DoValidation (Condition.InArray);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("]");
}
public void WriteArrayStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("[");
context = new WriterContext ();
context.InArray = true;
ctx_stack.Push (context);
Indent ();
}
public void WriteObjectEnd ()
{
DoValidation (Condition.InObject);
PutNewline (false);
ctx_stack.Pop ();
if (ctx_stack.Count == 1)
has_reached_end = true;
else {
context = ctx_stack.Peek ();
context.ExpectingValue = false;
}
Unindent ();
Put ("}");
}
public void WriteObjectStart ()
{
DoValidation (Condition.NotAProperty);
PutNewline ();
Put ("{");
context = new WriterContext ();
context.InObject = true;
ctx_stack.Push (context);
Indent ();
}
public void WritePropertyName (string property_name)
{
DoValidation (Condition.Property);
PutNewline ();
PutString (property_name);
if (pretty_print) {
if (property_name.Length > context.Padding)
context.Padding = property_name.Length;
for (int i = context.Padding - property_name.Length;
i >= 0; i--)
writer.Write (' ');
writer.Write (": ");
} else
writer.Write (':');
context.ExpectingValue = true;
}
}
}
#pragma warning restore 1587,3021
| |
/* ====================================================================
Licensed to the Apache Software Foundation (ASF) Under one or more
contributor license agreements. See the NOTICE file distributed with
this work for Additional information regarding copyright ownership.
The ASF licenses this file to You Under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed Under the License is distributed on an "AS Is" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations Under the License.
==================================================================== */
namespace NPOI.SS.Formula.PTG
{
using System;
using System.Text;
using NPOI.Util;
using NPOI.HSSF.Record;
/**
* "Special Attributes"
* This seems to be a Misc Stuff and Junk record. One function it serves Is
* in SUM functions (i.e. SUM(A1:A3) causes an area PTG then an ATTR with the SUM option Set)
* @author andy
* @author Jason Height (jheight at chariot dot net dot au)
*/
internal class AttrPtg : ControlPtg
{
public const byte sid = 0x19;
private static int SIZE = 4;
private byte field_1_options;
private short field_2_data;
/** only used for tAttrChoose: table of offsets to starts of args */
private int[] _jumpTable;
/** only used for tAttrChoose: offset to the tFuncVar for CHOOSE() */
private int _chooseFuncOffset;
// flags 'volatile' and 'space', can be combined.
// OOO spec says other combinations are theoretically possible but not likely to occur.
private static BitField semiVolatile = BitFieldFactory.GetInstance(0x01);
private static BitField optiIf = BitFieldFactory.GetInstance(0x02);
private static BitField optiChoose = BitFieldFactory.GetInstance(0x04);
private static BitField optiSkip = BitFieldFactory.GetInstance(0x08); // skip
private static BitField optiSum = BitFieldFactory.GetInstance(0x10);
private static BitField baxcel = BitFieldFactory.GetInstance(0x20); // 'assignment-style formula in a macro sheet'
private static BitField space = BitFieldFactory.GetInstance(0x40);
public static AttrPtg SUM = new AttrPtg(0x0010, 0, null, -1);
internal class SpaceType
{
/** 00H = Spaces before the next token (not allowed before tParen token) */
public static int SPACE_BEFORE = 0x00;
/** 01H = Carriage returns before the next token (not allowed before tParen token) */
public static int CR_BEFORE = 0x01;
/** 02H = Spaces before opening parenthesis (only allowed before tParen token) */
public static int SPACE_BEFORE_OPEN_PAREN = 0x02;
/** 03H = Carriage returns before opening parenthesis (only allowed before tParen token) */
public static int CR_BEFORE_OPEN_PAREN = 0x03;
/** 04H = Spaces before closing parenthesis (only allowed before tParen, tFunc, and tFuncVar tokens) */
public static int SPACE_BEFORE_CLOSE_PAREN = 0x04;
/** 05H = Carriage returns before closing parenthesis (only allowed before tParen, tFunc, and tFuncVar tokens) */
public static int CR_BEFORE_CLOSE_PAREN = 0x05;
/** 06H = Spaces following the equality sign (only in macro sheets) */
public static int SPACE_AFTER_EQUALITY = 0x06;
}
public AttrPtg()
{
_jumpTable = null;
_chooseFuncOffset = -1;
}
public AttrPtg(ILittleEndianInput in1)
{
field_1_options =(byte)in1.ReadByte();
field_2_data = in1.ReadShort();
if (IsOptimizedChoose)
{
int nCases = field_2_data;
int[] jumpTable = new int[nCases];
for (int i = 0; i < jumpTable.Length; i++)
{
jumpTable[i] = in1.ReadUShort();
}
_jumpTable = jumpTable;
_chooseFuncOffset = in1.ReadUShort();
}
else
{
_jumpTable = null;
_chooseFuncOffset = -1;
}
}
private AttrPtg(int options, int data, int[] jt, int chooseFuncOffset)
{
field_1_options = (byte)options;
field_2_data = (short)data;
_jumpTable = jt;
_chooseFuncOffset = chooseFuncOffset;
}
/// <summary>
/// Creates the space.
/// </summary>
/// <param name="type">a constant from SpaceType</param>
/// <param name="count">The count.</param>
public static AttrPtg CreateSpace(int type, int count)
{
int data = type & 0x00FF | (count << 8) & 0x00FFFF;
return new AttrPtg(space.Set(0), data, null, -1);
}
/// <summary>
/// Creates if.
/// </summary>
/// <param name="dist">distance (in bytes) to start of either
/// tFuncVar(IF) token (when false parameter is not present).</param>
public static AttrPtg CreateIf(int dist)
{
return new AttrPtg(optiIf.Set(0), dist, null, -1);
}
/// <summary>
/// Creates the skip.
/// </summary>
/// <param name="dist">distance (in bytes) to position behind tFuncVar(IF) token (minus 1).</param>
public static AttrPtg CreateSkip(int dist)
{
return new AttrPtg(optiSkip.Set(0), dist, null, -1);
}
public static AttrPtg GetSumSingle()
{
return new AttrPtg(optiSum.Set(0), 0, null, -1);
}
public bool IsSemiVolatile
{
get { return semiVolatile.IsSet(field_1_options); }
}
public bool IsOptimizedIf
{
get { return optiIf.IsSet(field_1_options); }
set { field_1_options = optiIf.SetByteBoolean(field_1_options, value); }
}
public bool IsOptimizedChoose
{
get { return optiChoose.IsSet(field_1_options); }
}
public bool IsSum
{
get { return optiSum.IsSet(field_1_options); }
set { field_1_options = optiSum.SetByteBoolean(field_1_options, value); }
}
// lets hope no one uses this anymore
public bool IsBaxcel
{
get{return baxcel.IsSet(field_1_options);}
}
// biff3&4 only shouldn't happen anymore
public bool IsSpace
{
get { return space.IsSet(field_1_options); }
}
public bool IsSkip
{
get { return optiSkip.IsSet(field_1_options); }
}
public short Data
{
get { return field_2_data; }
set { field_2_data = value; }
}
public int[] JumpTable
{
get
{
return (int[])_jumpTable.Clone();
}
}
public int ChooseFuncOffset
{
get
{
if (_jumpTable == null)
{
throw new InvalidOperationException("Not tAttrChoose");
}
return _chooseFuncOffset;
}
}
public override String ToString()
{
StringBuilder sb = new StringBuilder(64);
sb.Append(GetType().Name).Append(" [");
if (IsSemiVolatile)
{
sb.Append("volatile ");
}
if (IsSpace)
{
sb.Append("space count=").Append((field_2_data >> 8) & 0x00FF);
sb.Append(" type=").Append(field_2_data & 0x00FF).Append(" ");
}
// the rest seem to be mutually exclusive
if (IsOptimizedIf)
{
sb.Append("if dist=").Append(Data);
}
else if (IsOptimizedChoose)
{
sb.Append("choose nCases=").Append(Data);
}
else if (IsSkip)
{
sb.Append("skip dist=").Append(Data);
}
else if (IsSum)
{
sb.Append("sum ");
}
else if (IsBaxcel)
{
sb.Append("assign ");
}
sb.Append("]");
return sb.ToString();
}
public override void Write(ILittleEndianOutput out1)
{
out1.WriteByte(sid + PtgClass);
out1.WriteByte(field_1_options);
out1.WriteShort(field_2_data);
int[] jt = _jumpTable;
if (jt != null)
{
for (int i = 0; i < jt.Length; i++)
{
out1.WriteShort(jt[i]);
}
out1.WriteShort(_chooseFuncOffset);
}
}
public override int Size
{
get
{
if (_jumpTable != null)
{
return SIZE + (_jumpTable.Length + 1) * LittleEndianConsts.SHORT_SIZE;
}
return SIZE;
}
}
public String ToFormulaString(String[] operands)
{
if (space.IsSet(field_1_options))
{
return operands[0];
}
else if (optiIf.IsSet(field_1_options))
{
return ToFormulaString() + "(" + operands[0] + ")";
}
else if (optiSkip.IsSet(field_1_options))
{
return ToFormulaString() + operands[0]; //goto Isn't a real formula element should not show up
}
else
{
return ToFormulaString() + "(" + operands[0] + ")";
}
}
public int NumberOfOperands
{
get { return 1; }
}
public int Type
{
get { return -1; }
}
public override String ToFormulaString()
{
if (semiVolatile.IsSet(field_1_options))
{
return "ATTR(semiVolatile)";
}
if (optiIf.IsSet(field_1_options))
{
return "IF";
}
if (optiChoose.IsSet(field_1_options))
{
return "CHOOSE";
}
if (optiSkip.IsSet(field_1_options))
{
return "";
}
if (optiSum.IsSet(field_1_options))
{
return "SUM";
}
if (baxcel.IsSet(field_1_options))
{
return "ATTR(baxcel)";
}
if (space.IsSet(field_1_options))
{
return "";
}
return "UNKNOWN ATTRIBUTE";
}
public override Object Clone()
{
int[] jt;
if (_jumpTable == null)
{
jt = null;
}
else
{
jt = (int[])_jumpTable.Clone();
}
return new AttrPtg(field_1_options, field_2_data, jt, _chooseFuncOffset);
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using GameAnalyticsSDK.Events;
using GameAnalyticsSDK.Setup;
using GameAnalyticsSDK.Wrapper;
using GameAnalyticsSDK.State;
#if UNITY_EDITOR
using UnityEditor;
using System.IO;
#endif
namespace GameAnalyticsSDK
{
[RequireComponent(typeof(GA_SpecialEvents))]
[ExecuteInEditMode]
public partial class GameAnalytics : MonoBehaviour
{
#region public values
private static Settings _settings;
public static Settings SettingsGA
{
get
{
if(_settings == null)
{
InitAPI();
}
return _settings;
}
private set{ _settings = value; }
}
private static GameAnalytics _instance;
#endregion
#region unity derived methods
#if UNITY_EDITOR
void OnEnable()
{
EditorApplication.hierarchyWindowItemOnGUI += GameAnalytics.HierarchyWindowCallback;
if(Application.isPlaying)
_instance = this;
}
void OnDisable()
{
EditorApplication.hierarchyWindowItemOnGUI -= GameAnalytics.HierarchyWindowCallback;
}
#endif
public void Awake()
{
if (!Application.isPlaying)
{
return;
}
if(_instance != null)
{
// only one system tracker allowed per scene
Debug.LogWarning("Destroying duplicate GameAnalytics object - only one is allowed per scene!");
Destroy(gameObject);
return;
}
_instance = this;
DontDestroyOnLoad(gameObject);
Application.logMessageReceived += GA_Debug.HandleLog;
Initialize();
}
void OnDestroy()
{
if(!Application.isPlaying)
return;
if(_instance == this)
_instance = null;
}
void OnApplicationPause(bool pauseStatus)
{
#if UNITY_ANDROID && !UNITY_EDITOR
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = jc.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaClass ga = new AndroidJavaClass("com.gameanalytics.sdk.GAPlatform");
if (pauseStatus) {
ga.CallStatic("onActivityPaused", activity);
}
else {
ga.CallStatic("onActivityResumed", activity);
}
#endif
}
void OnApplicationQuit()
{
#if UNITY_ANDROID && !UNITY_EDITOR
if(!SettingsGA.UseManualSessionHandling)
{
AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = jc.GetStatic<AndroidJavaObject>("currentActivity");
AndroidJavaClass ga = new AndroidJavaClass("com.gameanalytics.sdk.GAPlatform");
ga.CallStatic("onActivityStopped", activity);
}
#elif (!UNITY_EDITOR && !UNITY_IOS && !UNITY_ANDROID && !UNITY_TVOS && !UNITY_WEBGL && !UNITY_TIZEN)
if(!SettingsGA.UseManualSessionHandling)
{
GameAnalyticsSDK.Net.GameAnalytics.OnStop();
}
#endif
}
#endregion
private static void InitAPI()
{
try
{
_settings = (Settings)Resources.Load("GameAnalytics/Settings", typeof(Settings));
GameAnalyticsSDK.State.GAState.Init();
#if UNITY_EDITOR
if(_settings == null)
{
//If the settings asset doesn't exist, then create it. We require a resources folder
if(!Directory.Exists(Application.dataPath + "/Resources"))
{
Directory.CreateDirectory(Application.dataPath + "/Resources");
}
if(!Directory.Exists(Application.dataPath + "/Resources/GameAnalytics"))
{
Directory.CreateDirectory(Application.dataPath + "/Resources/GameAnalytics");
Debug.LogWarning("GameAnalytics: Resources/GameAnalytics folder is required to store settings. it was created ");
}
const string path = "Assets/Resources/GameAnalytics/Settings.asset";
if(File.Exists(path))
{
AssetDatabase.DeleteAsset(path);
AssetDatabase.Refresh();
}
var asset = ScriptableObject.CreateInstance<Settings>();
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
Debug.LogWarning("GameAnalytics: Settings file didn't exist and was created");
Selection.activeObject = asset;
//save reference
_settings = asset;
}
#endif
}
catch(System.Exception e)
{
Debug.Log("Error getting Settings in InitAPI: " + e.Message);
}
}
private static void Initialize()
{
if(!Application.isPlaying)
return; // no need to setup anything else if we are in the editor and not playing
if(SettingsGA.InfoLogBuild)
{
GA_Setup.SetInfoLog(true);
}
if(SettingsGA.VerboseLogBuild)
{
GA_Setup.SetVerboseLog(true);
}
int platformIndex = GetPlatformIndex();
GA_Wrapper.SetUnitySdkVersion("unity " + Settings.VERSION);
GA_Wrapper.SetUnityEngineVersion("unity " + GetUnityVersion());
if(platformIndex >= 0)
{
GA_Wrapper.SetBuild(SettingsGA.Build[platformIndex]);
}
if(SettingsGA.CustomDimensions01.Count > 0)
{
GA_Setup.SetAvailableCustomDimensions01(SettingsGA.CustomDimensions01);
}
if(SettingsGA.CustomDimensions02.Count > 0)
{
GA_Setup.SetAvailableCustomDimensions02(SettingsGA.CustomDimensions02);
}
if(SettingsGA.CustomDimensions03.Count > 0)
{
GA_Setup.SetAvailableCustomDimensions03(SettingsGA.CustomDimensions03);
}
if(SettingsGA.ResourceItemTypes.Count > 0)
{
GA_Setup.SetAvailableResourceItemTypes(SettingsGA.ResourceItemTypes);
}
if(SettingsGA.ResourceCurrencies.Count > 0)
{
GA_Setup.SetAvailableResourceCurrencies(SettingsGA.ResourceCurrencies);
}
if(SettingsGA.UseManualSessionHandling)
{
SetEnabledManualSessionHandling(true);
}
if(platformIndex >= 0)
{
if (!SettingsGA.UseCustomId)
{
GA_Wrapper.Initialize (SettingsGA.GetGameKey (platformIndex), SettingsGA.GetSecretKey (platformIndex));
}
else
{
Debug.Log ("Custom id is enabled. Initialize is delayed until custom id has been set.");
}
}
else
{
Debug.LogWarning("Unsupported platform (or missing platform in settings): " + Application.platform);
}
}
/// <summary>
/// Track any real money transaction in-game.
/// </summary>
/// <param name="currency">Currency code in ISO 4217 format. (e.g. USD).</param>
/// <param name="amount">Amount in cents (int). (e.g. 99).</param>
/// <param name="itemType">Item Type bought. (e.g. Gold Pack).</param>
/// <param name="itemId">Item bought. (e.g. 1000 gold).</param>
/// <param name="cartType">Cart type.</param>
public static void NewBusinessEvent(string currency, int amount, string itemType, string itemId, string cartType)
{
GA_Business.NewEvent(currency, amount, itemType, itemId, cartType);
}
#if UNITY_IOS || UNITY_TVOS
/// <summary>
/// Track any real money transaction in-game (iOS version).
/// </summary>
/// <param name="currency">Currency code in ISO 4217 format. (e.g. USD).</param>
/// <param name="amount">Amount in cents (int). (e.g. 99).</param>
/// <param name="itemType">Item Type bought. (e.g. Gold Pack).</param>
/// <param name="itemId">Item bought. (e.g. 1000 gold).</param>
/// <param name="cartType">Cart type.</param>
/// <param name="receipt">Transaction receipt string.</param>
public static void NewBusinessEventIOS(string currency, int amount, string itemType, string itemId, string cartType, string receipt)
{
GA_Business.NewEvent(currency, amount, itemType, itemId, cartType, receipt, false);
}
/// <summary>
/// Track any real money transaction in-game (iOS version). Additionally fetch and attach the in-app purchase receipt.
/// </summary>
/// <param name="currency">Currency code in ISO 4217 format. (e.g. USD).</param>
/// <param name="amount">Amount in cents (int). (e.g. 99).</param>
/// <param name="itemType">Item Type bought. (e.g. Gold Pack).</param>
/// <param name="itemId">Item bought. (e.g. 1000 gold).</param>
/// <param name="cartType">Cart type.</param>
public static void NewBusinessEventIOSAutoFetchReceipt(string currency, int amount, string itemType, string itemId, string cartType)
{
GA_Business.NewEvent(currency, amount, itemType, itemId, cartType, null, true);
}
#elif UNITY_ANDROID
/// <summary>
/// Track any real money transaction in-game (Google Play version).
/// </summary>
/// <param name="currency">Currency code in ISO 4217 format. (e.g. USD).</param>
/// <param name="amount">Amount in cents (int). (e.g. 99).</param>
/// <param name="itemType">Item Type bought. (e.g. Gold Pack).</param>
/// <param name="itemId">Item bought. (e.g. 1000 gold).</param>
/// <param name="cartType">Cart type.</param>
/// <param name="receipt">Transaction receipt string.</param>
/// <param name="signature">Signature of transaction.</param>
public static void NewBusinessEventGooglePlay(string currency, int amount, string itemType, string itemId, string cartType, string receipt, string signature)
{
GA_Business.NewEventGooglePlay(currency, amount, itemType, itemId, cartType, receipt, signature);
}
#endif
/// <summary>
/// Track any type of design event that you want to measure i.e. GUI elements or tutorial steps. Custom dimensions are not supported.
/// </summary>
/// <param name="eventName">String can consist of 1 to 5 segments. Segments are seperated by ':' and segments can have a max length of 16. (e.g. segment1:anotherSegment:gold).</param>
public static void NewDesignEvent(string eventName)
{
GA_Design.NewEvent(eventName);
}
/// <summary>
/// Track any type of design event that you want to measure i.e. GUI elements or tutorial steps. Custom dimensions are not supported.
/// </summary>
/// <param name="eventName">String can consist of 1 to 5 segments. Segments are seperated by ':' and segments can have a max length of 16. (e.g. segment1:anotherSegment:gold).</param>
/// <param name="eventValue">Number value of event.</param>
public static void NewDesignEvent(string eventName, float eventValue)
{
GA_Design.NewEvent(eventName, eventValue);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01)
{
GA_Progression.NewEvent(progressionStatus, progression01);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
/// <param name="progression02">2nd progression (e.g. level01).</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01, string progression02)
{
GA_Progression.NewEvent(progressionStatus, progression01, progression02);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
/// <param name="progression02">2nd progression (e.g. level01).</param>
/// <param name="progression03">3rd progression (e.g. phase01).</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01, string progression02, string progression03)
{
GA_Progression.NewEvent(progressionStatus, progression01, progression02, progression03);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
/// /// <param name="score">The player's score.</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01, int score)
{
GA_Progression.NewEvent(progressionStatus, progression01, score);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
/// <param name="progression02">2nd progression (e.g. level01).</param>
/// /// <param name="score">The player's score.</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01, string progression02, int score)
{
GA_Progression.NewEvent(progressionStatus, progression01, progression02, score);
}
/// <summary>
/// Measure player progression in the game. It follows a 3 hierarchy structure (world, level and phase) to indicate a player's path or place.
/// </summary>
/// <param name="progressionStatus">Status of added progression.</param>
/// <param name="progression01">1st progression (e.g. world01).</param>
/// <param name="progression02">2nd progression (e.g. level01).</param>
/// <param name="progression03">3rd progression (e.g. phase01).</param>
/// <param name="score">The player's score.</param>
public static void NewProgressionEvent(GAProgressionStatus progressionStatus, string progression01, string progression02, string progression03, int score)
{
GA_Progression.NewEvent(progressionStatus, progression01, progression02, progression03, score);
}
/// <summary>
/// Analyze your in-game economy (virtual currencies). You will be able to see the flow (sink/source) for each virtual currency.
/// </summary>
/// <param name="flowType">Add or substract resource.</param>
/// <param name="currency">One of the available currencies set in Settings (Setup tab).</param>
/// <param name="amount">Amount sourced or sinked.</param>
/// <param name="itemType">One of the available currencies set in Settings (Setup tab).</param>
/// <param name="itemId">Item id (string max length=16).</param>
public static void NewResourceEvent(GAResourceFlowType flowType, string currency, float amount, string itemType, string itemId)
{
GA_Resource.NewEvent(flowType, currency, amount, itemType, itemId);
}
/// <summary>
/// Set up custom error events in the game. You can group the events by severity level and attach a message.
/// </summary>
/// <param name="severity">Severity of error.</param>
/// <param name="message">Error message (Optional, can be nil).</param>
public static void NewErrorEvent(GAErrorSeverity severity, string message)
{
GA_Error.NewEvent(severity, message);
}
/// <summary>
/// Set user facebook id.
/// </summary>
/// <param name="facebookId">Facebook id of user (Persists cross session).</param>
public static void SetFacebookId(string facebookId)
{
GA_Setup.SetFacebookId(facebookId);
}
/// <summary>
/// Set user gender.
/// </summary>
/// <param name="gender">Gender of user (Persists cross session).</param>
public static void SetGender(GAGender gender)
{
GA_Setup.SetGender(gender);
}
/// <summary>
/// Set user birth year.
/// </summary>
/// <param name="birthYear">Birth year of user (Persists cross session).</param>
public static void SetBirthYear(int birthYear)
{
GA_Setup.SetBirthYear(birthYear);
}
/// <summary>
/// Sets the custom identifier.
/// </summary>
/// <param name="userId">User identifier.</param>
public static void SetCustomId(string userId)
{
if (SettingsGA.UseCustomId)
{
Debug.Log ("Initializing with custom id: " + userId);
GA_Wrapper.SetCustomUserId (userId);
int index = GetPlatformIndex();
if(index >= 0)
{
GA_Wrapper.Initialize (SettingsGA.GetGameKey (index), SettingsGA.GetSecretKey (index));
}
else
{
Debug.LogWarning("Unsupported platform (or missing platform in settings): " + Application.platform);
}
}
else
{
Debug.LogWarning ("Custom id is not enabled");
}
}
/// <summary>
/// Sets the enabled manual session handling.
/// </summary>
/// <param name="enabled">If set to <c>true</c> enabled.</param>
public static void SetEnabledManualSessionHandling(bool enabled)
{
GA_Wrapper.SetEnabledManualSessionHandling(enabled);
}
/// <summary>
/// Starts the session.
/// </summary>
public static void StartSession()
{
GA_Wrapper.StartSession();
}
/// <summary>
/// Ends the session.
/// </summary>
public static void EndSession()
{
GA_Wrapper.EndSession();
}
/// <summary>
/// Set 1st custom dimension.
/// </summary>
/// <param name="customDimension">One of the available dimension values set in Settings (Setup tab). Will persist cross session. Set to null to remove again.</param>
public static void SetCustomDimension01(string customDimension)
{
GA_Setup.SetCustomDimension01(customDimension);
}
/// <summary>
/// Set 2nd custom dimension.
/// </summary>
/// <param name="customDimension">One of the available dimension values set in Settings (Setup tab). Will persist cross session. Set to null to remove again.</param>
public static void SetCustomDimension02(string customDimension)
{
GA_Setup.SetCustomDimension02(customDimension);
}
/// <summary>
/// Set 3rd custom dimension.
/// </summary>
/// <param name="customDimension">One of the available dimension values set in Settings (Setup tab). Will persist cross session. Set to null to remove again.</param>
public static void SetCustomDimension03(string customDimension)
{
GA_Setup.SetCustomDimension03(customDimension);
}
private static string GetUnityVersion()
{
string unityVersion = "";
string[] splitUnityVersion = Application.unityVersion.Split('.');
for(int i = 0; i < splitUnityVersion.Length; i++)
{
int result;
if(int.TryParse(splitUnityVersion[i], out result))
{
if(i == 0)
unityVersion = splitUnityVersion[i];
else
unityVersion += "." + splitUnityVersion[i];
}
else
{
string[] regexVersion = System.Text.RegularExpressions.Regex.Split(splitUnityVersion[i], "[^\\d]+");
if(regexVersion.Length > 0 && int.TryParse(regexVersion[0], out result))
{
unityVersion += "." + regexVersion[0];
}
}
}
return unityVersion;
}
private static int GetPlatformIndex()
{
int result = -1;
RuntimePlatform platform = Application.platform;
if(platform == RuntimePlatform.IPhonePlayer)
{
if(!SettingsGA.Platforms.Contains(platform))
{
result = SettingsGA.Platforms.IndexOf(RuntimePlatform.tvOS);
}
else
{
result = SettingsGA.Platforms.IndexOf(platform);
}
}
else if(platform == RuntimePlatform.tvOS)
{
if(!SettingsGA.Platforms.Contains(platform))
{
result = SettingsGA.Platforms.IndexOf(RuntimePlatform.IPhonePlayer);
}
else
{
result = SettingsGA.Platforms.IndexOf(platform);
}
}
// HACK: To also check for RuntimePlatform.MetroPlayerARM, RuntimePlatform.MetroPlayerX64 and RuntimePlatform.MetroPlayerX86 which are deprecated but have same value as the WSA enums
else if (platform == RuntimePlatform.WSAPlayerARM || platform == RuntimePlatform.WSAPlayerX64 || platform == RuntimePlatform.WSAPlayerX86 ||
((int)platform == (int)RuntimePlatform.WSAPlayerARM) || ((int)platform == (int)RuntimePlatform.WSAPlayerX64) || ((int)platform == (int)RuntimePlatform.WSAPlayerX86))
{
result = SettingsGA.Platforms.IndexOf(RuntimePlatform.WSAPlayerARM);
}
else
{
result = SettingsGA.Platforms.IndexOf(platform);
}
return result;
}
#if UNITY_EDITOR
/// <summary>
/// Dynamic search for a file.
/// </summary>
/// <returns>Returns the Unity path to a specified file.</returns>
/// <param name="">File name including extension e.g. image.png</param>
public static string WhereIs(string _file)
{
#if UNITY_SAMSUNGTV
return "";
#else
string[] assets = { Path.DirectorySeparatorChar + "Assets" + Path.DirectorySeparatorChar};
FileInfo[] myFile = new DirectoryInfo ("Assets").GetFiles (_file, SearchOption.AllDirectories);
string[] temp = myFile [0].ToString ().Split (assets, 2, System.StringSplitOptions.None);
return "Assets" + Path.DirectorySeparatorChar + temp [1];
#endif
}
public static void HierarchyWindowCallback(int instanceID, Rect selectionRect)
{
GameObject go = (GameObject)EditorUtility.InstanceIDToObject(instanceID);
if(go != null && go.GetComponent<GameAnalytics>() != null)
{
float addX = 0;
if(go.GetComponent("PlayMakerFSM") != null)
addX = selectionRect.height + 2;
if(GameAnalytics.SettingsGA.Logo == null)
{
GameAnalytics.SettingsGA.Logo = (Texture2D)AssetDatabase.LoadAssetAtPath(WhereIs("gaLogo.png"), typeof(Texture2D));
}
Graphics.DrawTexture(new Rect(GUILayoutUtility.GetLastRect().width - selectionRect.height - 5 - addX, selectionRect.y, selectionRect.height, selectionRect.height), GameAnalytics.SettingsGA.Logo);
}
}
#endif
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with customer bank account resources.
///
/// Customer Bank Accounts hold the bank details of a
/// [customer](#core-endpoints-customers). They always belong to a
/// [customer](#core-endpoints-customers), and may be linked to several
/// Direct Debit [mandates](#core-endpoints-mandates).
///
/// Note that customer bank accounts must be unique, and so you will
/// encounter a `bank_account_exists` error if you try to create a duplicate
/// bank account. You may wish to handle this by updating the existing
/// record instead, the ID of which will be provided as
/// `links[customer_bank_account]` in the error response.
/// </summary>
public class CustomerBankAccountService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public CustomerBankAccountService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Creates a new customer bank account object.
///
/// There are three different ways to supply bank account details:
///
/// - [Local details](#appendix-local-bank-details)
///
/// - IBAN
///
/// - [Customer Bank Account
/// Tokens](#javascript-flow-create-a-customer-bank-account-token)
///
/// For more information on the different fields required in each
/// country, see [local bank details](#appendix-local-bank-details).
/// </summary>
/// <param name="request">An optional `CustomerBankAccountCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single customer bank account resource</returns>
public Task<CustomerBankAccountResponse> CreateAsync(CustomerBankAccountCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<CustomerBankAccountResponse>("POST", "/customer_bank_accounts", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "customer_bank_accounts", customiseRequestMessage);
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of
/// your bank accounts.
/// </summary>
/// <param name="request">An optional `CustomerBankAccountListRequest` representing the query parameters for this list request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A set of customer bank account resources</returns>
public Task<CustomerBankAccountListResponse> ListAsync(CustomerBankAccountListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountListRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<CustomerBankAccountListResponse>("GET", "/customer_bank_accounts", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Get a lazily enumerated list of customer bank accounts.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<CustomerBankAccount> All(CustomerBankAccountListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountListRequest();
string cursor = null;
do
{
request.After = cursor;
var result = Task.Run(() => ListAsync(request, customiseRequestMessage)).Result;
foreach (var item in result.CustomerBankAccounts)
{
yield return item;
}
cursor = result.Meta?.Cursors?.After;
} while (cursor != null);
}
/// <summary>
/// Get a lazily enumerated list of customer bank accounts.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<Task<IReadOnlyList<CustomerBankAccount>>> AllAsync(CustomerBankAccountListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountListRequest();
return new TaskEnumerable<IReadOnlyList<CustomerBankAccount>, string>(async after =>
{
request.After = after;
var list = await this.ListAsync(request, customiseRequestMessage);
return Tuple.Create(list.CustomerBankAccounts, list.Meta?.Cursors?.After);
});
}
/// <summary>
/// Retrieves the details of an existing bank account.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BA".</param>
/// <param name="request">An optional `CustomerBankAccountGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single customer bank account resource</returns>
public Task<CustomerBankAccountResponse> GetAsync(string identity, CustomerBankAccountGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<CustomerBankAccountResponse>("GET", "/customer_bank_accounts/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Updates a customer bank account object. Only the metadata parameter
/// is allowed.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BA".</param>
/// <param name="request">An optional `CustomerBankAccountUpdateRequest` representing the body for this update request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single customer bank account resource</returns>
public Task<CustomerBankAccountResponse> UpdateAsync(string identity, CustomerBankAccountUpdateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountUpdateRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<CustomerBankAccountResponse>("PUT", "/customer_bank_accounts/:identity", urlParams, request, null, "customer_bank_accounts", customiseRequestMessage);
}
/// <summary>
/// Immediately cancels all associated mandates and cancellable
/// payments.
///
/// This will return a `disable_failed` error if the bank account has
/// already been disabled.
///
/// A disabled bank account can be re-enabled by creating a new bank
/// account resource with the same details.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "BA".</param>
/// <param name="request">An optional `CustomerBankAccountDisableRequest` representing the body for this disable request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single customer bank account resource</returns>
public Task<CustomerBankAccountResponse> DisableAsync(string identity, CustomerBankAccountDisableRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new CustomerBankAccountDisableRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<CustomerBankAccountResponse>("POST", "/customer_bank_accounts/:identity/actions/disable", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Creates a new customer bank account object.
///
/// There are three different ways to supply bank account details:
///
/// - [Local details](#appendix-local-bank-details)
///
/// - IBAN
///
/// - [Customer Bank Account
/// Tokens](#javascript-flow-create-a-customer-bank-account-token)
///
/// For more information on the different fields required in each country,
/// see [local bank details](#appendix-local-bank-details).
/// </summary>
public class CustomerBankAccountCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// Name of the account holder, as known by the bank. Usually this is
/// the same as the name stored with the linked
/// [creditor](#core-endpoints-creditors). This field will be
/// transliterated, upcased and truncated to 18 characters. This field
/// is required unless the request includes a [customer bank account
/// token](#javascript-flow-customer-bank-account-tokens).
/// </summary>
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
/// <summary>
/// Bank account number - see [local
/// details](#appendix-local-bank-details) for more information.
/// Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("account_number")]
public string AccountNumber { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must
/// not be provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonProperty("account_type")]
public CustomerBankAccountAccountType? AccountType { get; set; }
/// <summary>
/// Bank account type. Required for USD-denominated bank accounts. Must
/// not be provided for bank accounts in other currencies. See [local
/// details](#local-bank-details-united-states) for more information.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum CustomerBankAccountAccountType
{
/// <summary>`account_type` with a value of "savings"</summary>
[EnumMember(Value = "savings")]
Savings,
/// <summary>`account_type` with a value of "checking"</summary>
[EnumMember(Value = "checking")]
Checking,
}
/// <summary>
/// Bank code - see [local details](#appendix-local-bank-details) for
/// more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("bank_code")]
public string BankCode { get; set; }
/// <summary>
/// Branch code - see [local details](#appendix-local-bank-details) for
/// more information. Alternatively you can provide an `iban`.
/// </summary>
[JsonProperty("branch_code")]
public string BranchCode { get; set; }
/// <summary>
/// [ISO 3166-1 alpha-2
/// code](http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2#Officially_assigned_code_elements).
/// Defaults to the country code of the `iban` if supplied, otherwise is
/// required.
/// </summary>
[JsonProperty("country_code")]
public string CountryCode { get; set; }
/// <summary>
/// [ISO 4217](http://en.wikipedia.org/wiki/ISO_4217#Active_codes)
/// currency code. Currently "AUD", "CAD", "DKK", "EUR", "GBP", "NZD",
/// "SEK" and "USD" are supported.
/// </summary>
[JsonProperty("currency")]
public string Currency { get; set; }
/// <summary>
/// International Bank Account Number. Alternatively you can provide
/// [local details](#appendix-local-bank-details). IBANs are not
/// accepted for Swedish bank accounts denominated in SEK - you must
/// supply [local details](#local-bank-details-sweden).
/// </summary>
[JsonProperty("iban")]
public string Iban { get; set; }
/// <summary>
/// Linked resources.
/// </summary>
[JsonProperty("links")]
public CustomerBankAccountLinks Links { get; set; }
/// <summary>
/// Linked resources for a CustomerBankAccount.
/// </summary>
public class CustomerBankAccountLinks
{
/// <summary>
/// ID of the [customer](#core-endpoints-customers) that owns this
/// bank account.
/// </summary>
[JsonProperty("customer")]
public string Customer { get; set; }
/// <summary>
/// ID of a [customer bank account
/// token](#javascript-flow-customer-bank-account-tokens) to use in
/// place of bank account parameters.
/// </summary>
[JsonProperty("customer_bank_account_token")]
public string CustomerBankAccountToken { get; set; }
}
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your
/// bank accounts.
/// </summary>
public class CustomerBankAccountListRequest
{
/// <summary>
/// Cursor pointing to the start of the desired set.
/// </summary>
[JsonProperty("after")]
public string After { get; set; }
/// <summary>
/// Cursor pointing to the end of the desired set.
/// </summary>
[JsonProperty("before")]
public string Before { get; set; }
/// <summary>
/// Limit to records created within certain times.
/// </summary>
[JsonProperty("created_at")]
public CreatedAtParam CreatedAt { get; set; }
/// <summary>
/// Specify filters to limit records by creation time.
/// </summary>
public class CreatedAtParam
{
/// <summary>
/// Limit to records created after the specified date-time.
/// </summary>
[JsonProperty("gt")]
public DateTimeOffset? GreaterThan { get; set; }
/// <summary>
/// Limit to records created on or after the specified date-time.
/// </summary>
[JsonProperty("gte")]
public DateTimeOffset? GreaterThanOrEqual { get; set; }
/// <summary>
/// Limit to records created before the specified date-time.
/// </summary>
[JsonProperty("lt")]
public DateTimeOffset? LessThan { get; set; }
/// <summary>
///Limit to records created on or before the specified date-time.
/// </summary>
[JsonProperty("lte")]
public DateTimeOffset? LessThanOrEqual { get; set; }
}
/// <summary>
/// Unique identifier, beginning with "CU".
/// </summary>
[JsonProperty("customer")]
public string Customer { get; set; }
/// <summary>
/// Get enabled or disabled customer bank accounts.
/// </summary>
[JsonProperty("enabled")]
public bool? Enabled { get; set; }
/// <summary>
/// Get enabled or disabled customer bank accounts.
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum CustomerBankAccountEnabled
{
/// <summary>`enabled` with a value of "true"</summary>
[EnumMember(Value = "true")]
True,
/// <summary>`enabled` with a value of "false"</summary>
[EnumMember(Value = "false")]
False,
}
/// <summary>
/// Number of records to return.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
}
/// <summary>
/// Retrieves the details of an existing bank account.
/// </summary>
public class CustomerBankAccountGetRequest
{
}
/// <summary>
/// Updates a customer bank account object. Only the metadata parameter is
/// allowed.
/// </summary>
public class CustomerBankAccountUpdateRequest
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// Immediately cancels all associated mandates and cancellable payments.
///
/// This will return a `disable_failed` error if the bank account has
/// already been disabled.
///
/// A disabled bank account can be re-enabled by creating a new bank account
/// resource with the same details.
/// </summary>
public class CustomerBankAccountDisableRequest
{
}
/// <summary>
/// An API response for a request returning a single customer bank account.
/// </summary>
public class CustomerBankAccountResponse : ApiResponse
{
/// <summary>
/// The customer bank account from the response.
/// </summary>
[JsonProperty("customer_bank_accounts")]
public CustomerBankAccount CustomerBankAccount { get; private set; }
}
/// <summary>
/// An API response for a request returning a list of customer bank accounts.
/// </summary>
public class CustomerBankAccountListResponse : ApiResponse
{
/// <summary>
/// The list of customer bank accounts from the response.
/// </summary>
[JsonProperty("customer_bank_accounts")]
public IReadOnlyList<CustomerBankAccount> CustomerBankAccounts { get; private set; }
/// <summary>
/// Response metadata (e.g. pagination cursors)
/// </summary>
public Meta Meta { get; private set; }
}
}
| |
using System;
using System.Threading;
using System.Collections.Generic;
using System.Linq;
using ReactNative.Bridge;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Windows.Storage;
using SQLite3;
using ReactNative.Modules.Core;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using System.Text;
namespace ReactNative.Modules.SQLite
{
public class SQLiteModule : ReactContextNativeModuleBase, ILifecycleEventListener
{
static string version;
static Dictionary<string, Database> databases = new Dictionary<string, Database>();
static Dictionary<string, string> databaseKeys = new Dictionary<string, string>();
public SQLiteModule(ReactContext reactContext) : base(reactContext)
{
}
public override string Name
{
get
{
return "SQLite";
}
}
[ReactMethod]
public async void open(
JObject config,
ICallback doneCallback,
ICallback errorCallback
)
{
try
{
string dbname = config.Value<string>("name") ?? "";
string opendbname = ApplicationData.Current.LocalFolder.Path + "\\" + dbname;
string key = config.Value<string>("key");
//Database db = await (key != null ? Database.OpenAsyncWithKey(opendbname, key) : Database.OpenAsync(opendbname));
Database db = await Database.OpenAsyncWithKey(opendbname, key);
if (version == null)
{
JObject result = JObject.Parse(await db.OneAsyncVector("SELECT sqlite_version() || ' (' || sqlite_source_id() || ')' as version", new List<string>()));
version = result.Value<string>("version");
}
databases[dbname] = db;
databaseKeys[dbname] = key;
doneCallback.Invoke();
//Debug.WriteLine("Opened database");
}
catch (Exception e)
{
errorCallback.Invoke(e.Message);
Debug.WriteLine("Open database failed " + e.ToString());
}
}
[ReactMethod]
public void close(
JObject config,
ICallback doneCallback,
ICallback errorCallback
)
{
try
{
string dbname = config.Value<string>("path") ?? "";
Database db = databases[dbname];
db.closedb();
databases.Remove(dbname);
databaseKeys.Remove(dbname);
doneCallback.Invoke();
//Debug.WriteLine("Closed Database");
}
catch (Exception e)
{
errorCallback.Invoke(e.Message);
Debug.WriteLine("Close database failed " + e.ToString());
}
}
[ReactMethod]
public async void backgroundExecuteSqlBatch(
JObject config,
ICallback doneCallback,
ICallback errorCallback
)
{
try
{
string dbname = config.Value<JObject>("dbargs").Value<string>("dbname") ?? "";
if (!databaseKeys.Keys.Contains(dbname))
{
throw new Exception("Database does not exist");
}
if (!databases.Keys.Contains(dbname))
{
try
{
await reOpenDatabases();
if (!databases.Keys.Contains(dbname))
{
throw new Exception("Resume Didn't Work");
}
}
catch (Exception e)
{
throw new Exception("Failed to reopendatabase" + e.ToString());
}
}
string executesBase64 = config.Value<string>("executes");
byte[] data = Convert.FromBase64String(executesBase64);
string executesBase64Decoded = Encoding.UTF8.GetString(data);
JsonReader reader = new JsonTextReader(new StringReader(executesBase64Decoded));
reader.DateParseHandling = DateParseHandling.None;
JArray executes = JArray.Load(reader);
Database db = databases[dbname];
JArray results = new JArray();
long totalChanges = db.TotalChanges;
string q = "";
foreach (JObject e in executes)
{
try
{
q = e.Value<string>("qid");
string s = e.Value<string>("sql");
JArray pj = e.Value<JArray>("params");
IReadOnlyList<Object> p = pj.ToObject<IReadOnlyList<Object>>();
JArray rows = JArray.Parse(await db.AllAsyncVector(s, p));
long rowsAffected = db.TotalChanges - totalChanges;
totalChanges = db.TotalChanges;
JObject result = new JObject();
result["rowsAffected"] = rowsAffected;
result["rows"] = rows;
result["insertId"] = db.LastInsertRowId;
JObject resultInfo = new JObject();
resultInfo["type"] = "success";
resultInfo["qid"] = q;
resultInfo["result"] = result;
results.Add(resultInfo);
}
catch (Exception err)
{
JObject resultInfo = new JObject();
JObject result = new JObject();
result["code"] = -1;
result["message"] = err.Message;
resultInfo["type"] = "error";
resultInfo["qid"] = q;
resultInfo["result"] = result;
results.Add(resultInfo);
}
}
doneCallback.Invoke(results);
//Debug.WriteLine("Done Execute Sql Batch");
}
catch (Exception e)
{
errorCallback.Invoke(e.Message);
Debug.WriteLine("Error in background execute Sql batch" + e.ToString());
}
finally { }
}
[ReactMethod]
public async void delete(
JObject config,
ICallback doneCallback,
ICallback errorCallback)
{
try
{
string dbname = config.Value<string>("path") ?? "";
if (databases.Keys.Contains(dbname))
{
Database db = databases[dbname];
db.closedb();
databases.Remove(dbname);
databaseKeys.Remove(dbname);
}
StorageFile file = await ApplicationData.Current.LocalFolder.GetFileAsync(dbname);
await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
doneCallback.Invoke();
//Debug.WriteLine("Deleted database");
}
catch (Exception err)
{
errorCallback.Invoke(err.Message);
Debug.WriteLine("Error in Delete Database " + err.ToString());
}
finally { }
}
public void OnSuspend()
{
OnDestroy();
}
public async void OnResume()
{
await reOpenDatabases();
}
public void OnDestroy()
{
// close all databases
foreach (KeyValuePair<String, Database> entry in databases)
{
entry.Value.closedb();
}
databases.Clear();
}
public override void Initialize()
{
base.Initialize();
Context.AddLifecycleEventListener(this);
}
async Task reOpenDatabases()
{
try
{
foreach (KeyValuePair<String, String> entry in databaseKeys)
{
string opendbname = ApplicationData.Current.LocalFolder.Path + "\\" + entry.Key;
FileInfo fInfo = new FileInfo(opendbname);
if (!fInfo.Exists)
{
throw new Exception(opendbname + " not found");
}
Database db = await Database.OpenAsyncWithKey(opendbname, entry.Value);
if (version == null)
{
JObject result = JObject.Parse(await db.OneAsyncVector("SELECT sqlite_version() || ' (' || sqlite_source_id() || ')' as version", new List<string>()));
version = result.Value<string>("version");
}
databases[entry.Key] = db;
}
}
catch (Exception e)
{
throw new Exception("Failed to restore database" + e.ToString());
}
}
}
public class SQLiteReactPackage : IReactPackage
{
public IReadOnlyList<INativeModule> CreateNativeModules(ReactContext reactContext)
{
return new List<INativeModule>
{
new SQLiteModule(reactContext)
};
}
public IReadOnlyList<Type> CreateJavaScriptModulesConfig()
{
return new List<Type>(0);
}
public IReadOnlyList<UIManager.IViewManager> CreateViewManagers(
ReactContext reactContext)
{
return new List<UIManager.IViewManager>(0);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace ServicesCORS.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// 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.Net.Security;
using System.Net.Sockets;
using System.Net.Test.Common;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace System.Net.Http.Functional.Tests
{
using Configuration = System.Net.Test.Common.Configuration;
public abstract class HttpClientHandler_ClientCertificates_Test : HttpClientTestBase
{
public bool CanTestCertificates =>
Capability.IsTrustedRootCertificateInstalled() &&
(BackendSupportsCustomCertificateHandling || Capability.AreHostsFileNamesInstalled());
public bool CanTestClientCertificates =>
CanTestCertificates && BackendSupportsCustomCertificateHandling;
public HttpClientHandler_ClientCertificates_Test(ITestOutputHelper output)
{
_output = output;
}
private readonly ITestOutputHelper _output;
[Fact]
public void ClientCertificateOptions_Default()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
Assert.Equal(ClientCertificateOption.Manual, handler.ClientCertificateOptions);
}
}
[Theory]
[InlineData((ClientCertificateOption)2)]
[InlineData((ClientCertificateOption)(-1))]
public void ClientCertificateOptions_InvalidArg_ThrowsException(ClientCertificateOption option)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => handler.ClientCertificateOptions = option);
}
}
[Theory]
[InlineData(ClientCertificateOption.Automatic)]
[InlineData(ClientCertificateOption.Manual)]
public void ClientCertificateOptions_ValueArg_Roundtrips(ClientCertificateOption option)
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = option;
Assert.Equal(option, handler.ClientCertificateOptions);
}
}
[Fact]
public void ClientCertificates_ClientCertificateOptionsAutomatic_ThrowsException()
{
using (HttpClientHandler handler = CreateHttpClientHandler())
{
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
Assert.Throws<InvalidOperationException>(() => handler.ClientCertificates);
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Automatic_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ClientCertificateOptions = ClientCertificateOption.Automatic;
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop("Uses external server")]
[Fact]
public async Task Manual_SSLBackendNotSupported_ThrowsPlatformNotSupportedException()
{
if (BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
return;
}
HttpClientHandler handler = CreateHttpClientHandler();
handler.ClientCertificates.Add(Configuration.Certificates.GetClientCertificate());
using (var client = new HttpClient(handler))
{
await Assert.ThrowsAsync<PlatformNotSupportedException>(() => client.GetAsync(Configuration.Http.SecureRemoteEchoServer));
}
}
[OuterLoop("Uses external server")]
[Fact]
public void Manual_SendClientCertificateWithClientAuthEKUToRemoteServer_OK()
{
if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
_output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithClientAuthEKUToRemoteServer_OK)}()");
return;
}
// 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(async useSocketsHttpHandlerString =>
{
var cert = Configuration.Certificates.GetClientCertificate();
HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string body = await response.Content.ReadAsStringAsync();
byte[] bytes = Convert.FromBase64String(body);
var receivedCert = new X509Certificate2(bytes);
Assert.Equal(cert, receivedCert);
return SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden()
{
if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
_output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithServerAuthEKUToRemoteServer_Forbidden)}()");
return;
}
// 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(async useSocketsHttpHandlerString =>
{
var cert = Configuration.Certificates.GetServerCertificate();
HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
return SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[OuterLoop("Uses external server")]
[Fact]
public void Manual_SendClientCertificateWithNoEKUToRemoteServer_OK()
{
if (!CanTestClientCertificates) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
_output.WriteLine($"Skipping {nameof(Manual_SendClientCertificateWithNoEKUToRemoteServer_OK)}()");
return;
}
// 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(async useSocketsHttpHandlerString =>
{
var cert = Configuration.Certificates.GetNoEKUCertificate();
HttpClientHandler handler = CreateHttpClientHandler(useSocketsHttpHandlerString);
handler.ClientCertificates.Add(cert);
using (var client = new HttpClient(handler))
{
HttpResponseMessage response = await client.GetAsync(Configuration.Http.EchoClientCertificateRemoteServer);
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
string body = await response.Content.ReadAsStringAsync();
byte[] bytes = Convert.FromBase64String(body);
var receivedCert = new X509Certificate2(bytes);
Assert.Equal(cert, receivedCert);
return SuccessExitCode;
}
}, UseSocketsHttpHandler.ToString()).Dispose();
}
[ActiveIssue(30056, TargetFrameworkMonikers.Uap)]
[OuterLoop("Uses GC and waits for finalizers")]
[Theory]
[InlineData(6, false)]
[InlineData(3, true)]
public async Task Manual_CertificateSentMatchesCertificateReceived_Success(
int numberOfRequests,
bool reuseClient) // validate behavior with and without connection pooling, which impacts client cert usage
{
if (!BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
_output.WriteLine($"Skipping {nameof(Manual_CertificateSentMatchesCertificateReceived_Success)}()");
return;
}
var options = new LoopbackServer.Options { UseSsl = true };
Func<X509Certificate2, HttpClient> createClient = (cert) =>
{
HttpClientHandler handler = CreateHttpClientHandler();
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
handler.ClientCertificates.Add(cert);
Assert.True(handler.ClientCertificates.Contains(cert));
return new HttpClient(handler);
};
Func<HttpClient, LoopbackServer, Uri, X509Certificate2, Task> makeAndValidateRequest = async (client, server, url, cert) =>
{
await TestHelper.WhenAllCompletedOrAnyFailed(
client.GetStringAsync(url),
server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
// We can't do Assert.Equal(cert, sslStream.RemoteCertificate) because
// on .NET Framework sslStream.RemoteCertificate is always an X509Certificate
// object which is not equal to the X509Certificate2 object we use in the tests.
// So, we'll just compare a few properties to make sure it's the right certificate.
Assert.Equal(cert.Subject, sslStream.RemoteCertificate.Subject);
Assert.Equal(cert.Issuer, sslStream.RemoteCertificate.Issuer);
await connection.ReadRequestHeaderAndSendResponseAsync(additionalHeaders: "Connection: close\r\n");
}));
};
await LoopbackServer.CreateServerAsync(async (server, url) =>
{
using (X509Certificate2 cert = Configuration.Certificates.GetClientCertificate())
{
if (reuseClient)
{
using (HttpClient client = createClient(cert))
{
for (int i = 0; i < numberOfRequests; i++)
{
await makeAndValidateRequest(client, server, url, cert);
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
else
{
for (int i = 0; i < numberOfRequests; i++)
{
using (HttpClient client = createClient(cert))
{
await makeAndValidateRequest(client, server, url, cert);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
}, options);
}
[ActiveIssue(30056, TargetFrameworkMonikers.Uap)]
[Theory]
[InlineData(ClientCertificateOption.Manual)]
[InlineData(ClientCertificateOption.Automatic)]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Fails with \"Authentication failed\" error.")]
public async Task AutomaticOrManual_DoesntFailRegardlessOfWhetherClientCertsAreAvailable(ClientCertificateOption mode)
{
if (!BackendSupportsCustomCertificateHandling) // can't use [Conditional*] right now as it's evaluated at the wrong time for SocketsHttpHandler
{
_output.WriteLine($"Skipping {nameof(AutomaticOrManual_DoesntFailRegardlessOfWhetherClientCertsAreAvailable)}()");
return;
}
using (HttpClientHandler handler = CreateHttpClientHandler())
using (var client = new HttpClient(handler))
{
handler.ServerCertificateCustomValidationCallback = delegate { return true; };
handler.ClientCertificateOptions = mode;
await LoopbackServer.CreateServerAsync(async server =>
{
Task clientTask = client.GetStringAsync(server.Uri);
Task serverTask = server.AcceptConnectionAsync(async connection =>
{
SslStream sslStream = Assert.IsType<SslStream>(connection.Stream);
await connection.ReadRequestHeaderAndSendResponseAsync();
});
await new Task[] { clientTask, serverTask }.WhenAllOrAnyFailed();
}, new LoopbackServer.Options { UseSsl = true });
}
}
private bool BackendSupportsCustomCertificateHandling
{
get
{
#if TargetsWindows
return true;
#else
if (UseSocketsHttpHandler)
{
// Socket Handler is independent of platform curl.
return true;
}
return TestHelper.NativeHandlerSupportsSslConfiguration();
#endif
}
}
}
}
| |
//
// TypeReferenceCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Tue Oct 03 00:35:28 CEST 2006
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using System.Collections;
using System.Collections.Specialized;
using Mono.Cecil.Cil;
using Hcp = Mono.Cecil.HashCodeProvider;
using Cmp = System.Collections.Comparer;
public sealed class TypeReferenceCollection : NameObjectCollectionBase, IList, IReflectionVisitable {
ModuleDefinition m_container;
public TypeReference this [int index] {
get { return this.BaseGet (index) as TypeReference; }
set { this.BaseSet (index, value); }
}
public TypeReference this [string fullName] {
get { return this.BaseGet (fullName) as TypeReference; }
set { this.BaseSet (fullName, value); }
}
public ModuleDefinition Container {
get { return m_container; }
}
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return this; }
}
bool IList.IsReadOnly {
get { return false; }
}
bool IList.IsFixedSize {
get { return false; }
}
object IList.this [int index] {
get { return BaseGet (index); }
set {
Check (value);
BaseSet (index, value);
}
}
public TypeReferenceCollection (ModuleDefinition container) :
base (Hcp.Instance, Cmp.Default)
{
m_container = container;
}
public void Add (TypeReference value)
{
if (value == null)
throw new ArgumentNullException ("value");
Attach (value);
this.BaseAdd (value.FullName, value);
}
public void Clear ()
{
foreach (TypeReference item in this)
Detach (item);
this.BaseClear ();
}
public bool Contains (TypeReference value)
{
return Contains (value.FullName);
}
public bool Contains (string fullName)
{
return this.BaseGet (fullName) != null;
}
public int IndexOf (TypeReference value)
{
string [] keys = this.BaseGetAllKeys ();
return Array.IndexOf (keys, value.FullName, 0, keys.Length);
}
public void Remove (TypeReference value)
{
if (this.Contains (value))
Detach (value);
this.BaseRemove (value.FullName);
}
public void RemoveAt (int index)
{
Detach (this [index]);
this.BaseRemoveAt (index);
}
public void CopyTo (Array ary, int index)
{
this.BaseGetAllValues ().CopyTo (ary, index);
}
public new IEnumerator GetEnumerator ()
{
return this.BaseGetAllValues ().GetEnumerator ();
}
public void Accept (IReflectionVisitor visitor)
{
visitor.VisitTypeReferenceCollection (this);
}
#if CF_1_0 || CF_2_0
internal object [] BaseGetAllValues ()
{
object [] values = new object [this.Count];
for (int i=0; i < values.Length; ++i) {
values [i] = this.BaseGet (i);
}
return values;
}
#endif
void Check (object value)
{
if (!(value is TypeReference))
throw new ArgumentException ();
}
int IList.Add (object value)
{
Check (value);
Add (value as TypeReference);
return 0;
}
bool IList.Contains (object value)
{
Check (value);
return Contains (value as TypeReference);
}
int IList.IndexOf (object value)
{
throw new NotSupportedException ();
}
void IList.Insert (int index, object value)
{
throw new NotSupportedException ();
}
void IList.Remove (object value)
{
Check (value);
Remove (value as TypeReference);
}
void Detach (TypeReference type)
{
type.Module = null;
}
void Attach (TypeReference type)
{
if (type.Module != null)
throw new ReflectionException ("Type is already attached, clone it instead");
type.Module = m_container;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System;
public class GLDraw
{
/*
* Clipping code: http://forum.unity3d.com/threads/17066-How-to-draw-a-GUI-2D-quot-line-quot?p=230386#post230386
* Thick line drawing code: http://unifycommunity.com/wiki/index.php?title=VectorLine
*/
protected static bool clippingEnabled;
protected static Rect clippingBounds;
public static Material lineMaterial = null;
/* @ Credit: "http://cs-people.bu.edu/jalon/cs480/Oct11Lab/clip.c" */
protected static bool clip_test(float p, float q, ref float u1, ref float u2)
{
float r;
bool retval = true;
if (p < 0.0)
{
r = q / p;
if (r > u2)
retval = false;
else if (r > u1)
u1 = r;
}
else if (p > 0.0)
{
r = q / p;
if (r < u1)
retval = false;
else if (r < u2)
u2 = r;
}
else if (q < 0.0)
retval = false;
return retval;
}
public static bool segment_rect_intersection(Rect bounds, ref Vector2 p1, ref Vector2 p2)
{
float u1 = 0.0f, u2 = 1.0f, dx = p2.x - p1.x, dy;
if (clip_test(-dx, p1.x - bounds.xMin, ref u1, ref u2))
{
if (clip_test(dx, bounds.xMax - p1.x, ref u1, ref u2))
{
dy = p2.y - p1.y;
if (clip_test(-dy, p1.y - bounds.yMin, ref u1, ref u2))
{
if (clip_test(dy, bounds.yMax - p1.y, ref u1, ref u2))
{
if (u2 < 1.0)
{
p2.x = p1.x + u2 * dx;
p2.y = p1.y + u2 * dy;
}
if (u1 > 0.0)
{
p1.x += u1 * dx;
p1.y += u1 * dy;
}
return true;
}
}
}
}
return false;
}
public static void BeginGroup(Rect position)
{
clippingEnabled = true;
clippingBounds = new Rect(0, 0, position.width, position.height);
GUI.BeginGroup(position);
}
public static void EndGroup()
{
GUI.EndGroup();
clippingBounds = new Rect(0, 0, Screen.width, Screen.height);
clippingEnabled = false;
}
public static Vector2 BeginScrollView(Rect position, Vector2 scrollPos, Rect viewRect, Rect clipRect)
{
clippingEnabled = true;
clippingBounds = clipRect;
return GUI.BeginScrollView(position, scrollPos, viewRect);
}
public static void EndScrollView()
{
GUI.EndScrollView();
clippingBounds = new Rect(0, 0, Screen.width, Screen.height);
clippingEnabled = false;
}
public static void CreateMaterial()
{
if (lineMaterial != null)
return;
lineMaterial = new Material("Shader \"Lines/Colored Blended\" {" +
"SubShader { Pass { " +
" Blend SrcAlpha OneMinusSrcAlpha " +
" ZWrite Off Cull Off Fog { Mode Off } " +
" BindChannels {" +
" Bind \"vertex\", vertex Bind \"color\", color }" +
"} } }");
lineMaterial.hideFlags = HideFlags.HideAndDontSave;
lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
}
public static void DrawLine(Vector2 start, Vector2 end, Color color, float width)
{
if (Event.current == null)
return;
if (Event.current.type != EventType.repaint)
return;
if (clippingEnabled)
if (!segment_rect_intersection(clippingBounds, ref start, ref end))
return;
CreateMaterial();
lineMaterial.SetPass(0);
Vector3 startPt;
Vector3 endPt;
if (width == 1)
{
GL.Begin(GL.LINES);
GL.Color(color);
startPt = new Vector3(start.x, start.y, 0);
endPt = new Vector3(end.x, end.y, 0);
GL.Vertex(startPt);
GL.Vertex(endPt);
}
else
{
GL.Begin(GL.QUADS);
GL.Color(color);
startPt = new Vector3(end.y, start.x, 0);
endPt = new Vector3(start.y, end.x, 0);
Vector3 perpendicular = (startPt - endPt).normalized * width;
Vector3 v1 = new Vector3(start.x, start.y, 0);
Vector3 v2 = new Vector3(end.x, end.y, 0);
GL.Vertex(v1 - perpendicular);
GL.Vertex(v1 + perpendicular);
GL.Vertex(v2 + perpendicular);
GL.Vertex(v2 - perpendicular);
}
GL.End();
}
public static void DrawRect(Rect rect, Color color)
{
if (Event.current == null)
return;
if (Event.current.type != EventType.repaint)
return;
CreateMaterial();
// set the current material
lineMaterial.SetPass( 0 );
GL.Begin( GL.QUADS );
GL.Color( color );
GL.Vertex3( rect.xMin, rect.yMin, 0 );
GL.Vertex3( rect.xMax, rect.yMin, 0 );
GL.Vertex3( rect.xMax, rect.yMax, 0 );
GL.Vertex3( rect.xMin, rect.yMax, 0 );
GL.End();
}
public static void DrawBox(Rect box, Color color, float width)
{
Vector2 p1 = new Vector2(box.xMin, box.yMin);
Vector2 p2 = new Vector2(box.xMax, box.yMin);
Vector2 p3 = new Vector2(box.xMax, box.yMax);
Vector2 p4 = new Vector2(box.xMin, box.yMax);
DrawLine(p1, p2, color, width);
DrawLine(p2, p3, color, width);
DrawLine(p3, p4, color, width);
DrawLine(p4, p1, color, width);
}
public static void DrawBox(Vector2 topLeftCorner, Vector2 bottomRightCorner, Color color, float width)
{
Rect box = new Rect(topLeftCorner.x, topLeftCorner.y, bottomRightCorner.x - topLeftCorner.x, bottomRightCorner.y - topLeftCorner.y);
DrawBox(box, color, width);
}
public static void DrawRoundedBox(Rect box, float radius, Color color, float width)
{
Vector2 p1, p2, p3, p4, p5, p6, p7, p8;
p1 = new Vector2(box.xMin + radius, box.yMin);
p2 = new Vector2(box.xMax - radius, box.yMin);
p3 = new Vector2(box.xMax, box.yMin + radius);
p4 = new Vector2(box.xMax, box.yMax - radius);
p5 = new Vector2(box.xMax - radius, box.yMax);
p6 = new Vector2(box.xMin + radius, box.yMax);
p7 = new Vector2(box.xMin, box.yMax - radius);
p8 = new Vector2(box.xMin, box.yMin + radius);
DrawLine(p1, p2, color, width);
DrawLine(p3, p4, color, width);
DrawLine(p5, p6, color, width);
DrawLine(p7, p8, color, width);
Vector2 t1, t2;
float halfRadius = radius / 2;
t1 = new Vector2(p8.x, p8.y + halfRadius);
t2 = new Vector2(p1.x - halfRadius, p1.y);
DrawBezier(p8, t1, p1, t2, color, width);
t1 = new Vector2(p2.x + halfRadius, p2.y);
t2 = new Vector2(p3.x, p3.y - halfRadius);
DrawBezier(p2, t1, p3, t2, color, width);
t1 = new Vector2(p4.x, p4.y + halfRadius);
t2 = new Vector2(p5.x + halfRadius, p5.y);
DrawBezier(p4, t1, p5, t2, color, width);
t1 = new Vector2(p6.x - halfRadius, p6.y);
t2 = new Vector2(p7.x, p7.y + halfRadius);
DrawBezier(p6, t1, p7, t2, color, width);
}
public static void DrawConnectingCurve(Vector2 start, Vector2 end, Color color, float width)
{
Vector2 distance = start - end;
Vector2 tangentA = start;
tangentA.x -= distance.x * 0.5f;
Vector2 tangentB = end;
tangentB.x += distance.x * 0.5f;
int segments = Mathf.FloorToInt((distance.magnitude / 20) * 3);
DrawBezier(start, tangentA, end, tangentB, color, width, segments);
Vector2 pA = CubeBezier(start, tangentA, end, tangentB, 0.7f);
Vector2 pB = CubeBezier(start, tangentA, end, tangentB, 0.8f);
float arrowHeadSize = 10;
Vector2 arrowPosA = pB;
Vector2 arrowPosB = arrowPosA;
Vector2 arrowPosC = arrowPosA;
Vector2 dir = (pB - pA).normalized;
arrowPosB.x += dir.y * arrowHeadSize;
arrowPosB.y -= dir.x * arrowHeadSize;
arrowPosB -= dir * arrowHeadSize;
arrowPosC.x -= dir.y * arrowHeadSize;
arrowPosC.y += dir.x * arrowHeadSize;
arrowPosC -= dir * arrowHeadSize;
DrawLine(arrowPosA, arrowPosB, color, 1);
DrawLine(arrowPosA, arrowPosC, color, 1);
DrawLine(arrowPosB, arrowPosC, color, 1);
}
public static void DrawBezier(Vector2 start, Vector2 startTangent, Vector2 end, Vector2 endTangent, Color color, float width)
{
int segments = Mathf.FloorToInt((start - end).magnitude / 20) * 3; // Three segments per distance of 20
DrawBezier(start, startTangent, end, endTangent, color, width, segments);
}
public static void DrawBezier(Vector2 start, Vector2 startTangent, Vector2 end, Vector2 endTangent, Color color, float width, int segments)
{
Vector2 startVector = CubeBezier(start, startTangent, end, endTangent, 0);
for (int i = 1; i <= segments; i++)
{
Vector2 endVector = CubeBezier(start, startTangent, end, endTangent, i / (float)segments);
DrawLine(startVector, endVector, color, width);
startVector = endVector;
}
}
private static Vector2 CubeBezier(Vector2 s, Vector2 st, Vector2 e, Vector2 et, float t)
{
float rt = 1 - t;
float rtt = rt * t;
return rt * rt * rt * s + 3 * rt * rtt * st + 3 * rtt * t * et + t * t * t * e;
}
}
| |
using System;
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.VFX;
namespace UnityEditor.VFX.Block
{
class PositionSequentialVariantProvider : VariantProvider
{
protected override sealed Dictionary<string, object[]> variants
{
get
{
return new Dictionary<string, object[]>
{
{ "shape", Enum.GetValues(typeof(PositionSequential.SequentialShape)).Cast<object>().ToArray() }
};
}
}
}
[VFXInfo(category = "Position", variantProvider = typeof(PositionSequentialVariantProvider), experimental = true)]
class PositionSequential : VFXBlock
{
public enum SequentialShape
{
Line,
Circle,
ThreeDimensional,
}
public enum IndexMode
{
ParticleID,
Custom
}
[SerializeField, VFXSetting(VFXSettingAttribute.VisibleFlags.InInspector)]
[Tooltip(@"Shape used for this sequence")]
protected SequentialShape shape = SequentialShape.Line;
[SerializeField, VFXSetting]
[Tooltip(@"Index used for fetching progression in this sequence:
- Particle ID
- Custom provided index")]
protected IndexMode index = IndexMode.ParticleID;
[SerializeField, VFXSetting]
[Tooltip("Write position")]
private bool writePosition = true;
[SerializeField, VFXSetting]
[Tooltip("Write target position")]
private bool writeTargetPosition = false;
[SerializeField, VFXSetting]
private VFXOperatorUtility.SequentialAddressingMode mode = VFXOperatorUtility.SequentialAddressingMode.Wrap;
public override string name { get { return string.Format("Position : Sequential ({0})", shape); } }
public override VFXContextType compatibleContexts { get { return VFXContextType.kInitAndUpdateAndOutput; } }
public override VFXDataType compatibleData { get { return VFXDataType.kParticle; } }
public class InputProperties
{
}
public class InputPropertiesCustomIndex
{
[Tooltip("Index used to sample the sequential distribution")]
public uint Index = 0;
}
public class InputPropertiesWritePosition
{
[Tooltip("Offset applied to the initial index used to compute the position")]
public int OffsetIndex = 0;
}
public class InputPropertiesWriteTargetPosition
{
[Tooltip("Offset applied to the initial index used to compute the target position")]
public int OffsetTargetIndex = 1;
}
public class InputPropertiesLine
{
[Tooltip("Element count used to loop over the sequence")]
public uint Count = 64;
[Tooltip("Start Position")]
public Position Start = Position.defaultValue;
[Tooltip("End Position")]
public Position End = new Position() { position = new Vector3(1, 0, 0) };
}
public class InputPropertiesCircle
{
[Tooltip("Element count used to loop over the sequence")]
public uint Count = 64;
[Tooltip("Center of the circle")]
public Position Center = Position.defaultValue;
[Tooltip("Rotation Axis")]
public DirectionType Normal = new DirectionType() { direction = Vector3.forward };
[Tooltip("Start Angle (Midnight direction)")]
public DirectionType Up = new DirectionType() { direction = Vector3.up };
[Tooltip("Radius of the circle")]
public float Radius = 1.0f;
}
public class InputPropertiesThreeDimensional
{
[Tooltip("Element X count used to loop over the sequence")]
public uint CountX = 8;
[Tooltip("Element Y count used to loop over the sequence")]
public uint CountY = 8;
[Tooltip("Element Z count used to loop over the sequence")]
public uint CountZ = 8;
public Position Origin = Position.defaultValue;
public Vector AxisX = Vector3.right;
public Vector AxisY = Vector3.up;
public Vector AxisZ = Vector3.forward;
}
protected override IEnumerable<VFXPropertyWithValue> inputProperties
{
get
{
var commonProperties = PropertiesFromType("InputProperties");
if (index == IndexMode.Custom)
commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesCustomIndex"));
if (writePosition)
commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesWritePosition"));
if (writeTargetPosition)
commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesWriteTargetPosition"));
switch (shape)
{
case SequentialShape.Line: commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesLine")); break;
case SequentialShape.Circle: commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesCircle")); break;
case SequentialShape.ThreeDimensional: commonProperties = commonProperties.Concat(PropertiesFromType("InputPropertiesThreeDimensional")); break;
}
return commonProperties;
}
}
public override IEnumerable<VFXAttributeInfo> attributes
{
get
{
if (index == IndexMode.ParticleID)
yield return new VFXAttributeInfo(VFXAttribute.ParticleId, VFXAttributeMode.Read);
if (writePosition)
yield return new VFXAttributeInfo(VFXAttribute.Position, VFXAttributeMode.ReadWrite);
if (writeTargetPosition)
yield return new VFXAttributeInfo(VFXAttribute.TargetPosition, VFXAttributeMode.ReadWrite);
}
}
private VFXExpression GetPositionFromIndex(VFXExpression indexExpr, IEnumerable<VFXNamedExpression> expressions)
{
if (shape == SequentialShape.Line)
{
var start = expressions.First(o => o.name == "Start").exp;
var end = expressions.First(o => o.name == "End").exp;
var count = expressions.First(o => o.name == "Count").exp;
return VFXOperatorUtility.SequentialLine(start, end, indexExpr, count, mode);
}
else if (shape == SequentialShape.Circle)
{
var center = expressions.First(o => o.name == "Center").exp;
var normal = expressions.First(o => o.name == "Normal").exp;
var up = expressions.First(o => o.name == "Up").exp;
var radius = expressions.First(o => o.name == "Radius").exp;
var count = expressions.First(o => o.name == "Count").exp;
return VFXOperatorUtility.SequentialCircle(center, radius, normal, up, indexExpr, count, mode);
}
else if (shape == SequentialShape.ThreeDimensional)
{
var origin = expressions.First(o => o.name == "Origin").exp;
var axisX = expressions.First(o => o.name == "AxisX").exp;
var axisY = expressions.First(o => o.name == "AxisY").exp;
var axisZ = expressions.First(o => o.name == "AxisZ").exp;
var countX = expressions.First(o => o.name == "CountX").exp;
var countY = expressions.First(o => o.name == "CountY").exp;
var countZ = expressions.First(o => o.name == "CountZ").exp;
return VFXOperatorUtility.Sequential3D(origin, axisX, axisY, axisZ, indexExpr, countX, countY, countZ, mode);
}
throw new NotImplementedException();
}
private static readonly string s_computedPosition = "computedPosition";
private static readonly string s_computedTargetPosition = "computedTargetPosition";
public override IEnumerable<VFXNamedExpression> parameters
{
get
{
var expressions = GetExpressionsFromSlots(this);
var indexExpr = (index == IndexMode.ParticleID) ? new VFXAttributeExpression(VFXAttribute.ParticleId) : expressions.First(o => o.name == "Index").exp;
if (writePosition)
{
var indexOffsetExpr = indexExpr + new VFXExpressionCastIntToUint(expressions.First(o => o.name == "OffsetIndex").exp);
var positionExpr = GetPositionFromIndex(indexOffsetExpr, expressions);
yield return new VFXNamedExpression(positionExpr, s_computedPosition);
}
if (writeTargetPosition)
{
var indexOffsetExpr = indexExpr + new VFXExpressionCastIntToUint(expressions.First(o => o.name == "OffsetTargetIndex").exp);
var positionExpr = GetPositionFromIndex(indexOffsetExpr, expressions);
yield return new VFXNamedExpression(positionExpr, s_computedTargetPosition);
}
}
}
public override string source
{
get
{
var source = string.Empty;
if (writePosition)
{
source += string.Format("position += {0};\n", s_computedPosition);
}
if (writeTargetPosition)
{
source += string.Format("targetPosition += {0};\n", s_computedTargetPosition);
}
return source;
}
}
}
}
| |
// Copyright (c) Six Labors.
// Licensed under the Apache License, Version 2.0.
using System.IO;
namespace SixLabors.Fonts.Tables.AdvancedTypographic.GPos
{
/// <summary>
/// Lookup Type 7: Contextual Positioning Subtables.
/// A Contextual Positioning subtable describes glyph positioning in context so a text-processing client can adjust the position
/// of one or more glyphs within a certain pattern of glyphs.
/// <see href="https://docs.microsoft.com/en-us/typography/opentype/spec/gpos#lookup-type-7-contextual-positioning-subtables"/>
/// </summary>
internal static class LookupType7SubTable
{
public static LookupSubTable Load(BigEndianBinaryReader reader, long offset, LookupFlags lookupFlags)
{
reader.Seek(offset, SeekOrigin.Begin);
ushort subTableFormat = reader.ReadUInt16();
return subTableFormat switch
{
1 => LookupType7Format1SubTable.Load(reader, offset, lookupFlags),
2 => LookupType7Format2SubTable.Load(reader, offset, lookupFlags),
3 => LookupType7Format3SubTable.Load(reader, offset, lookupFlags),
_ => throw new InvalidFontFileException(
$"Invalid value for 'subTableFormat' {subTableFormat}. Should be '1', '2' or 3."),
};
}
internal sealed class LookupType7Format1SubTable : LookupSubTable
{
private readonly CoverageTable coverageTable;
private readonly SequenceRuleSetTable[] seqRuleSetTables;
public LookupType7Format1SubTable(CoverageTable coverageTable, SequenceRuleSetTable[] seqRuleSetTables, LookupFlags lookupFlags)
: base(lookupFlags)
{
this.seqRuleSetTables = seqRuleSetTables;
this.coverageTable = coverageTable;
}
public static LookupType7Format1SubTable Load(BigEndianBinaryReader reader, long offset, LookupFlags lookupFlags)
{
SequenceRuleSetTable[] seqRuleSets = TableLoadingUtils.LoadSequenceContextFormat1(reader, offset, out CoverageTable coverageTable);
return new LookupType7Format1SubTable(coverageTable, seqRuleSets, lookupFlags);
}
public override bool TryUpdatePosition(
FontMetrics fontMetrics,
GPosTable table,
GlyphPositioningCollection collection,
Tag feature,
ushort index,
int count)
{
ushort glyphId = collection[index][0];
if (glyphId == 0)
{
return false;
}
int offset = this.coverageTable.CoverageIndexOf(glyphId);
if (offset <= -1)
{
return false;
}
// TODO: Check this.
// https://docs.microsoft.com/en-us/typography/opentype/spec/gsub#example-7-contextual-substitution-format-1
SequenceRuleSetTable ruleSetTable = this.seqRuleSetTables[offset];
SkippingGlyphIterator iterator = new(fontMetrics, collection, index, this.LookupFlags);
foreach (SequenceRuleTable ruleTable in ruleSetTable.SequenceRuleTables)
{
int remaining = count - 1;
int seqLength = ruleTable.InputSequence.Length;
if (seqLength > remaining)
{
continue;
}
if (!AdvancedTypographicUtils.MatchSequence(iterator, 1, ruleTable.InputSequence))
{
continue;
}
// It's a match. Perform position update and return true if anything changed.
return AdvancedTypographicUtils.ApplyLookupList(
fontMetrics,
table,
feature,
this.LookupFlags,
ruleTable.SequenceLookupRecords,
collection,
index,
count);
}
return false;
}
}
internal sealed class LookupType7Format2SubTable : LookupSubTable
{
private readonly CoverageTable coverageTable;
private readonly ClassDefinitionTable classDefinitionTable;
private readonly ClassSequenceRuleSetTable[] sequenceRuleSetTables;
public LookupType7Format2SubTable(
CoverageTable coverageTable,
ClassDefinitionTable classDefinitionTable,
ClassSequenceRuleSetTable[] sequenceRuleSetTables,
LookupFlags lookupFlags)
: base(lookupFlags)
{
this.coverageTable = coverageTable;
this.classDefinitionTable = classDefinitionTable;
this.sequenceRuleSetTables = sequenceRuleSetTables;
}
public static LookupType7Format2SubTable Load(BigEndianBinaryReader reader, long offset, LookupFlags lookupFlags)
{
CoverageTable coverageTable = TableLoadingUtils.LoadSequenceContextFormat2(reader, offset, out ClassDefinitionTable classDefTable, out ClassSequenceRuleSetTable[] classSeqRuleSets);
return new LookupType7Format2SubTable(coverageTable, classDefTable, classSeqRuleSets, lookupFlags);
}
public override bool TryUpdatePosition(
FontMetrics fontMetrics,
GPosTable table,
GlyphPositioningCollection collection,
Tag feature,
ushort index,
int count)
{
ushort glyphId = collection[index][0];
if (glyphId == 0)
{
return false;
}
if (this.coverageTable.CoverageIndexOf(glyphId) < 0)
{
return false;
}
int offset = this.classDefinitionTable.ClassIndexOf(glyphId);
if (offset < 0)
{
return false;
}
ClassSequenceRuleSetTable ruleSetTable = this.sequenceRuleSetTables[offset];
SkippingGlyphIterator iterator = new(fontMetrics, collection, index, this.LookupFlags);
foreach (ClassSequenceRuleTable ruleTable in ruleSetTable.SequenceRuleTables)
{
int remaining = count - 1;
int seqLength = ruleTable.InputSequence.Length;
if (seqLength > remaining)
{
continue;
}
if (!AdvancedTypographicUtils.MatchClassSequence(iterator, 1, ruleTable.InputSequence, this.classDefinitionTable))
{
continue;
}
// It's a match. Perform position update and return true if anything changed.
return AdvancedTypographicUtils.ApplyLookupList(
fontMetrics,
table,
feature,
this.LookupFlags,
ruleTable.SequenceLookupRecords,
collection,
index,
count);
}
return false;
}
}
internal sealed class LookupType7Format3SubTable : LookupSubTable
{
private readonly CoverageTable[] coverageTables;
private readonly SequenceLookupRecord[] sequenceLookupRecords;
public LookupType7Format3SubTable(CoverageTable[] coverageTables, SequenceLookupRecord[] sequenceLookupRecords, LookupFlags lookupFlags)
: base(lookupFlags)
{
this.coverageTables = coverageTables;
this.sequenceLookupRecords = sequenceLookupRecords;
}
public static LookupType7Format3SubTable Load(BigEndianBinaryReader reader, long offset, LookupFlags lookupFlags)
{
SequenceLookupRecord[] seqLookupRecords = TableLoadingUtils.LoadSequenceContextFormat3(reader, offset, out CoverageTable[] coverageTables);
return new LookupType7Format3SubTable(coverageTables, seqLookupRecords, lookupFlags);
}
public override bool TryUpdatePosition(
FontMetrics fontMetrics,
GPosTable table,
GlyphPositioningCollection collection,
Tag feature,
ushort index,
int count)
{
ushort glyphId = collection[index][0];
if (glyphId == 0)
{
return false;
}
SkippingGlyphIterator iterator = new(fontMetrics, collection, index, this.LookupFlags);
if (!AdvancedTypographicUtils.MatchCoverageSequence(iterator, this.coverageTables, 0))
{
return false;
}
return AdvancedTypographicUtils.ApplyLookupList(
fontMetrics,
table,
feature,
this.LookupFlags,
this.sequenceLookupRecords,
collection,
index,
count);
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace NotificationHubsSample.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
#nullable enable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using IronPython.Runtime;
using Microsoft.Scripting.Actions;
using Microsoft.Scripting.Interpreter;
using Microsoft.Scripting.Utils;
using AstUtils = Microsoft.Scripting.Ast.Utils;
using MSAst = System.Linq.Expressions;
namespace IronPython.Compiler.Ast {
public class CallExpression : Expression, IInstructionProvider {
private readonly Expression[] _args;
private readonly Keyword[] _kwargs;
private Expression[]? _implicitArgs;
public CallExpression(Expression target, IReadOnlyList<Expression>? args, IReadOnlyList<Keyword>? kwargs) {
Target = target;
_args = args?.ToArray() ?? Array.Empty<Expression>();
_kwargs = kwargs?.ToArray() ?? Array.Empty<Keyword>();
}
public Expression Target { get; }
public IReadOnlyList<Expression> Args => _args;
public IReadOnlyList<Keyword> Kwargs => _kwargs;
internal void SetImplicitArgs(params Expression[] args) {
_implicitArgs = args;
}
public bool NeedsLocalsDictionary() {
if (!(Target is NameExpression nameExpr)) return false;
if (nameExpr.Name == "eval" || nameExpr.Name == "exec") return true;
if (nameExpr.Name == "dir" || nameExpr.Name == "vars" || nameExpr.Name == "locals") {
// could be splatting empty list or dict resulting in 0-param call which needs context
return Args.All(arg => arg is StarredExpression) && Kwargs.All(arg => arg.Name is null);
}
return false;
}
private static readonly Argument _listTypeArgument = new(ArgumentType.List);
private static readonly Argument _dictTypeArgument = new(ArgumentType.Dictionary);
public override MSAst.Expression Reduce() {
ReadOnlySpan<Expression> args = _args;
ReadOnlySpan<Keyword> kwargs = _kwargs;
if (args.Length == 0 && _implicitArgs != null) {
args = _implicitArgs;
}
// count splatted list args and find the lowest index of a list argument, if any
ScanArgs(args, out var numList, out int firstListPos);
Debug.Assert(numList == 0 || firstListPos < args.Length);
// count splatted dictionary args and find the lowest index of a dict argument, if any
ScanKwargs(kwargs, out var numDict, out int firstDictPos);
Debug.Assert(numDict == 0 || firstDictPos < kwargs.Length);
// all list arguments and all simple arguments after the first list will be collated into a single list for the actual call
// all dictionary arguments will be merged into a single dictionary for the actual call
Argument[] kinds = new Argument[firstListPos + Math.Min(numList, 1) + (Kwargs.Count - numDict) + Math.Min(numDict, 1)];
MSAst.Expression[] values = new MSAst.Expression[2 + kinds.Length];
values[0] = Parent.LocalContext;
values[1] = Target;
int i = 0;
// add simple arguments
if (firstListPos > 0) {
foreach (var arg in args) {
if (i == firstListPos) break;
Debug.Assert(arg is not StarredExpression);
kinds[i] = Argument.Simple;
values[i + 2] = arg;
i++;
}
}
// unpack list arguments
if (numList > 0) {
kinds[i] = _listTypeArgument;
values[i + 2] = UnpackListHelper(args.Slice(firstListPos));
i++;
}
// add named arguments
if (Kwargs.Count != numDict) {
foreach (var arg in Kwargs) {
if (arg.Name is not null) {
kinds[i] = new Argument(arg.Name);
values[i + 2] = arg.Expression;
i++;
}
}
}
// unpack dict arguments
if (numDict > 0) {
kinds[i] = _dictTypeArgument;
values[i + 2] = UnpackDictHelper(Parent.LocalContext, kwargs.Slice(firstDictPos), numDict);
}
return Parent.Invoke(
new CallSignature(kinds),
values
);
static void ScanArgs(ReadOnlySpan<Expression> args, out int numArgs, out int firstArgPos) {
numArgs = 0;
firstArgPos = args.Length;
if (args.Length == 0) return;
for (var i = args.Length - 1; i >= 0; i--) {
var arg = args[i];
if (arg is StarredExpression) {
firstArgPos = i;
numArgs++;
}
}
}
static void ScanKwargs(ReadOnlySpan<Keyword> kwargs, out int numArgs, out int firstArgPos) {
numArgs = 0;
firstArgPos = kwargs.Length;
if (kwargs.Length == 0) return;
for (var i = kwargs.Length - 1; i >= 0; i--) {
var kwarg = kwargs[i];
if (kwarg.Name is null) {
firstArgPos = i;
numArgs++;
}
}
}
// Compare to: ClassDefinition.Reduce.__UnpackBasesHelper
static MSAst.Expression UnpackListHelper(ReadOnlySpan<Expression> args) {
Debug.Assert(args.Length > 0);
Debug.Assert(args[0] is StarredExpression);
if (args.Length == 1) return ((StarredExpression)args[0]).Value;
return UnpackSequenceHelper<PythonList>(args, AstMethods.MakeEmptyList, AstMethods.ListAppend, AstMethods.ListExtend);
}
// Compare to: CallExpression.Reduce.__UnpackKeywordsHelper
static MSAst.Expression UnpackDictHelper(MSAst.Expression context, ReadOnlySpan<Keyword> kwargs, int numDict) {
Debug.Assert(kwargs.Length > 0);
Debug.Assert(0 < numDict && numDict <= kwargs.Length);
Debug.Assert(kwargs[0].Name is null);
if (numDict == 1) return kwargs[0].Expression;
var expressions = new ReadOnlyCollectionBuilder<MSAst.Expression>(numDict + 2);
var varExpr = Expression.Variable(typeof(PythonDictionary), "$dict");
expressions.Add(Expression.Assign(varExpr, Expression.Call(AstMethods.MakeEmptyDict)));
foreach (var arg in kwargs) {
if (arg.Name is null) {
expressions.Add(Expression.Call(AstMethods.DictMerge, context, varExpr, AstUtils.Convert(arg.Expression, typeof(object))));
}
}
expressions.Add(varExpr);
return Expression.Block(typeof(PythonDictionary), new MSAst.ParameterExpression[] { varExpr }, expressions);
}
}
#region IInstructionProvider Members
void IInstructionProvider.AddInstructions(LightCompiler compiler) {
ReadOnlySpan<Expression> args = _args;
if (args.Length == 0 && _implicitArgs != null) {
args = _implicitArgs;
}
if (Kwargs.Count > 0) {
compiler.Compile(Reduce());
return;
}
for (int i = 0; i < args.Length; i++) {
if (args[i] is StarredExpression) {
compiler.Compile(Reduce());
return;
}
}
switch (args.Length) {
#region Generated Python Call Expression Instruction Switch
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instruction_switch from: generate_calls.py
case 0:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Instructions.Emit(new Invoke0Instruction(Parent.PyContext));
return;
case 1:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Instructions.Emit(new Invoke1Instruction(Parent.PyContext));
return;
case 2:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Compile(args[1]);
compiler.Instructions.Emit(new Invoke2Instruction(Parent.PyContext));
return;
case 3:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Compile(args[1]);
compiler.Compile(args[2]);
compiler.Instructions.Emit(new Invoke3Instruction(Parent.PyContext));
return;
case 4:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Compile(args[1]);
compiler.Compile(args[2]);
compiler.Compile(args[3]);
compiler.Instructions.Emit(new Invoke4Instruction(Parent.PyContext));
return;
case 5:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Compile(args[1]);
compiler.Compile(args[2]);
compiler.Compile(args[3]);
compiler.Compile(args[4]);
compiler.Instructions.Emit(new Invoke5Instruction(Parent.PyContext));
return;
case 6:
compiler.Compile(Parent.LocalContext);
compiler.Compile(Target);
compiler.Compile(args[0]);
compiler.Compile(args[1]);
compiler.Compile(args[2]);
compiler.Compile(args[3]);
compiler.Compile(args[4]);
compiler.Compile(args[5]);
compiler.Instructions.Emit(new Invoke6Instruction(Parent.PyContext));
return;
// *** END GENERATED CODE ***
#endregion
}
compiler.Compile(Reduce());
}
#endregion
private abstract class InvokeInstruction : Instruction {
public override int ProducedStack => 1;
public override string InstructionName => "Python Invoke" + (ConsumedStack - 1);
}
#region Generated Python Call Expression Instructions
// *** BEGIN GENERATED CODE ***
// generated by function: gen_call_expression_instructions from: generate_calls.py
private class Invoke0Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object>> _site;
public Invoke0Instruction(PythonContext context) {
_site = context.CallSite0;
}
public override int ConsumedStack => 2;
public override int Run(InterpretedFrame frame) {
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target));
return +1;
}
}
private class Invoke1Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object>> _site;
public Invoke1Instruction(PythonContext context) {
_site = context.CallSite1;
}
public override int ConsumedStack => 3;
public override int Run(InterpretedFrame frame) {
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0));
return +1;
}
}
private class Invoke2Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object>> _site;
public Invoke2Instruction(PythonContext context) {
_site = context.CallSite2;
}
public override int ConsumedStack => 4;
public override int Run(InterpretedFrame frame) {
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1));
return +1;
}
}
private class Invoke3Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object>> _site;
public Invoke3Instruction(PythonContext context) {
_site = context.CallSite3;
}
public override int ConsumedStack => 5;
public override int Run(InterpretedFrame frame) {
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2));
return +1;
}
}
private class Invoke4Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object>> _site;
public Invoke4Instruction(PythonContext context) {
_site = context.CallSite4;
}
public override int ConsumedStack => 6;
public override int Run(InterpretedFrame frame) {
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3));
return +1;
}
}
private class Invoke5Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object>> _site;
public Invoke5Instruction(PythonContext context) {
_site = context.CallSite5;
}
public override int ConsumedStack => 7;
public override int Run(InterpretedFrame frame) {
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4));
return +1;
}
}
private class Invoke6Instruction : InvokeInstruction {
private readonly CallSite<Func<CallSite, CodeContext, object, object, object, object, object, object, object, object>> _site;
public Invoke6Instruction(PythonContext context) {
_site = context.CallSite6;
}
public override int ConsumedStack => 8;
public override int Run(InterpretedFrame frame) {
var arg5 = frame.Pop();
var arg4 = frame.Pop();
var arg3 = frame.Pop();
var arg2 = frame.Pop();
var arg1 = frame.Pop();
var arg0 = frame.Pop();
var target = frame.Pop();
frame.Push(_site.Target(_site, (CodeContext)frame.Pop(), target, arg0, arg1, arg2, arg3, arg4, arg5));
return +1;
}
}
// *** END GENERATED CODE ***
#endregion
public override string NodeName => "function call";
public override void Walk(PythonWalker walker) {
if (walker.Walk(this)) {
Target?.Walk(walker);
if (_implicitArgs is not null) {
foreach (var arg in _implicitArgs) {
arg.Walk(walker);
}
}
foreach (var arg in _args) {
arg.Walk(walker);
}
foreach (var arg in _kwargs) {
arg.Walk(walker);
}
}
walker.PostWalk(this);
}
}
}
| |
// The MIT License (MIT)
//
// CoreTweet - A .NET Twitter Library supporting Twitter API 1.1
// Copyright (c) 2013-2015 CoreTweet Development Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using CoreTweet.Core;
namespace CoreTweet
{
/// <summary>
/// Provides the type of the HTTP method.
/// </summary>
public enum MethodType
{
/// <summary>
/// GET method.
/// </summary>
Get,
/// <summary>
/// POST method.
/// </summary>
Post
}
/// <summary>
/// Provides a set of static (Shared in Visual Basic) methods for sending a request to Twitter and some other web services.
/// </summary>
internal static partial class Request
{
private static string CreateQueryString(IEnumerable<KeyValuePair<string, string>> prm)
{
return prm.Select(x => UrlEncode(x.Key) + "=" + UrlEncode(x.Value)).JoinToString("&");
}
internal static string CreateQueryString(IEnumerable<KeyValuePair<string, object>> prm)
{
return CreateQueryString(prm.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())));
}
#if !WIN_RT
private static void WriteMultipartFormData(Stream stream, string boundary, IEnumerable<KeyValuePair<string, object>> prm)
{
const int bufferSize = 81920;
prm.ForEach(x =>
{
var valueStream = x.Value as Stream;
var valueBytes = x.Value as IEnumerable<byte>;
#if !PCL
var valueFile = x.Value as FileInfo;
#endif
var valueString = x.Value.ToString();
#if WP
var valueInputStream = x.Value as Windows.Storage.Streams.IInputStream;
if(valueInputStream != null) valueStream = valueInputStream.AsStreamForRead();
#endif
stream.WriteString("--" + boundary + "\r\n");
if(valueStream != null || valueBytes != null
#if !PCL
|| valueFile != null
#endif
)
{
stream.WriteString("Content-Type: application/octet-stream\r\n");
}
stream.WriteString(string.Format(@"Content-Disposition: form-data; name=""{0}""", x.Key));
#if !PCL
if(valueFile != null)
stream.WriteString(string.Format(@"; filename=""{0}""",
valueFile.Name.Replace("\n", "%0A").Replace("\r", "%0D").Replace("\"", "%22")));
else
#endif
if(valueStream != null || valueBytes != null)
stream.WriteString(@"; filename=""file""");
stream.WriteString("\r\n\r\n");
#if !PCL
if(valueFile != null)
valueStream = valueFile.OpenRead();
#endif
if(valueStream != null)
{
var buffer = new byte[bufferSize];
int count;
while((count = valueStream.Read(buffer, 0, bufferSize)) > 0)
stream.Write(buffer, 0, count);
}
else if(valueBytes != null)
{
var buffer = valueBytes as byte[];
if(buffer != null)
stream.Write(buffer, 0, buffer.Length);
else
{
buffer = new byte[bufferSize];
var i = 0;
foreach(var b in valueBytes)
{
buffer[i++] = b;
if(i == bufferSize)
{
stream.Write(buffer, 0, bufferSize);
i = 0;
}
}
if(i > 0)
stream.Write(buffer, 0, i);
}
}
else
stream.WriteString(valueString);
#if !PCL
if(valueFile != null)
valueStream.Close();
#endif
stream.WriteString("\r\n");
});
stream.WriteString("--" + boundary + "--");
}
#endif
#if !WP
private const DecompressionMethods CompressionType = DecompressionMethods.GZip | DecompressionMethods.Deflate;
#endif
#if !(PCL || WIN_RT || WP)
internal static HttpWebResponse HttpGet(Uri url, string authorizationHeader, ConnectionOptions options)
{
if(options == null) options = new ConnectionOptions();
var req = (HttpWebRequest)WebRequest.Create(url);
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
return (HttpWebResponse)req.GetResponse();
}
internal static HttpWebResponse HttpPost(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(prm == null) prm = new Dictionary<string,object>();
if(options == null) options = new ConnectionOptions();
var data = Encoding.UTF8.GetBytes(CreateQueryString(prm));
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = data.Length;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
using(var reqstr = req.GetRequestStream())
reqstr.Write(data, 0, data.Length);
return (HttpWebResponse)req.GetResponse();
}
internal static HttpWebResponse HttpPostWithMultipartFormData(Uri url, IEnumerable<KeyValuePair<string, object>> prm, string authorizationHeader, ConnectionOptions options)
{
if(options == null) options = new ConnectionOptions();
var boundary = Guid.NewGuid().ToString();
var req = (HttpWebRequest)WebRequest.Create(url);
req.ServicePoint.Expect100Continue = false;
req.Method = "POST";
req.Timeout = options.Timeout;
req.ReadWriteTimeout = options.ReadWriteTimeout;
req.UserAgent = options.UserAgent;
req.Proxy = options.Proxy;
req.ContentType = "multipart/form-data;boundary=" + boundary;
req.Headers.Add(HttpRequestHeader.Authorization, authorizationHeader);
req.SendChunked = true;
if(options.UseCompression)
req.AutomaticDecompression = CompressionType;
if (options.DisableKeepAlive)
req.KeepAlive = false;
options.BeforeRequestAction?.Invoke(req);
using(var reqstr = req.GetRequestStream())
WriteMultipartFormData(reqstr, boundary, prm);
return (HttpWebResponse)req.GetResponse();
}
#endif
/// <summary>
/// Generates the signature.
/// </summary>
/// <param name="t">The tokens.</param>
/// <param name="httpMethod">The HTTP method.</param>
/// <param name="url">The URL.</param>
/// <param name="prm">The parameters.</param>
/// <returns>The signature.</returns>
internal static string GenerateSignature(Tokens t, MethodType httpMethod, Uri url, IEnumerable<KeyValuePair<string, string>> prm)
{
var key = Encoding.UTF8.GetBytes(
string.Format("{0}&{1}", UrlEncode(t.ConsumerSecret),
UrlEncode(t.AccessTokenSecret)));
var prmstr = prm.Select(x => new KeyValuePair<string, string>(UrlEncode(x.Key), UrlEncode(x.Value)))
.Concat(
url.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries)
.Select(x =>
{
var s = x.Split('=');
return new KeyValuePair<string, string>(s[0], s[1]);
})
)
.OrderBy(x => x.Key).ThenBy(x => x.Value)
.Select(x => x.Key + "=" + x.Value)
.JoinToString("&");
var msg = Encoding.UTF8.GetBytes(
string.Format("{0}&{1}&{2}",
httpMethod.ToString().ToUpperInvariant(),
UrlEncode(url.GetComponents(UriComponents.Scheme | UriComponents.UserInfo | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped)),
UrlEncode(prmstr)
));
return Convert.ToBase64String(SecurityUtils.HmacSha1(key, msg));
}
/// <summary>
/// Generates the parameters.
/// </summary>
/// <param name="consumerKey">The consumer key.</param>
/// <param name="token">The token.</param>
/// <returns>The parameters.</returns>
internal static Dictionary<string, string> GenerateParameters(string consumerKey, string token)
{
var ret = new Dictionary<string, string>() {
{"oauth_consumer_key", consumerKey},
{"oauth_signature_method", "HMAC-SHA1"},
{"oauth_timestamp", ((DateTimeOffset.UtcNow - InternalUtils.unixEpoch).Ticks / 10000000L).ToString("D")},
{"oauth_nonce", new Random().Next(int.MinValue, int.MaxValue).ToString("X")},
{"oauth_version", "1.0"}
};
if(!string.IsNullOrEmpty(token))
ret.Add("oauth_token", token);
return ret;
}
/// <summary>
/// Encodes the specified text.
/// </summary>
/// <param name="text">The text.</param>
/// <returns>The encoded text.</returns>
internal static string UrlEncode(string text)
{
if(string.IsNullOrEmpty(text))
return "";
return Encoding.UTF8.GetBytes(text)
.Select(x => x < 0x80 && "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~"
.Contains(((char)x).ToString()) ? ((char)x).ToString() : ('%' + x.ToString("X2")))
.JoinToString();
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.SignalR;
using Microsoft.Azure.SignalR.Management;
namespace Microsoft.Azure.WebJobs.Extensions.SignalRService
{
/// <summary>
/// AzureSignalRClient used for negotiation, publishing messages and managing group membership.
/// It will be created for each function request.
/// </summary>
internal class AzureSignalRClient : IAzureSignalRSender
{
public const string AzureSignalRUserPrefix = "asrs.u.";
private static readonly string[] SystemClaims =
{
"aud", // Audience claim, used by service to make sure token is matched with target resource.
"exp", // Expiration time claims. A token is valid only before its expiration time.
"iat", // Issued At claim. Added by default. It is not validated by service.
"nbf" // Not Before claim. Added by default. It is not validated by service.
};
private readonly ServiceHubContext _serviceHubContext;
public AzureSignalRClient(ServiceHubContext serviceHubContext)
{
_serviceHubContext = serviceHubContext;
}
public Task<SignalRConnectionInfo> GetClientConnectionInfoAsync(string userId, string idToken, string[] claimTypeList, HttpContext httpContext)
{
var customerClaims = GetCustomClaims(idToken, claimTypeList);
return GetClientConnectionInfoAsync(userId, customerClaims, httpContext);
}
public async Task<SignalRConnectionInfo> GetClientConnectionInfoAsync(string userId, IList<Claim> claims, HttpContext httpContext)
{
var negotiateResponse = await _serviceHubContext.NegotiateAsync(new NegotiationOptions()
{
UserId = userId,
Claims = BuildJwtClaims(claims, AzureSignalRUserPrefix).ToList(),
HttpContext = httpContext
}).ConfigureAwait(false);
return new SignalRConnectionInfo
{
Url = negotiateResponse.Url,
AccessToken = negotiateResponse.AccessToken
};
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Breaking change")]
public IList<Claim> GetCustomClaims(string idToken, string[] claimTypeList)
{
var customClaims = new List<Claim>();
if (idToken != null && claimTypeList != null && claimTypeList.Length > 0)
{
var jwtToken = new JwtSecurityTokenHandler().ReadJwtToken(idToken);
foreach (var claim in jwtToken.Claims)
{
if (claimTypeList.Contains(claim.Type))
{
customClaims.Add(claim);
}
}
}
return customClaims;
}
public Task SendToAll(SignalRData data)
{
return InvokeAsync(data.Endpoints, hubContext => hubContext.Clients.All.SendCoreAsync(data.Target, data.Arguments));
}
public Task SendToConnection(string connectionId, SignalRData data)
{
return InvokeAsync(data.Endpoints, hubContext => hubContext.Clients.Client(connectionId).SendCoreAsync(data.Target, data.Arguments));
}
public Task SendToUser(string userId, SignalRData data)
{
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException($"{nameof(userId)} cannot be null or empty");
}
return InvokeAsync(data.Endpoints, hubContext => hubContext.Clients.User(userId).SendCoreAsync(data.Target, data.Arguments));
}
public Task SendToGroup(string groupName, SignalRData data)
{
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException($"{nameof(groupName)} cannot be null or empty");
}
return InvokeAsync(data.Endpoints, hubContext => hubContext.Clients.Group(groupName).SendCoreAsync(data.Target, data.Arguments));
}
public Task AddUserToGroup(SignalRGroupAction action)
{
var userId = action.UserId;
var groupName = action.GroupName;
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException($"{nameof(userId)} cannot be null or empty");
}
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException($"{nameof(groupName)} cannot be null or empty");
}
return InvokeAsync(action.Endpoints, hubContext => hubContext.UserGroups.AddToGroupAsync(userId, groupName));
}
public Task RemoveUserFromGroup(SignalRGroupAction action)
{
var userId = action.UserId;
var groupName = action.GroupName;
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException($"{nameof(userId)} cannot be null or empty");
}
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException($"{nameof(groupName)} cannot be null or empty");
}
return InvokeAsync(action.Endpoints, hubContext => hubContext.UserGroups.RemoveFromGroupAsync(userId, groupName));
}
public Task RemoveUserFromAllGroups(SignalRGroupAction action)
{
var userId = action.UserId;
if (string.IsNullOrEmpty(userId))
{
throw new ArgumentException($"{nameof(userId)} cannot be null or empty");
}
return InvokeAsync(action.Endpoints, hubContext => hubContext.UserGroups.RemoveFromAllGroupsAsync(userId));
}
public Task AddConnectionToGroup(SignalRGroupAction action)
{
var connectionId = action.ConnectionId;
var groupName = action.GroupName;
if (string.IsNullOrEmpty(connectionId))
{
throw new ArgumentException($"{nameof(connectionId)} cannot be null or empty");
}
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException($"{nameof(groupName)} cannot be null or empty");
}
return InvokeAsync(action.Endpoints, hubContext => hubContext.Groups.AddToGroupAsync(connectionId, groupName));
}
public Task RemoveConnectionFromGroup(SignalRGroupAction action)
{
var connectionId = action.ConnectionId;
var groupName = action.GroupName;
if (string.IsNullOrEmpty(connectionId))
{
throw new ArgumentException($"{nameof(connectionId)} cannot be null or empty");
}
if (string.IsNullOrEmpty(groupName))
{
throw new ArgumentException($"{nameof(groupName)} cannot be null or empty");
}
return InvokeAsync(action.Endpoints, hubContext => hubContext.Groups.RemoveFromGroupAsync(connectionId, groupName));
}
private static IEnumerable<Claim> BuildJwtClaims(IEnumerable<Claim> customerClaims, string prefix)
{
if (customerClaims != null)
{
foreach (var claim in customerClaims)
{
// Add AzureSignalRUserPrefix if customer's claim name is duplicated with SignalR system claims.
// And split it when return from SignalR Service.
if (SystemClaims.Contains(claim.Type))
{
yield return new Claim(prefix + claim.Type, claim.Value);
}
else
{
yield return claim;
}
}
}
}
private async Task InvokeAsync(ServiceEndpoint[] endpoints, Func<ServiceHubContext, Task> func)
{
var targetHubContext = endpoints == null ? _serviceHubContext : (_serviceHubContext as IInternalServiceHubContext).WithEndpoints(endpoints);
await func.Invoke(targetHubContext).ConfigureAwait(false);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using GraphSharp.Algorithms.EdgeRouting;
using GraphSharp.Algorithms.Highlight;
using GraphSharp.Algorithms.Layout;
using GraphSharp.Algorithms.OverlapRemoval;
using QuickGraph;
using GraphSharp.Algorithms.Layout.Compound;
using Windows.Foundation;
using Windows.UI.Xaml;
namespace GraphSharp.Controls
{
/// <summary>
/// For general purposes, with general types.
/// </summary>
public class GraphLayout : GraphLayout<object, IEdge<object>, IBidirectionalGraph<object, IEdge<object>>>
{
public GraphLayout()
{
//bcz:
//if (System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
//{
// var g = new BidirectionalGraph<object, IEdge<object>>();
// var vertices = new object[] { "S", "A", "M", "P", "L", "E" };
// var edges = new IEdge<object>[] {
// new Edge<object>(vertices[0], vertices[1]),
// new Edge<object>(vertices[1], vertices[2]),
// new Edge<object>(vertices[1], vertices[3]),
// new Edge<object>(vertices[3], vertices[4]),
// new Edge<object>(vertices[0], vertices[4]),
// new Edge<object>(vertices[4], vertices[5])
// };
// g.AddVerticesAndEdgeRange(edges);
// OverlapRemovalAlgorithmType = "FSA";
// LayoutAlgorithmType = "FR";
// Graph = g;
//}
}
}
/// <summary>
/// THE layout control. Support layout, edge routing and overlap removal algorithms, with multiple layout states.
/// </summary>
/// <typeparam name="TVertex">Type of the vertices.</typeparam>
/// <typeparam name="TEdge">Type of the edges.</typeparam>
/// <typeparam name="TGraph">Type of the graph.</typeparam>
public partial class GraphLayout<TVertex, TEdge, TGraph> : GraphCanvas
where TVertex : class
where TEdge : IEdge<TVertex>
where TGraph : class, IBidirectionalGraph<TVertex, TEdge>
{
protected readonly Dictionary<TEdge, EdgeControl> _edgeControls = new Dictionary<TEdge, EdgeControl>();
private readonly Queue<TEdge> _edgesAdded = new Queue<TEdge>();
private readonly Queue<TEdge> _edgesRemoved = new Queue<TEdge>();
private readonly List<LayoutState<TVertex, TEdge>> _layoutStates = new List<LayoutState<TVertex, TEdge>>();
private readonly TimeSpan _notificationLayoutDelay = new TimeSpan(0, 0, 0, 0, 5); // 5 ms
private readonly object _notificationSyncRoot = new object();
protected readonly Dictionary<TVertex, VertexControl> _vertexControls = new Dictionary<TVertex, VertexControl>();
private readonly Queue<TVertex> _verticesAdded = new Queue<TVertex>();
private readonly Queue<TVertex> _verticesRemoved = new Queue<TVertex>();
private readonly Stopwatch stopWatch = new Stopwatch();
private DateTime _lastNotificationTimestamp = DateTime.Now;
protected IDictionary<TVertex, Size /*bcz:*/> _sizes;
protected BackgroundWorker _worker;
protected IDictionary<TVertex, Size /*bcz:*/> VertexSizes
{
get
{
if (_sizes == null)
{
InvalidateMeasure();
UpdateLayout();
_sizes = new Dictionary<TVertex, Size /*bcz:*/>();
foreach (var kvp in _vertexControls)
{
var size = kvp.Value.DesiredSize;
_sizes.Add(kvp.Key, new Size /*bcz:*/(
(double.IsNaN(size.Width) ? 0 : (float)size.Width),
(double.IsNaN(size.Height) ? 0 : (float)size.Height)));
}
}
return _sizes;
}
}
#region Layout
protected Algorithms.Layout.LayoutMode ActualLayoutMode
{
get
{
if (LayoutMode == LayoutMode.Compound ||
LayoutMode == LayoutMode.Automatic && Graph != null && Graph is ICompoundGraph<TVertex, TEdge>)
return Algorithms.Layout.LayoutMode.Compound;
return Algorithms.Layout.LayoutMode.Simple;
}
}
protected bool IsCompoundMode
{
get { return ActualLayoutMode == Algorithms.Layout.LayoutMode.Compound; }
}
protected virtual bool CanLayout
{
get { return true; }
}
public override void ContinueLayout()
{
Layout(true);
}
public override void Relayout()
{
//clear the states before
_layoutStates.Clear();
Layout(false);
}
public void CancelLayout()
{
if (_worker != null && _worker.IsBusy && _worker.WorkerSupportsCancellation)
_worker.CancelAsync();
}
public void RecalculateEdgeRouting()
{
foreach (var state in _layoutStates)
state.RouteInfos = RouteEdges(state.OverlapRemovedPositions, GetLatestVertexSizes());
ChangeState(StateIndex);
}
public void RecalculateOverlapRemoval()
{
foreach (var state in _layoutStates)
state.OverlapRemovedPositions = OverlapRemoval(state.Positions, GetLatestVertexSizes());
ChangeState(StateIndex);
}
protected virtual ILayoutContext<TVertex, TEdge, TGraph> CreateLayoutContext(
IDictionary<TVertex, Point> positions, IDictionary<TVertex, Size> sizes)
{
if (!CanLayout)
return null;
//bcz:
//if (ActualLayoutMode == Algorithms.Layout.LayoutMode.Simple)
return new LayoutContext<TVertex, TEdge, TGraph>(Graph, positions, sizes, ActualLayoutMode);
//else
//{
// var borders = (from kvp in _vertexControls
// where kvp.Value is CompoundVertexControl
// select kvp).ToDictionary(
// kvp => kvp.Key,
// kvp => ((CompoundVertexControl)kvp.Value).VertexBorderThickness);
// var layoutTypes = (from kvp in _vertexControls
// where kvp.Value is CompoundVertexControl
// select kvp).ToDictionary(
// kvp => kvp.Key,
// kvp => ((CompoundVertexControl)kvp.Value).LayoutMode);
// return new CompoundLayoutContext<TVertex, TEdge, TGraph>(Graph, positions, sizes, ActualLayoutMode, borders, layoutTypes);
//}
}
protected virtual IHighlightContext<TVertex, TEdge, TGraph> CreateHighlightContext()
{
return new HighlightContext<TVertex, TEdge, TGraph>(Graph);
}
protected virtual IOverlapRemovalContext<TVertex> CreateOverlapRemovalContext(
IDictionary<TVertex, Point> positions, IDictionary<TVertex, Size> sizes)
{
var rectangles = new Dictionary<TVertex, Rect>();
foreach (var vertex in Graph.Vertices)
{
Point position;
Size size;
if (!positions.TryGetValue(vertex, out position) || !sizes.TryGetValue(vertex, out size))
continue;
rectangles[vertex] =
new Rect(
position.X - size.Width * (float)0.5,
position.Y - size.Height * (float)0.5,
size.Width,
size.Height);
}
return new OverlapRemovalContext<TVertex>(rectangles);
}
bool HasBeenLoaded = false; // bcz:
protected virtual void Layout(bool continueLayout)
{
if (Graph == null || Graph.VertexCount == 0 || !LayoutAlgorithmFactory.IsValidAlgorithm(LayoutAlgorithmType) || !CanLayout)
return; //no graph to layout, or wrong layout algorithm
UpdateLayout();
if (!HasBeenLoaded) // bcz this.IsLoaded)
{
RoutedEventHandler handler = null;
var gl = this; // bcz:
handler = new RoutedEventHandler((s, e) =>
{
HasBeenLoaded = true; // bcz:
Layout(continueLayout);
// var gl = (GraphLayout<TVertex, TEdge, TGraph>)e.Source; // bcz:
gl.Loaded -= handler;
});
this.Loaded += handler;
return;
}
//get the actual positions if we want to continue the layout
IDictionary<TVertex, Point> oldPositions = GetOldVertexPositions(continueLayout);
IDictionary<TVertex, Size> oldSizes = GetLatestVertexSizes();
//create the context
var layoutContext = CreateLayoutContext(oldPositions, oldSizes);
//create the layout algorithm using the factory
LayoutAlgorithm = LayoutAlgorithmFactory.CreateAlgorithm(LayoutAlgorithmType, layoutContext,
LayoutParameters);
if (AsyncCompute)
{
//Asynchronous computing - progress report & anything else
//if there's a running progress than cancel that
CancelLayout();
_worker = new BackgroundWorker
{
WorkerSupportsCancellation = true,
WorkerReportsProgress = true
};
//run the algorithm on a background thread
_worker.DoWork += ((sender, e) =>
{
var worker = (BackgroundWorker)sender;
var argument = (AsyncThreadArgument)e.Argument;
if (argument.showAllStates)
argument.algorithm.IterationEnded +=
((s, args) =>
{
var iterArgs = args;
if (iterArgs != null)
{
worker.ReportProgress(
(int)Math.Round(iterArgs.StatusInPercent), iterArgs);
iterArgs.Abort = worker.CancellationPending;
}
});
else
argument.algorithm.ProgressChanged +=
((s, percent) => worker.ReportProgress((int)Math.Round(percent)));
argument.algorithm.Compute();
});
//progress changed if an iteration ended
_worker.ProgressChanged +=
((s, e) =>
{
if (e.UserState == null)
LayoutStatusPercent = e.ProgressPercentage;
else
OnLayoutIterationFinished(e.UserState as ILayoutIterationEventArgs<TVertex>);
});
//background thread finished if the iteration ended
_worker.RunWorkerCompleted += ((s, e) =>
{
OnLayoutFinished();
_worker = null;
});
OnLayoutStarted();
_worker.RunWorkerAsync(new AsyncThreadArgument
{
algorithm = LayoutAlgorithm,
showAllStates = ShowAllStates
});
}
else
{
//Syncronous computing - no progress report
LayoutAlgorithm.Started += ((s, e) => OnLayoutStarted());
if (ShowAllStates)
LayoutAlgorithm.IterationEnded += ((s, e) => OnLayoutIterationFinished(e));
LayoutAlgorithm.Finished += ((s, e) => OnLayoutFinished());
LayoutAlgorithm.Compute();
}
}
private IDictionary<TVertex, Point> GetOldVertexPositions(bool continueLayout)
{
if (ActualLayoutMode == GraphSharp.Algorithms.Layout.LayoutMode.Simple)
{
return continueLayout ? GetLatestVertexPositions() : null;
}
else
{
return GetRelativePositions(continueLayout);
}
}
private IDictionary<TVertex, Point> GetLatestVertexPositions()
{
IDictionary<TVertex, Point> vertexPositions = new Dictionary<TVertex, Point>(_vertexControls.Count);
//go through the vertex presenters and get the actual layoutpositions
if (ActualLayoutMode == Algorithms.Layout.LayoutMode.Simple)
{
foreach (var vc in _vertexControls)
{
var x = GetX(vc.Value);
var y = GetY(vc.Value);
vertexPositions[vc.Key] =
new Point(
double.IsNaN(x) ? 0.0 : x,
double.IsNaN(y) ? 0.0 : y);
}
}
else
{
Point topLeft = new Point(0, 0);
foreach (var vc in _vertexControls)
{
var position = vc.Value.TransformToVisual(this).TransformPoint(topLeft); // .TranslatePoint(topLeft, this);
position.X += vc.Value.ActualWidth / 2;
position.Y += vc.Value.ActualHeight / 2;
vertexPositions[vc.Key] = position;
}
}
return vertexPositions;
}
private Point GetRelativePosition(VertexControl vc, UIElement relativeTo)
{
return vc.TransformToVisual(relativeTo).TransformPoint(new Windows.Foundation.Point(vc.ActualWidth / 2.0, vc.ActualHeight / 2.0));// bcz: .TranslatePoint(new Point(vc.ActualWidth / 2.0, vc.ActualHeight / 2.0), relativeTo);
}
private Point GetRelativePosition(VertexControl vc)
{
return GetRelativePosition(vc, this);
}
private IDictionary<TVertex, Point> GetRelativePositions(bool continueLayout)
{
//if layout is continued it gets the relative position of every vertex
//otherwise it's gets it only for the vertices with fixed parents
var posDict = new Dictionary<TVertex, Point>(_vertexControls.Count);
if (continueLayout)
{
foreach (var kvp in _vertexControls)
{
posDict[kvp.Key] = GetRelativePosition(kvp.Value);
}
}
else
{
// bcz:
//foreach (var kvp in _vertexControls)
//{
// if (!(kvp.Value is CompoundVertexControl))
// continue;
// var cvc = (CompoundVertexControl)kvp.Value;
// foreach (var vc in cvc.Vertices)
// {
// posDict[(TVertex)vc.Vertex] = GetRelativePosition(vc, cvc);
// }
//}
}
return posDict;
}
private IDictionary<TVertex, Size> GetLatestVertexSizes()
{
// if (!IsMeasureValid) // bcz:
Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
IDictionary<TVertex, Size> vertexSizes =
new Dictionary<TVertex, Size>(_vertexControls.Count);
//go through the vertex presenters and get the actual layoutpositions
foreach (var vc in _vertexControls)
vertexSizes[vc.Key] = new Size(vc.Value.ActualWidth, vc.Value.ActualHeight);
return vertexSizes;
}
protected void OnLayoutStarted()
{
stopWatch.Reset();
stopWatch.Start();
LayoutStatusPercent = 0.0;
}
protected virtual void OnLayoutIterationFinished(ILayoutIterationEventArgs<TVertex> iterArgs)
{
if (iterArgs == null || iterArgs.VertexPositions == null)
{
if (LayoutAlgorithm is ICompoundLayoutAlgorithm<TVertex, TEdge, TGraph>)
{
var la = (ICompoundLayoutAlgorithm<TVertex, TEdge, TGraph>)LayoutAlgorithm;
}
else
{
}
OnLayoutIterationFinished(LayoutAlgorithm.VertexPositions, null);
SetLayoutInformations();
}
else
{
//TODO compound layout
OnLayoutIterationFinished(iterArgs.VertexPositions, iterArgs.Message);
LayoutStatusPercent = iterArgs.StatusInPercent;
SetLayoutInformations(iterArgs as ILayoutInfoIterationEventArgs<TVertex, TEdge>);
}
}
protected virtual void OnLayoutIterationFinished(
IDictionary<TVertex, Point> vertexPositions,
string message)
{
var sizes = GetLatestVertexSizes();
var overlapRemovedPositions = OverlapRemoval(vertexPositions, sizes);
var edgeRoutingInfos = RouteEdges(overlapRemovedPositions, sizes);
var state = new LayoutState<TVertex, TEdge>(
vertexPositions,
overlapRemovedPositions,
edgeRoutingInfos,
stopWatch.Elapsed,
_layoutStates.Count,
(message ?? string.Empty));
_layoutStates.Add(state);
StateCount = _layoutStates.Count;
}
protected virtual void OnLayoutFinished()
{
stopWatch.Stop();
OnLayoutIterationFinished(null);
StateIndex = StateCount - 1;
//animating to the finish state
if (StateIndex == 0)
ChangeState(StateIndex);
LayoutStatusPercent = 100;
}
private void SetLayoutInformations(ILayoutInfoIterationEventArgs<TVertex, TEdge> iterArgs)
{
if (iterArgs == null)
return;
foreach (var kvp in _vertexControls)
{
var vertex = kvp.Key;
var control = kvp.Value;
GraphElementBehaviour.SetLayoutInfo(control, iterArgs.GetVertexInfo(vertex));
}
foreach (var kvp in _edgeControls)
{
var edge = kvp.Key;
var control = kvp.Value;
GraphElementBehaviour.SetLayoutInfo(control, iterArgs.GetEdgeInfo(edge));
}
}
private void SetLayoutInformations()
{
if (LayoutAlgorithm == null)
return;
foreach (var kvp in _vertexControls)
{
var vertex = kvp.Key;
var control = kvp.Value;
GraphElementBehaviour.SetLayoutInfo(control, LayoutAlgorithm.GetVertexInfo(vertex));
}
foreach (var kvp in _edgeControls)
{
var edge = kvp.Key;
var control = kvp.Value;
GraphElementBehaviour.SetLayoutInfo(control, LayoutAlgorithm.GetEdgeInfo(edge));
}
}
protected IDictionary<TVertex, Point> OverlapRemoval(IDictionary<TVertex, Point> positions,
IDictionary<TVertex, Size> sizes)
{
if (positions == null || sizes == null)
return positions; //not valid positions or sizes
bool isValidAlgorithm = OverlapRemovalAlgorithmFactory.IsValidAlgorithm(OverlapRemovalAlgorithmType);
if (OverlapRemovalConstraint == AlgorithmConstraints.Skip
||
(OverlapRemovalConstraint == AlgorithmConstraints.Automatic &&
(!LayoutAlgorithmFactory.NeedOverlapRemoval(LayoutAlgorithmType) || !isValidAlgorithm))
|| (OverlapRemovalConstraint == AlgorithmConstraints.Must && !isValidAlgorithm))
return positions;
//create the algorithm parameters based on the old parameters
OverlapRemovalParameters = OverlapRemovalAlgorithmFactory.CreateParameters(OverlapRemovalAlgorithmType,
OverlapRemovalParameters);
//create the context - rectangles, ...
var context = CreateOverlapRemovalContext(positions, sizes);
//create the concreate algorithm
OverlapRemovalAlgorithm = OverlapRemovalAlgorithmFactory.CreateAlgorithm(OverlapRemovalAlgorithmType,
context, OverlapRemovalParameters);
if (OverlapRemovalAlgorithm != null)
{
OverlapRemovalAlgorithm.Compute();
var result = new Dictionary<TVertex, Point>();
foreach (var res in OverlapRemovalAlgorithm.Rectangles)
{
result[res.Key] = new Point(
(res.Value.Left + res.Value.Size.Width * 0.5),
(res.Value.Top + res.Value.Size.Height * 0.5));
}
return result;
}
return positions;
}
/// <summary>
/// This method runs the proper edge routing algorithm.
/// </summary>
/// <param name="positions">The vertex positions.</param>
/// <param name="sizes">The sizes of the vertices.</param>
/// <returns>The routes of the edges.</returns>
protected IDictionary<TEdge, Point[]> RouteEdges(IDictionary<TVertex, Point> positions,
IDictionary<TVertex, Size> sizes)
{
IEdgeRoutingAlgorithm<TVertex, TEdge, TGraph> algorithm = null;
bool isValidAlgorithmType = EdgeRoutingAlgorithmFactory.IsValidAlgorithm(EdgeRoutingAlgorithmType);
if (EdgeRoutingConstraint == AlgorithmConstraints.Must && isValidAlgorithmType)
{
//an EdgeRouting algorithm must be used
EdgeRoutingParameters = EdgeRoutingAlgorithmFactory.CreateParameters(EdgeRoutingAlgorithmType,
EdgeRoutingParameters);
var context = CreateLayoutContext(positions, sizes);
algorithm = EdgeRoutingAlgorithmFactory.CreateAlgorithm(EdgeRoutingAlgorithmType, context,
EdgeRoutingParameters);
algorithm.Compute();
}
else if (EdgeRoutingConstraint == AlgorithmConstraints.Automatic)
{
if (!LayoutAlgorithmFactory.NeedEdgeRouting(LayoutAlgorithmType) &&
LayoutAlgorithm is IEdgeRoutingAlgorithm<TVertex, TEdge, TGraph>)
//the layout algorithm routes the edges
algorithm = LayoutAlgorithm as IEdgeRoutingAlgorithm<TVertex, TEdge, TGraph>;
else if (isValidAlgorithmType)
{
//the selected EdgeRouting algorithm will route the edges
EdgeRoutingParameters = EdgeRoutingAlgorithmFactory.CreateParameters(EdgeRoutingAlgorithmType,
EdgeRoutingParameters);
var context = CreateLayoutContext(positions, sizes);
algorithm = EdgeRoutingAlgorithmFactory.CreateAlgorithm(EdgeRoutingAlgorithmType, context,
EdgeRoutingParameters);
algorithm.Compute();
}
}
if (algorithm == null)
return null;
//route the edges
return algorithm.EdgeRoutes;
}
/// <summary>
/// Changes which layout state should be shown.
/// </summary>
/// <param name="stateIndex">The index of the shown layout state.</param>
protected void ChangeState(int stateIndex)
{
var activeState = _layoutStates[stateIndex];
LayoutState = activeState;
var positions = activeState.OverlapRemovedPositions;
//Animate the vertices
if (positions != null)
{
Point pos;
foreach (var v in Graph.Vertices)
{
VertexControl vp;
if (!_vertexControls.TryGetValue(v, out vp))
continue;
if (positions.TryGetValue(v, out pos))
RunMoveAnimation(vp, pos.X, pos.Y);
}
}
//Change the edge routes
if (activeState.RouteInfos != null)
{
foreach (var e in Graph.Edges)
{
EdgeControl ec;
if (!_edgeControls.TryGetValue(e, out ec))
continue;
Point[] routePoints;
activeState.RouteInfos.TryGetValue(e, out routePoints);
ec.RoutePoints = routePoints;
}
}
}
public void RefreshHighlight()
{
//TODO doit
}
private class AsyncThreadArgument
{
public ILayoutAlgorithm<TVertex, TEdge, TGraph> algorithm;
public bool showAllStates;
}
#endregion
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.